13.3.6 超时、日志与统计项配置要点
本节聚焦 HAProxy 中影响稳定性、可观测性与排障效率的三类配置:超时(timeout)、日志(log)与统计项(stats)。这些配置多在 defaults 与 listen/backend 中定义,需结合业务流量模型与网络环境合理设置。
原理草图(连接生命周期与观测路径):
超时配置要点#
超时用于控制连接生命周期,避免资源被慢请求或异常连接占用。建议在 defaults 中统一设定,必要时在特定 frontend/backend 覆盖。
完整示例(可执行)#
文件路径:/etc/haproxy/haproxy.cfg
global
log /dev/log local0
log /dev/log local1 notice
daemon
maxconn 20000
defaults
mode http
log global
option httplog
timeout connect 5s
timeout client 30s
timeout server 30s
timeout http-request 10s
timeout http-keep-alive 10s
timeout queue 30s
timeout tunnel 1h
frontend fe_web
bind :80
default_backend be_app
backend be_app
balance roundrobin
server app1 10.0.0.11:8080 check
server app2 10.0.0.12:8080 check
命令解释与验证#
# 检查配置语法,输出 "Configuration file is valid"
haproxy -c -f /etc/haproxy/haproxy.cfg
# 重载服务(不中断连接)
systemctl reload haproxy
# 观察连接与超时是否合理
ss -ant | head -n 20
参数要点与建议#
timeout connect:后端故障时快速失败能力,建议 2-5s。timeout client/server:慢请求容忍度,长连接业务适当调大。timeout http-request:防御慢速攻击(slowloris)。timeout queue:避免拥塞时无限排队。timeout tunnel:WebSocket/CONNECT 这类长连接。
日志配置要点#
日志是定位问题与审计流量的关键,global 指定日志目标,defaults/frontend 指定日志格式与级别。
示例(含日志格式与健康检查)#
global
log /dev/log local0
log /dev/log local1 notice
defaults
log global
option httplog
option log-health-checks
dontlognull
log-format "%ci:%cp -> %si:%sp [%t] %r %ST %B %TR/%Tw/%Tc/%Tr/%Ta %ID"
frontend fe_web
bind :80
default_backend be_app
日志落地与查看#
# rsyslog 接收 haproxy 日志
cat >/etc/rsyslog.d/49-haproxy.conf <<'EOF'
if ($programname == 'haproxy') then /var/log/haproxy.log
& stop
EOF
systemctl restart rsyslog
# 实时查看日志
tail -f /var/log/haproxy.log
关键字段解释#
%ci/%cp:客户端 IP/端口%si/%sp:前端监听 IP/端口%TR/%Tw/%Tc/%Tr/%Ta:请求/队列/连接/响应/总耗时%ST:状态码,%B:字节数%ID:请求 ID(便于链路追踪)
统计项配置要点#
统计页面用于实时查看连接数、后端健康与流量分布。通常在 listen 或 frontend 中配置 stats。
示例(独立 stats 监听)#
listen stats
bind 127.0.0.1:8404
stats enable
stats uri /haproxy?stats
stats auth admin:StrongPass
stats refresh 10s
stats show-legends
stats admin if { src 127.0.0.1 }
访问验证#
# 本机访问统计页
curl -u admin:StrongPass http://127.0.0.1:8404/haproxy?stats
# 预期输出包含 Backend/Server/Status 等字段
安全建议#
- 只绑定管理网段或本地回环。
- 必须开启认证并配合 ACL 限制来源。
- 生产环境慎用
stats admin。
排错指南(常见问题)#
- 日志无输出
# 检查 haproxy 是否写入 syslog
logger -t haproxy "test log"
grep haproxy /var/log/syslog /var/log/messages /var/log/haproxy.log
- 若无,检查 rsyslog 规则与
log /dev/log配置。
- 频繁 504/连接超时
# 查看后端响应耗时与队列耗时
tail -f /var/log/haproxy.log | grep " 504 "
- 调大
timeout server或检查后端服务性能。
- stats 页面无法访问
- 确认bind与防火墙放行端口;检查stats auth账号密码。
练习题#
- 将
timeout client/server调整为 60s,验证慢请求是否仍被中断。 - 自定义
log-format增加X-Request-Id输出,并用curl -H验证日志。 - 将 stats 监听改为
:8404,使用 ACL 仅允许内网段访问。