在Linux环境下实现服务发现和负载均衡是构建可扩展、高可用系统的关键。以下是几种常用的实现方案:
bash
# dnsmasq配置示例
address=/service.example.com/192.168.1.100,192.168.1.101,192.168.1.102
Consul
# 安装Consul
wget https://releases.hashicorp.com/consul/1.10.0/consul_1.10.0_linux_amd64.zip
unzip consul_1.10.0_linux_amd64.zip
sudo mv consul /usr/local/bin/
# 启动Consul agent
consul agent -dev -client=0.0.0.0
etcd
# 安装etcd
wget https://github.com/etcd-io/etcd/releases/download/v3.5.0/etcd-v3.5.0-linux-amd64.tar.gz
tar xzvf etcd-v3.5.0-linux-amd64.tar.gz
cd etcd-v3.5.0-linux-amd64
./etcd
Zookeeper
# 安装Zookeeper
wget https://archive.apache.org/dist/zookeeper/zookeeper-3.6.3/apache-zookeeper-3.6.3-bin.tar.gz
tar xzvf apache-zookeeper-3.6.3-bin.tar.gz
cd apache-zookeeper-3.6.3-bin
cp conf/zoo_sample.cfg conf/zoo.cfg
./bin/zkServer.sh start
# 安装Nginx
sudo apt install nginx # Ubuntu/Debian
sudo yum install nginx # CentOS/RHEL
# 配置负载均衡
sudo vi /etc/nginx/conf.d/load-balancer.conf
upstream backend {
server 192.168.1.100:8080;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
# 负载均衡算法
# least_conn; # 最少连接
# ip_hash; # IP哈希
# 默认是轮询
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
# 安装HAProxy
sudo apt install haproxy # Ubuntu/Debian
sudo yum install haproxy # CentOS/RHEL
# 配置示例
sudo vi /etc/haproxy/haproxy.cfg
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server server1 192.168.1.100:8080 check
server server2 192.168.1.101:8080 check
server server3 192.168.1.102:8080 check
# 安装ipvsadm
sudo apt install ipvsadm # Ubuntu/Debian
sudo yum install ipvsadm # CentOS/RHEL
# 配置示例
sudo ipvsadm -A -t 192.168.1.200:80 -s rr
sudo ipvsadm -a -t 192.168.1.200:80 -r 192.168.1.100:8080 -g
sudo ipvsadm -a -t 192.168.1.200:80 -r 192.168.1.101:8080 -g
sudo ipvsadm -a -t 192.168.1.200:80 -r 192.168.1.102:8080 -g
# 创建Kubernetes服务
kubectl expose deployment my-app --port=8080 --target-port=80 --type=LoadBalancer
# docker-compose.yml示例
version: '3'
services:
traefik:
image: traefik:v2.4
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
command:
- --api.insecure=true
- --providers.docker=true
- --entrypoints.web.address=:80
whoami:
image: containous/whoami
labels:
- "traefik.http.routers.whoami.rule=Host(`whoami.example.com`)"
upstream backend {
server 192.168.1.100:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.101:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.102:8080 max_fails=3 fail_timeout=30s;
}
backend http_back
option httpchk GET /health
http-check expect status 200
server server1 192.168.1.100:8080 check
server server2 192.168.1.101:8080 check
server server3 192.168.1.102:8080 check
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
listen stats
bind *:9000
stats enable
stats uri /haproxy?stats
stats realm HAProxy\ Statistics
stats auth admin:password
以上方案可根据实际业务需求和技术栈选择组合使用,构建适合您系统的服务发现和负载均衡架构。