CentOS环境负载均衡实操指南
一、方案选型与适用场景
二、快速上手 Nginx 负载均衡
sudo yum install -y epel-release && sudo yum install -y nginxsudo systemctl start nginx && sudo systemctl enable nginxhttp {
upstream backend {
server 192.168.1.101:80;
server 192.168.1.102:80;
}
server {
listen 80;
server_name 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;
}
}
}
max_fails=3 fail_timeout=10s,失败超过阈值后暂时剔除。location /nginx_status {
stub_status;
access_log off;
allow 127.0.0.1;
deny all;
}
sudo firewall-cmd --permanent --add-port=80/tcp && sudo firewall-cmd --reload三、HAProxy 负载均衡配置
sudo yum install -y haproxysudo systemctl start haproxy && sudo systemctl enable haproxyglobal
log /dev/log local0
log /dev/log local1 notice
maxconn 4096
tune.ssl.default-dh-param 2048
defaults
log global
mode http
option httplog
option dontlognull
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
frontend http-in
bind *:80
default_backend servers
backend servers
balance roundrobin
server server1 192.168.1.101:80 check
server server2 192.168.1.102:80 check
sudo firewall-cmd --permanent --add-port=80/tcp && sudo firewall-cmd --reload四、LVS 四层负载均衡与高可用
sudo yum install -y ipvsadm keepalivedecho "1" > /proc/sys/net/ipv4/ip_forwardsudo ipvsadm -A -t 192.168.1.100:80 -s rr
sudo ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.101:80 -g
sudo ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.102:80 -g
vrrp_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 { 192.168.1.100 }
}
state 设为 BACKUP,priority 设低(如 90),其余一致。sudo systemctl start keepalived五、生产实践与优化要点
max_fails/fail_timeout 实现被动健康检查;必要时结合主动健康检查与监控告警。check,结合 inter/rise/fall 精细控制摘除与恢复策略。