用 HAProxy 搭建 Web 集群(负载均衡),核心是把用户请求分发到多台后端 Web 服务器,提升并发与可用性。下面是完整、可直接复制的实战步骤(CentOS/RHEL 环境)。
一、环境规划(示例)
HAProxy 负载均衡器:192.168.1.100(CentOS 7/8/9)
Web 服务器 1(Nginx):192.168.1.101
Web 服务器 2(Nginx):192.168.1.102
所有机器关闭防火墙、SELinux(测试环境)
二、步骤 1:配置后端 Web 服务器(两台都做)
bash
运行
1. 安装 Nginx
yum install -y nginx
2. 创建区分页面(方便测试负载均衡)
Web1 (101):
echo "<h1>Web Server 1 (192.168.1.101)</h1>" > /usr/share/nginx/html/index.html
Web2 (102):
echo "<h1>Web Server 2 (192.168.1.102)</h1>" > /usr/share/nginx/html/index.html
3. 启动并开机自启
systemctl start nginx
systemctl enable nginx
三、步骤 2:在 192.168.1.100 安装与配置 HAProxy
- 安装 HAProxy
bash
运行
yum install -y haproxy
或 dnf install haproxy -y (CentOS 8+/RHEL 8+)
- 备份并编辑配置(关键)
bash
运行
cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak
vim /etc/haproxy/haproxy.cfg
完整可用配置(直接替换):
ini
global
log 127.0.0.1 local3 info
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
user haproxy
group haproxy
daemon
maxconn 4096
defaults
mode http
log global
option httplog
option dontlognull
retries 3
timeout http-request 5s
timeout queue 1m
timeout connect 5s
timeout client 1m
timeout server 1m
maxconn 2048
监听 80 端口,Web 集群
listen web_cluster
bind 0.0.0.0:80
option httpchk GET /index.html # HTTP 健康检查
balance roundrobin # 轮询算法
server web1 192.168.1.101:80 check inter 2000 fall 3 rise 2
server web2 192.168.1.102:80 check inter 2000 fall 3 rise 2
监控页面(可选,推荐)
listen stats
bind 0.0.0.0:1080
stats enable
stats uri /stats # 访问路径
stats auth admin:Admin@123 # 账号密码
stats refresh 30s # 刷新间隔
- 启动、开机自启、检查配置
bash
运行
检查配置是否正确
haproxy -c -f /etc/haproxy/haproxy.cfg
启动
systemctl start haproxy
systemctl enable haproxy
查看状态
systemctl status haproxy
四、步骤 3:测试负载均衡
浏览器 /curl 访问 HAProxy IP:
bash
运行
curl http://192.168.1.100
多次刷新 / 请求,会交替显示 Server 1 / Server 2(轮询生效)。
查看 HAProxy 监控:
访问:http://192.168.1.100:1080/stats
输入账号:admin / 密码:Admin@123
可看到两台 Web 节点状态、流量、健康检查结果。
五、常用调度算法(balance)
roundrobin:轮询(默认,加权)
leastconn:最小连接数(适合长连接应用)
source:根据客户端 IP 哈希(会话保持)
uri:根据 URL 哈希
url_param:根据 URL 参数哈希
六、健康检查关键参数
check:开启健康检查
inter 2000:检查间隔 2 秒
fall 3:失败 3 次标记为宕机
rise 2:恢复 2 次标记为上线
option httpchk GET /index.html:七层 HTTP 检查
七、高可用扩展(生产必备)
用 Keepalived 给 HAProxy 做双机热备(VIP 漂移)
避免单点故障