DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决 HAProxy 报错 504 Gateway Time-out 与终止标志分析

解析 HAProxy 触发 504 Gateway Time-out 与终止代码 sH/sR 机制,提供后端超时优化与长连接保活配置调整方案。

问题现象

客户端通过 HAProxy 代理发起耗时查询或文件上传时,请求被强制中断并返回:

HTTP/1.1 504 Gateway Time-out
Content-Length: 92
Connection: close

<html><body><h1>504 Gateway Time-out</h1>
The server didn't respond in time.
</body></html>

HAProxy 日志中记录的终止状态码出现 sH-- 或 sR--。

触发根因

  1. 后端服务器处理超时:HAProxy 成功与后端建立 TCP 连接并发送了请求体,但在 timeout server 时间内未收到任何响应头部。
  2. 后端服务未在规定时间内回传数据:在大数据报表导出或流式长传输中,分块间隔超过了配置值。
  3. 后端连接排队或进程卡死:后端应用 worker 饱和,无法从 backlog 中提取新连接。

诊断排查步骤

  1. 分析 haproxy.log 中的日志字段:
haproxy[18942]: 192.168.1.100:54120 [15/Nov/2026:08:15:30.100] http-in backend_api/srv1 0/0/1/1/30002 504 194 - - sH-- 12/8/2/1/0 0/0 "POST /export/data HTTP/1.1"
  • 0/0/1/1/30002:分别代表等待客户端请求时间 / 连接队列时间 / 建立后端TCP时间 / 等待后端返回响应头时间(30002ms) / 整体会话时长。
  • sH--:代表在等待后端发送 HTTP Response Header 时超时中断。

解决步骤与操作命令

步骤一:针对耗时业务增大后端超时时间

在 /etc/haproxy/haproxy.cfg 对应的 backend 或 defaults 中调整时间:

defaults
    mode                    http
    timeout connect         5s
    timeout client          60s
    timeout server          60s
    timeout http-request    10s
    timeout http-keep-alive 10s

backend backend_export_api
    mode http
    balance roundrobin
    timeout server 300s
    timeout connect 10s
    server srv1 10.0.1.11:8080 check inter 2000 fall 3 rise 2
    server srv2 10.0.1.12:8080 check inter 2000 fall 3 rise 2

步骤二:开启后端长连接池复用

减轻后端每次新建 TCP 握手与 TLS 握手的开销:

backend backend_export_api
    mode http
    http-reuse safe
    server srv1 10.0.1.11:8080 check pool-max-conn 50

步骤三:检查并平滑重载 HAProxy

# 语法校验
haproxy -c -f /etc/haproxy/haproxy.cfg

# 平滑重载
systemctl reload haproxy

验证方法

使用 curl 发起大响应长周期请求:

curl -w "
Time Total: %{time_total}s | HTTP: %{http_code}
" -X POST http://127.0.0.1/export/data

请求在耗时超过原 30s 后正常返回 HTTP 200,HAProxy 日志中终止状态为正常完成。