13.5.3 故障判定与摘除机制
故障判定与摘除机制#
本节说明 HAProxy 如何基于健康检查判定后端故障并自动摘除,结合配置、命令与排错示例,确保判定准确且可控。
1. 原理草图:判定与摘除流程
2. 判定逻辑关键参数与示例
- rise/fall:连续成功/失败阈值
- inter/fastinter/downinter:不同状态的检查间隔
- timeout check:单次检查超时
- observe layer4/layer7:按 TCP/HTTP 结果判定
- error-limit:错误阈值触发降级或DOWN
# /etc/haproxy/haproxy.cfg
defaults
mode http
timeout connect 3s
timeout client 30s
timeout server 30s
timeout check 2s
backend app_backend
option httpchk GET /health
http-check expect status 200
default-server inter 3s fastinter 1s downinter 5s rise 3 fall 2
server s1 10.0.0.11:8080 check
server s2 10.0.0.12:8080 check
预期效果:
- s1 连续 2 次失败 -> DOWN -> 自动摘除
- s1 连续 3 次成功 -> UP -> 重新加入
3. 运行时摘除与恢复命令(命令解释)
启用管理 socket:
# /etc/haproxy/haproxy.cfg
global
stats socket /run/haproxy/admin.sock mode 660 level admin
摘除/恢复示例(适用于临时维护):
# 将 s1 置为维护模式(立即摘除)
echo "disable server app_backend/s1" | socat stdio /run/haproxy/admin.sock
# 恢复 s1(重新参与健康检查)
echo "enable server app_backend/s1" | socat stdio /run/haproxy/admin.sock
# 查看后端状态
echo "show stat" | socat stdio /run/haproxy/admin.sock | grep app_backend
命令解释:
- disable server:强制 MAINT,跳过健康检查
- enable server:恢复可用状态
- show stat:查看UP/DOWN与检查计数
4. 安装与最小验证步骤(可执行)
# 安装(以 Ubuntu 为例)
sudo apt-get update
sudo apt-get install -y haproxy socat
# 校验配置语法
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
# 启动服务
sudo systemctl restart haproxy
sudo systemctl status haproxy
验证健康检查:
# 健康检查接口返回 200
curl -i http://10.0.0.11:8080/health
curl -i http://10.0.0.12:8080/health
# 故障模拟(关闭后端)
ssh 10.0.0.11 "sudo systemctl stop app"
sleep 5
echo "show stat" | socat stdio /run/haproxy/admin.sock | grep app_backend
5. 典型失败场景与排错
- 检查超时频繁:timeout check 太低或后端响应慢
- 处理:提升 timeout check,查看后端日志
- 误判 DOWN:fall 过小或 inter 过短
- 处理:适当提高 fall、延长 inter
- HTTP 误匹配:expect 规则与实际响应码不符
- 处理:调整 http-check expect,确认健康接口
排错命令:
# 查看 haproxy 日志(按发行版调整路径)
sudo journalctl -u haproxy -n 200
# 查看端口连通性
nc -zv 10.0.0.11 8080
# 手工探测健康检查URL
curl -v http://10.0.0.11:8080/health
6. 练习
1. 将 fall 从 2 调整为 5,观察摘除时间变化。
2. 把 timeout check 设为 1s,制造后端慢响应,确认判定逻辑。
3. 使用 disable server 将 s2 维护摘除,再 enable server 恢复。
4. 将 http-check expect status 200 改为 status 204,观察误判并修复。