解决 Nginx 反向代理报错 504 Gateway Time-out 超时与 upstream 调优
排查 Nginx 作为反向代理返回 504 Gateway Time-out 错误,分析 upstream 后端响应超时与 proxy_read_timeout 优化配置。
问题现象
客户端通过浏览器或 API 调用系统接口时,请求挂起大约 60 秒后返回 HTTP 状态码 504:
<html>
<head><title>504 Gateway Time-out</title></head>
<body>
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>nginx</center>
</body>
</html>
查看 Nginx 的 error.log,记录以下致命日志:
2026/11/15 18:00:10 [error] 1420#0: *8912 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 203.0.113.10, server: example.com, request: "POST /api/export/excel HTTP/1.1", upstream: "http://127.0.0.1:8080/api/export/excel"
触发根因
HTTP 504(Gateway Time-out)明确表示:作为网关或反向代理的 Nginx 成功与后端上游服务(Upstream,如 Tomcat、Node.js、Python Gunicorn 或 PHP-FPM)建立了 TCP 连接,但在等待后端计算并返回响应数据的过程中,等待时间超过了规定的超时上限:
- 后端业务执行严重超时:生成大报表、导出大量数据、或执行了复杂的慢 SQL,执行时间超过了 Nginx 默认的
proxy_read_timeout(默认为 60 秒); - 后端工作线程全部阻塞耗尽:后端服务的连接池或工作线程池打满挂起,请求在后端的排队队列中长时间等待,无法在 60 秒内被处理;
- 下游依赖服务死锁或网络超时:后端调用的第三方外部 API 未设置超时,陷入死循环等待。
解决步骤
1. 针对长耗时业务局部调大 proxy_read_timeout
如果该接口(如异步批量导出、文件处理)本身耗时合理但超过 60 秒,在 Nginx 配置中针对该 location 单独放宽超时:
location /api/export/ {
proxy_pass http://127.0.0.1:8080;
# 与后端建立连接的超时(建议短,如 5s)
proxy_connect_timeout 10s;
# 发送请求给后端的超时
proxy_send_timeout 60s;
# 等待后端响应的最长超时(调整为 300 秒)
proxy_read_timeout 300s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
重新加载 Nginx 配置:
sudo nginx -t && sudo nginx -s reload
2. 如果后端是 PHP-FPM,同步调整 FastCGI 超时与执行时间
针对 PHP 架构,不仅需要调整 Nginx,还需调整 PHP 配置:
在 Nginx 中:
fastcgi_read_timeout 300s;
在 php.ini 与 php-fpm.conf 中:
max_execution_time = 300
request_terminate_timeout = 300s
3. 将同步阻塞耗时任务重构为异步任务队列
对于耗时超过数十秒的接口,根本性的架构优化是避免前端 HTTP 长连接同步阻塞:
- 接口接收请求后,生成一个
task_id并将任务推入 Redis/RabbitMQ 异步队列,立即向前端返回 HTTP 202 Accepted; - 后台 Worker 进程异步消费处理并落盘;
- 前端通过轮询或 WebSocket 查询任务进度与下载链接。
验证确认
再次发起慢请求测试:
curl -i -X POST -m 120 http://example.com/api/export/excel
请求在 75 秒后顺利返回 HTTP 200 OK 与完整的生成报表数据,未再出现 504 Gateway Time-out。


