504 Gateway Timeout需分阶段定位卡点并按需调参:先查Nginx错误日志明确失败环节(如connecting/send/reading),再依业务场景设proxy_connect_timeout(3–15s)、proxy_send_timeout(10–60s)、proxy_read_timeout(建议P95+2~3秒);同步优化client_*超时、keepalive及健康检查重试机制。

接口响应慢导致 Nginx 报 504 Gateway Timeout 或连接中断,关键不是统一拉长所有超时值,而是分阶段定位卡点、按需收紧或放宽对应参数,并同步对齐后端与客户端行为。
先看错误日志,锁定超时发生阶段
Nginx 错误日志(/var/log/nginx/error.log)会明确提示哪一环失败:
-
while connecting to upstream → TCP 建连失败,查
proxy_connect_timeout -
while sending request to upstream → 请求发到后端过程中卡住,查
proxy_send_timeout -
while reading response header from upstream → 后端已接受连接但迟迟不返回响应头,查
proxy_read_timeout -
client timed out 或 upstream prematurely closed connection → 客户端断开或后端主动关闭,需检查
client_header_timeout、client_body_timeout或后端 keepalive 设置
按业务场景设合理 proxy 超时值
三个核心代理超时参数应写在 http 块中全局生效,再按路径局部覆盖:
-
proxy_connect_timeout 5s:同机房后端设 3–5 秒;跨可用区设 5–8 秒;公网后端不超过 15 秒 -
proxy_send_timeout 30s:普通接口 10–30 秒足够;大文件上传可配合client_max_body_size提升至 60 秒 -
proxy_read_timeout 12s:最易误配。若接口 P95 耗时为 9 秒,建议设为 12 秒(+2~3 秒缓冲),而非盲目填 60 或 300 秒
例如导出类接口可单独在 location 中覆盖:location /api/export { proxy_read_timeout 300s; }
补全客户端侧与连接复用控制
只调 proxy_* 不够,空闲连接也会拖垮整体表现:
-
client_header_timeout 15s:防止恶意不发请求头的连接长期占坑 -
client_body_timeout 30s:控制上传节奏,两次接收 body 数据间隔超时 -
send_timeout 20s:Nginx 往客户端写响应时单次阻塞上限 -
keepalive_timeout 30s:HTTP 长连接空闲关闭时间,30–60 秒较平衡
必须配套健康检查与重试机制
光改超时不能防故障扩散:
- 启用
proxy_next_upstream error timeout http_502 http_504,失败自动换节点重试 - upstream 中为每个 server 加
max_fails=2 fail_timeout=15s,避免反复打挂掉的实例 - 确认后端自身超时设置合理,如 Tomcat 的
connectionTimeout、Spring Boot 的server.tomcat.connection-timeout,需与 Nginx 对齐











