13.1.5 行业最佳实践与常见部署形态
在生产环境中,HAProxy常作为四层/七层统一入口与流量治理核心,最佳实践强调“标准化配置、可观测性、弹性扩展与故障自愈”。建议采用分层架构:公网入口(SSL终止/HTTP路由)+内网应用集群(TCP/HTTP)+数据库中间层(ProxySQL/MySQL读写分离),并通过统一的配置模板、版本控制与灰度发布降低变更风险。
原理草图(典型分层形态)
常见部署形态与示例#
1) 双机热备 + VIP(Keepalived)#
适用:中小规模、运维复杂度低
示例配置:HAProxy + Keepalived 主备切换
/etc/haproxy/haproxy.cfg(精简可运行)
global
log /dev/log local0
maxconn 20000
daemon
defaults
log global
mode http
timeout connect 5s
timeout client 30s
timeout server 30s
frontend fe_http
bind *:80
default_backend be_web
backend be_web
balance roundrobin
option httpchk GET /health
server web1 10.0.0.11:8080 check
server web2 10.0.0.12:8080 check
/etc/keepalived/keepalived.conf(主节点示例)
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 {
10.0.0.100/24
}
}
校验命令
haproxy -c -f /etc/haproxy/haproxy.cfg # 配置语法检查
systemctl restart haproxy # 重启生效
ip a | grep 10.0.0.100 # 验证VIP是否漂移
curl -I http://10.0.0.100/health # 验证后端健康
预期效果:主机故障时VIP漂移到备机,访问不中断或短暂闪断。
2) 多活集群 + DNS/GSLB#
适用:多地域、高可用、跨地域容灾
示例:DNS轮询两地HAProxy
/etc/haproxy/haproxy.cfg(站点A/B通用)
frontend fe_http
bind *:80
default_backend be_web
backend be_web
balance leastconn
server web1 10.1.0.11:8080 check
server web2 10.1.0.12:8080 check
DNS记录示例(逻辑)
www.example.com A 203.0.113.10 ; 站点A
www.example.com A 203.0.113.20 ; 站点B
排错提示:
- 若某地不可达,先检查站点出口与健康检查接口是否可访问:
curl -I http://203.0.113.10/health
- 若DNS未切换,检查TTL是否过高。
3) 四层入口 + 七层网关组合#
适用:高吞吐 + 灵活路由
示例:入口TCP转发到L7网关
# 入口L4
frontend fe_tcp
bind *:443
mode tcp
default_backend be_l7
backend be_l7
mode tcp
balance roundrobin
server gw1 10.0.0.21:8443 check
server gw2 10.0.0.22:8443 check
说明:入口只做TCP转发,实际HTTP路由在后端网关完成。
4) 边界层与业务层分离(安全隔离)#
适用:安全与业务隔离、便于分权运维
示例:边界层启用ACL与限流
frontend fe_edge
bind *:80
acl is_admin path_beg /admin
http-request deny if is_admin !{ src 10.0.0.0/24 }
stick-table type ip size 100k expire 10m store http_req_rate(10s)
http-request track-sc0 src
http-request deny if { sc_http_req_rate(0) gt 50 }
default_backend be_app
5) 容器化部署(K8s/Sidecar)#
示例:Docker启动HAProxy并挂载配置
docker run -d --name haproxy \
-p 80:80 \
-v /opt/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro \
haproxy:2.8
预期效果:容器启动后对外提供80端口服务。
行业实践要点(含命令与排错)#
-
配置治理:git版本管理 + 语法校验 + 灰度发布
bash haproxy -c -f /etc/haproxy/haproxy.cfg systemctl reload haproxy -
可观测性:开启stats页面与socket
cfg listen stats bind *:8404 stats enable stats uri /stats stats auth admin:Admin@123
访问:http://<ip>:8404/stats -
容量与弹性:
cfg global nbthread 4 maxconn 50000 -
安全与合规:TLS套件统一
cfg frontend fe_https bind *:443 ssl crt /etc/ssl/certs/site.pem alpn h2,http/1.1 -
高可用演练:
bash systemctl stop haproxy # 模拟故障 ip a | grep 10.0.0.100 # 观察VIP漂移
常见问题排错清单#
- 访问超时:检查后端健康检查是否失败
echo "show stat" | socat /run/haproxy/admin.sock stdio | head - 连接数过高:调整maxconn并检查后端性能瓶颈
ss -s - 配置不生效:确认reload是否成功
journalctl -u haproxy -n 50
练习#
- 搭建“双机热备 + VIP”环境,模拟主机宕机并验证VIP漂移。
- 在边界层添加ACL,仅允许内网访问
/admin。 - 打开stats页面,观察后端节点状态变为UP/DOWN。