HAProxy 是一款高性能的开源负载均衡器和反向代理软件,同时支持 四层(TCP) 和 七层(HTTP) 负载均衡。
一、核心概念对比
| 特性 | 四层负载均衡(Layer 4) | 七层负载均衡(Layer 7) |
|---|---|---|
| 工作层级 | TCP/UDP 传输层 | HTTP/HTTPS 应用层 |
| 转发依据 | IP + 端口 | URL、Cookie、请求头等 |
| 性能 | 更高(不解析应用层内容) | 稍低(需解析 HTTP 报文) |
| 适用场景 | 数据库、邮件、TLS 直通 | Web 服务、API 网关 |
| 健康检查 | TCP 连接检测 | HTTP 状态码/内容检测 |
| 会话保持 | Source IP 哈希 | Cookie 插入、IP 哈希 |
二、四层(TCP)负载均衡配置
四层模式下,HAProxy 只做 IP+端口转发,不解析应用层协议内容。
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
maxconn 4000
defaults
log global
mode tcp # 四层模式
option tcplog
option dontlognull
retries 3
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend tcp_frontend
bind *:3306 # 监听 MySQL 默认端口
default_backend tcp_servers
backend tcp_servers
balance roundrobin # 轮询算法
server db1 192.168.1.10:3306 check inter 2000 fall 3 rise 5
server db2 192.168.1.11:3306 check inter 2000 fall 3 rise 5
server db_backup 192.168.1.12:3306 backup
关键参数说明:
mode tcp:声明为四层负载均衡balance roundrobin:轮询分配请求check:启用健康检查inter 2000:健康检查间隔 2 秒fall 3:连续 3 次失败标记为 DOWNrise 5:连续 5 次成功标记为 UPbackup:仅在其他服务器全部不可用时启用
三、七层(HTTP)负载均衡配置
七层模式下,HAProxy 可以解析 HTTP 报文,实现基于 URL、Host、Cookie 等内容的精细路由。
global
log /dev/log local0
maxconn 4000
daemon
defaults
log global
mode http # 七层模式
option httplog
option dontlognull
retries 3
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
# ============ 前端配置 ============
frontend http_frontend
bind *:80
mode http
# 定义 ACL 规则
acl is_api path_beg /api
acl is_static path_beg /static
acl is_ws hdr(Upgrade) -i websocket
# 根据 ACL 规则路由到不同后端
use_backend api_servers if is_api
use_backend static_servers if is_static
use_backend ws_servers if is_ws
# 默认后端
default_backend web_servers
# ============ 后端配置 ============
backend web_servers
mode http
balance leastconn # 最少连接数算法
option httpchk GET /health
http-check expect status 200
cookie SERVERID insert indirect nocache # Cookie 会话保持
server web1 192.168.1.10:80 check inter 2s fall 3 rise 5 weight 1 cookie web1
server web2 192.168.1.11:80 check inter 2s fall 3 rise 5 weight 1 cookie web2
backend api_servers
mode http
balance roundrobin
option httpchk GET /api/health
http-check expect status 200
server api1 192.168.1.20:8080 check
server api2 192.168.1.21:8080 check
backend static_servers
mode http
balance roundrobin
server static1 192.168.1.30:80 check
server static2 192.168.1.31:80 check
backend ws_servers
mode http
balance source # Source IP 哈希,保证 WebSocket 粘性
server ws1 192.168.1.40:8080 check
server ws2 192.168.1.41:8080 check
# ============ 监控面板 ============
listen stats
bind *:9000
stats enable
stats uri /haproxy
stats auth admin:password123
stats refresh 5s
七层关键特性说明:
acl is_api path_beg /api:匹配以/api开头的请求路径use_backend ... if ...:根据 ACL 规则转发option httpchk GET /health:HTTP 健康检查,请求/health接口http-check expect status 200:期望返回 200 状态码cookie SERVERID insert indirect nocache:自动插入 Cookie 实现会话保持balance source:基于源 IP 哈希,同一客户端始终转发到同一后端
四、负载均衡算法对比
| 算法 | 配置指令 | 适用场景 | 优缺点 |
|---|---|---|---|
| 轮询 | balance roundrobin | 后端性能均衡的 Web 服务 | 简单均匀,不考虑后端负载 |
| 最少连接 | balance leastconn | 长连接场景(数据库/WebSocket) | 动态适应负载,有额外计算开销 |
| Source IP 哈希 | balance source | 需要会话保持的无状态服务 | 同一客户端固定后端,负载可能不均 |
| URI 哈希 | balance uri | CDN/缓存场景 | 提高缓存命中率 |
| 一致性哈希 | balance uri + hash-type consistent | 后端动态扩缩容 | 后端变动时影响最小 |
五、HAProxy + Keepalived 高可用配置
Keepalived 通过 VRRP 协议在主备节点之间漂移虚拟 IP(VIP),实现 HAProxy 的高可用,避免单点故障。
1.架构拓扑
Client
│
VIP: 192.168.1.100
│
┌──────────┴──────────┐
│ │
HAProxy Master HAProxy Backup
192.168.1.11 192.168.1.12
│ │
└──────────┬──────────┘
│
Backend Servers
2.环境准备
| 节点角色 | 主机名 | IP 地址 | 说明 |
|---|---|---|---|
| Master | lb01 | 192.168.1.11 | 主负载均衡器 |
| Backup | lb02 | 192.168.1.12 | 备负载均衡器 |
| VIP | — | 192.168.1.100 | 漂移虚拟 IP |
两台节点均需安装 HAProxy 和 Keepalived:
yum install -y haproxy keepalived # CentOS/RHEL
# apt install -y haproxy keepalived # Debian/Ubuntu
3.系统参数配置(两台节点都执行)
# 开启 IP 转发
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
# 允许绑定非本地 IP(VIP)
echo "net.ipv4.ip_nonlocal_bind = 1" >> /etc/sysctl.conf
sysctl -p
4.HAProxy 配置(两台节点相同)
global
log /dev/log local0
maxconn 4000
daemon
defaults
log global
mode http
option httplog
retries 3
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
option httpchk GET /
server web1 192.168.1.20:80 check inter 2s fall 3 rise 5
server web2 192.168.1.21:80 check inter 2s fall 3 rise 5
listen stats
bind *:9000
stats enable
stats uri /haproxy
stats auth admin:password123
将配置同步到两台节点:
scp /etc/haproxy/haproxy.cfg lb02:/etc/haproxy/
5.Keepalived 配置
Master 节点(lb01) /etc/keepalived/keepalived.conf:
global_defs {
router_id lb01
}
# HAProxy 进程检测脚本
vrrp_script chk_haproxy {
script "/usr/bin/killall -0 haproxy"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0 # 根据实际网卡名修改
virtual_router_id 51 # 主备必须相同
priority 100 # 主节点优先级 > 备节点
advert_int 1
authentication {
auth_type PASS
auth_pass 123456 # 主备必须相同
}
virtual_ipaddress {
192.168.1.100/24 # VIP 地址
}
track_script {
chk_haproxy # 关联健康检查脚本
}
}
Backup 节点(lb02) /etc/keepalived/keepalived.conf:
global_defs {
router_id lb02
}
vrrp_script chk_haproxy {
script "/usr/bin/killall -0 haproxy"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51 # 与 Master 相同
priority 90 # 低于 Master 的 100
advert_int 1
authentication {
auth_type PASS
auth_pass 123456 # 与 Master 相同
}
virtual_ipaddress {
192.168.1.100/24
}
track_script {
chk_haproxy
}
}
6.启动与验证
# 检查 HAProxy 配置语法
haproxy -c -f /etc/haproxy/haproxy.cfg
# 两台节点分别启动服务
systemctl enable haproxy keepalived --now
# 在 Master 上验证 VIP 绑定
ip addr show eth0
# 应看到 192.168.1.100 已绑定
# 模拟故障:停止 Master 的 HAProxy
systemctl stop haproxy
# 等待几秒后,在 Backup 上检查 VIP 是否漂移过来
ip addr show eth0
# 恢复后 VIP 应自动漂回 Master
systemctl start haproxy
工作原理
- Master 节点持有 VIP,所有客户端流量通过 VIP 进入 Master 的 HAProxy
- Keepalived 每 2 秒执行
killall -0 haproxy检测 HAProxy 进程 - 若 Master 的 HAProxy 宕机或 Master 整机故障,VRRP 协议触发 VIP 漂移
- Backup 节点自动接管 VIP,客户端无感知切换
- Master 恢复后,VIP 自动漂回(因 Master 优先级更高)
六、配置验证与排错
# 检查 HAProxy 配置语法
haproxy -c -f /etc/haproxy/haproxy.cfg
# 平滑重载配置(不中断现有连接)
systemctl reload haproxy
# 查看实时日志
tail -f /var/log/haproxy.log
# 测试不同路径转发
curl -v http://192.168.1.100/api/test
curl -v http://192.168.1.100/static/image.png
# 查看 VIP 绑定情况
ip addr show | grep 192.168.1.100
# 前台运行(调试模式,输出详细连接和请求信息)
haproxy -d -f /etc/haproxy/haproxy.cfg
# 前台运行但不进入后台(方便 Ctrl+C 停止)
haproxy -db -f /etc/haproxy/haproxy.cfg
# 实时查看日志
tail -f /var/log/haproxy.log
# 过滤错误日志
tail -f /var/log/haproxy.log | grep -i error
常见注意事项:
- ACL 规则按顺序匹配,前面的优先级高,注意规则顺序
- 路径匹配默认大小写敏感,
/api和/API不同- 四层模式下无法使用
httpchk,只能用 TCP 连接检测- 七层模式下后端服务器看到的源 IP 是 HAProxy 的 IP,需通过
X-Forwarded-For头传递真实客户端 IP

1622

被折叠的 条评论
为什么被折叠?



