Ubuntu实现负载均衡的实用方案
一、方案总览与选型
二、快速上手示例
示例一 Nginx 七层负载均衡(HTTP)
upstream backend {
least_conn;
server 10.0.1.11:80 max_fails=3 fail_timeout=30s;
server 10.0.1.12:80 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
示例二 HAProxy 四层/七层负载均衡
global
log /dev/log local0
daemon
maxconn 4096
defaults
log global
mode http
timeout connect 5s
timeout client 50s
timeout server 50s
frontend http-in
bind *:80
default_backend web-backend
backend web-backend
balance roundrobin
option httpchk GET /health
server web1 10.0.1.11:80 check
server web2 10.0.1.12:80 check
三、高可用部署模式
LVS + Keepalived(四层 + VIP 漂移)
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 120
advert_int 1
authentication { auth_type PASS; auth_pass 1111 }
virtual_ipaddress { 192.168.226.150 }
}
virtual_server 192.168.226.150 80 {
delay_loop 6
lb_algo wrr
lb_kind DR
protocol TCP
real_server 10.0.1.11 80 { weight 1; TCP_CHECK { connect_timeout 8; retry 3; } }
real_server 10.0.1.12 80 { weight 1; TCP_CHECK { connect_timeout 8; retry 3; } }
}
Nginx/HAProxy + Keepalived(七层 + VIP 漂移)
#!/usr/bin/env bash
curl -f http://127.0.0.1/health || exit 1
四、生产优化与排障要点
五、常见误区与建议