最明确的504诊断方法是查error.log中“upstream timed out”记录,结合access.log的$request_time和$upstream_response_time定位超时环节,并用curl直连后端验证真实响应性能。

直接查 Nginx 错误日志里有没有 504 Gateway Timeout,这是最明确的信号——说明 Nginx 等待后端响应超时了。
看 error.log 中的 upstream timed out 记录
Nginx 把超时判定为错误,会记到 /var/log/nginx/error.log(路径以实际配置为准)。执行:
tail -f /var/log/nginx/error.log | grep "504"
典型日志示例:
2026/06/13 22:18:42 [error] 12345#0: *6789 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.10.55, server: api.example.com, request: "GET /order/123 HTTP/1.1", upstream: "http://backend:8080/order/123", host: "api.example.com"
- upstream timed out:明确是上游(后端)超时
- while reading response header:Nginx 已发请求给后端,但迟迟没收到响应头
- upstream: "http://backend:8080/":指向具体后端地址,可据此定位服务
- client IP 和 request URI:便于复现或关联业务场景
对齐 access.log 查真实耗时
单看 error.log 只知道“超时”,但不知道“多慢”。需同步查 access.log:
grep "12345#0: \*6789" /var/log/nginx/access.log
找到同一连接 ID(如 *6789)在 access.log 中的记录,通常包含 $request_time 字段,例如:
192.168.10.55 - - [13/Jun/2026:22:18:42 +0800] "GET /order/123 HTTP/1.1" 504 563 "-" "curl/7.68.0" 60.123
末尾的 60.123 就是总耗时(秒),说明这次请求卡了整整 60 秒才被 Nginx 主动中断——这基本等于你配置的 proxy_read_timeout 值。
确认 Nginx 当前生效的超时参数
执行命令查看当前加载的配置中相关 timeout 设置:
nginx -T 2>/dev/null | grep -E "(proxy_(connect|send|read)_timeout|upstream)"
重点关注三项:
- proxy_connect_timeout:Nginx 连后端的建连超时(一般设 5–10s)
- proxy_send_timeout:Nginx 向后端发完请求后,等待后端接收完成的超时
- proxy_read_timeout:最常触发 504 的参数,即等待后端返回响应头/体的总时间
如果 access.log 显示耗时总是接近某个 timeout 值(比如稳定卡在 60s),而该值又明显小于业务合理耗时,那大概率就是这个参数太小,或者后端真卡住了。
验证后端真实响应能力
绕过 Nginx 直连后端,排除代理层干扰:
- 在 Nginx 服务器上执行:curl -w "\n%{time_total}\n" -o /dev/null -s http://127.0.0.1:8080/api/test
- 观察输出的响应总时间(单位:秒);若超过 60 秒,需进一步检查后端日志与慢查询
- 查看 access.log 中的 $upstream_response_time 字段,例如日志中出现 "0.002 128.456 0.001",表示三次重试中第二次耗时 128.456 秒,确认后端存在真实延迟











