haproxy负载均衡集群搭建:Haproxy负载均衡集群搭
很多新手在搭建web服务时,单台服务器扛不住流量,或者一挂就全站瘫痪。Haproxy 是轻量级的高性能负载均衡软件,能帮你把流量分发到多台后端服务器,既提升并发能力又提供故障转移。
本文带你从零开始,亲手搭一个 haproxy 负载均衡集群。
环境准备与软件安装
先准备好两台前端负载节点(假设IP:192.168.1.10 和 192.168.1.11)和至少两台后端Web服务器(IP:192.168.1.20 和 192.168.1.21)。
操作系统推荐 Ubuntu 20.04 或 CentOS 7+。
分别在两台前端节点上安装 haproxy:
# Ubuntu/Debian
sudo apt update && sudo apt install haproxy -y
# CentOS/RHEL
sudo yum install epel-release -y
sudo yum install haproxy -y
安装后检查版本:haproxy -v,能看到版本号说明装好了。
编写核心配置文件
Haproxy 的配置文件是 /etc/haproxy/haproxy.cfg,分为 global(全局设置)、defaults(默认参数)、frontend(前端监听)、backend(后端服务器池)几个段落。
下面是一个适用于集群搭建的示例:
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
frontend web_front
bind *:80
default_backend web_servers
backend web_servers
balance roundrobin
server web1 192.168.1.20:80 check inter 3000 fall 3 rise 2
server web2 192.168.1.21:80 check inter 3000 fall 3 rise 2
关键点说明:
balance roundrobin是轮询算法,每个请求轮流发到后端。check开启健康检查,inter 3000每3秒检查一次,fall 3连续失败3次摘除节点,rise 2连续成功2次重新启用。- 如果想做多节点集群,把第二个前端节点(192.168.1.11)也配成相同配置(注意IP绑定各自地址即可),这就形成了前端集群。
启动服务与验证配置
在每台前端节点上执行:
sudo systemctl restart haproxy
sudo systemctl enable haproxy
检查配置是否正确:haproxy -c -f /etc/haproxy/haproxy.cfg,输出 Configuration file is valid 才安全。
查看进程是否运行:ps aux | grep haproxy。
避坑指南:新手最常见的几个问题
- 端口冲突:haproxy默认监听80,如果本机已有nginx或apache占用了80端口,需要先停掉或修改haproxy的bind端口。
- 后端服务器防火墙:确保前端节点能访问后端服务器的端口(如80),临时测试可以
curl http://192.168.1.20。如果不通,检查后端防火墙或selinux。 - 健康检查失败:后端服务器没有正确响应时,haproxy会自动摘除节点。在配置文件里加上
option httpchk GET /可以让haproxy通过HTTP GET请求检查后端,而不是简单的TCP连接检测。 - 日志不显示:默认haproxy日志走rsyslog,要开启UDP接收。编辑
/etc/rsyslog.conf,取消注释$ModLoad imudp和$UDPServerRun 514,然后重启rsyslog和haproxy。
效果验证:确认负载均衡集群正常工作
先在后端服务器上创建不同的测试页面(比如web1显示“Server 1”,web2显示“Server 2”),方便区分。
然后从客户端访问任意前端节点的IP:
curl http://192.168.1.10
多执行几次,你会交替看到 Server 1 和 Server 2 的内容,说明轮询生效。
模拟故障:停掉 web1 上的服务(sudo systemctl stop nginx),再次访问,应该始终只返回 Server 2。
恢复 web1 后,等待健康检查通过(约6秒),访问又会交替出现。
查看 haproxy 统计页面能直观看到节点状态。
在配置文件 frontend 段添加:
stats enable
stats uri /haproxy-stats
stats auth admin:yourpassword
重启后浏览器访问 http://前端IP/haproxy-stats,输入用户名密码,就能看到每个后端节点的当前状态、连接数、健康检查结果。
如果你正在处理haproxy负载均衡集群搭建,建议先按本文步骤完整执行,再根据自己的环境做微调;
遇到异常时优先回看避坑和高频问题部分。
掌握了这些,你已经具备在生产环境中部署高可用负载均衡的基础能力。