在 CentOS 上从零实现负载均衡
一、方案总览与准备
二、方案一 HAProxy 快速落地(L4/L7 通用)
yum install -y haproxysystemctl start haproxy && systemctl enable haproxyglobal
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
tune.ssl.default-dh-param 2048
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server web1 10.0.0.2:80 check
server web2 10.0.0.3:80 check
listen stats
bind *:8080
stats enable
stats uri /stats
stats refresh 30s
stats auth admin:StrongPass@2025
stats admin if TRUE
local2 日志接入 rsyslog(/etc/rsyslog.d/haproxy.conf):local2.* /var/log/haproxy.log,重启 rsyslog。firewall-cmd --permanent --add-service=http && firewall-cmd --permanent --add-port=8080/tcp && firewall-cmd --reloadhaproxy -f /etc/haproxy/haproxy.cfg -csystemctl reload haproxyhttp://10.0.0.10/(轮询到 web1/web2)http://10.0.0.10:8080/stats(账号 admin / StrongPass@2025)三、方案二 Nginx 实现负载均衡(HTTP 反向代理)
yum install -y epel-release && yum install -y nginxsystemctl start nginx && systemctl enable nginxupstream backend_servers {
server 10.0.0.2:80;
server 10.0.0.3:80;
}
server {
listen 80;
server_name _;
location / {
proxy_pass http://backend_servers;
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;
}
}
nginx -t && systemctl reload nginxhttp://<LB_IP>/,请求将在 web1/web2 之间分发四、高可用与扩展
yum install -y keepalivedvrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass YourPass
}
virtual_ipaddress {
10.0.0.100/24
}
}
state 改为 BACKUP,priority 设为 90systemctl start keepalived && systemctl enable keepalivedip addr show eth0 应看到 VIP 10.0.0.100 在主节点;故障切换后漂移到备节点yum install -y ipvsadm keepalivedvrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication { auth_type PASS; auth_pass YourPass }
virtual_ipaddress { 10.0.0.100/24 }
}
virtual_server 10.0.0.100 80 {
delay_loop 6
lb_algo rr
lb_kind DR
protocol TCP
real_server 10.0.0.2 80 {
weight 1
TCP_CHECK { connect_timeout 10 connect_port 80 }
}
real_server 10.0.0.3 80 {
weight 1
TCP_CHECK { connect_timeout 10 connect_port 80 }
}
}
systemctl start keepalived 生效五、验证与常见问题
curl 与 HAProxy stats/Nginx 页面应自动剔除异常节点cookie 或 source 策略;Nginx 可用 ip_hashsetenforce 0 或配置策略放行)X-Forwarded-For,导致源 IP 丢失