Linux 负载均衡与高可用网络架构实战
一、负载均衡原理与架构选型
核心作用:
- 流量分发(Round-Robin、Least Connections 等)
常见模式:
- 四层(L4):传输层(TCP/UDP),性能高 → LVS
- 七层(L7):应用层(HTTP/HTTPS),灵活 → Nginx / HAProxy
架构类型:
二、LVS(Linux Virtual Server)四层负载均衡
安装:
apt install ipvsadm keepalived # 或 yum
modprobe ip_vs
IPVS 管理:
ipvsadm -A -t 192.168.10.100:80 -s rr # 添加虚拟服务器
ipvsadm -a -t 192.168.10.100:80 -r 192.168.10.11:80 -m -w 1 # 添加 Real Server(NAT 模式)
ipvsadm -Ln
DR 模式(高性能):
- Director 与 Real Server 同网段
- Real Server 设置 VIP(lo:0 接口,arp_ignore=1)
Real Server 配置(/etc/sysctl.conf):
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
VIP 配置:
ip addr add 192.168.10.100/32 dev lo
三、Nginx 七层负载均衡
配置示例(/etc/nginx/nginx.conf):
http { upstream backend { least_conn; # 最少连接 server backend1.example.com:8080 weight=5 max_fails=3 fail_timeout=30s; server backend2.example.com:8080 weight=5; keepalive 32; } server { listen 80; server_name lb.example.com; location / { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; health_check; # 需要 ngx_http_upstream_healthcheck_module } } }
Session 保持:ip_hash 或 sticky cookie。
TLS 终结:Nginx 处理 HTTPS,减轻后端压力。
四、HAProxy 配置示例
优点:统计丰富、配置灵活。
frontend http-in bind *:80 acl is_health path /health use_backend health if is_health default_backend webservers backend webservers balance roundrobin option httpchk GET /health server web1 192.168.10.11:80 check maxconn 1000 server web2 192.168.10.12:80 check maxconn 1000
五、高可用方案:Keepalived + VRRP
Keepalived 配置(/etc/keepalived/keepalived.conf):
vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 100 # Backup 设 90 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.10.100/24 } } virtual_server 192.168.10.100 80 { delay_loop 10 lb_algo rr lb_kind DR persistence_timeout 3600 protocol TCP real_server 192.168.10.11 80 { weight 1 TCP_CHECK { connect_timeout 3 } } }
双主热备:两个节点互为主备。
六、生产调优、监控与故障处理
性能调优:
- 调整
net.core.somaxconn、tcp_max_syn_backlog(第五篇) - Nginx worker_processes = CPU 核数
监控:
ipvsadm -Ln
nginx -V
echo"GET /status" | nc localhost 8080 # HAProxy stats
Prometheus:node_exporter + blackbox + nginx_exporter + keepalived_exporter。
常见故障:
- VIP 漂移失败:VRRP 优先级、认证不一致、防火墙挡 multicast。
- 性能瓶颈:单节点 LVS 极限 → 结合 Anycast 或多层 LB。
排查:
- Keepalived 日志:
journalctl -u keepalived
七、云原生与进阶架构
- Kubernetes:Ingress(Nginx / Traefik)、MetalLB(裸金属 LB)、Service LB。
- 云厂商:ALB/NLB + Auto Scaling。
- 全局负载:DNS + AnyCast + GSLB。
最佳实践: