504
Nginx 504 Gateway Timeout 原因与解决方法
快速答案
504 表示后端在 Nginx 的等待时间内没有返回。先找出慢在哪里(慢查询、外部接口、队列),再按需调大 proxy_read_timeout 或 fastcgi_read_timeout。
最常见的原因:后端处理太慢:慢 SQL、调用外部接口卡住、导出/上传等长任务。
先这样改:只给慢接口加长超时
location /api/export {
proxy_pass http://127.0.0.1:3000;
proxy_connect_timeout 5s;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}最后核对: · 依据下方列出的官方文档 · 出处
典型日志
upstream timed out (110: Connection timed out) while reading response header from upstream upstream timed out (110: Connection timed out) while connecting to upstream
常见原因
- 后端处理太慢:慢 SQL、调用外部接口卡住、导出/上传等长任务。
- PHP-FPM 进程池耗尽(pm.max_children 太小),请求在排队。
- proxy_read_timeout / fastcgi_read_timeout 太短(默认 60s)。
- 后端所在机器到上游的网络不通,连接阶段就超时。
排查命令
看是 connecting 还是 reading 阶段超时
#
grep 'upstream timed out' /var/log/nginx/error.log | tail直接测后端耗时
#
time curl -s -o /dev/null http://127.0.0.1:3000/slow-pathPHP-FPM 是否到达进程上限
#
grep -i 'max_children' /var/log/php*-fpm.log修复配置
只给慢接口加长超时
location /api/export {
proxy_pass http://127.0.0.1:3000;
proxy_connect_timeout 5s;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}PHP-FPM
location ~ \.php$ {
fastcgi_read_timeout 300s;
...
}
# 同时调整 php.ini 的 max_execution_time 和 FPM 的 pm.max_children改完先 nginx -t,通过后 systemctl reload nginx。
关键事实与出处
- proxy_read_timeout 默认 60 秒,计的是两次读操作之间的间隔,不是整个响应的总时长。 [nginx.org]
- fastcgi_read_timeout 默认同样是 60 秒。 [nginx.org]
以上事实于 2026-11-14 对照原文核对;nginx 版本更新后请以官方文档为准。
常见问题
把超时调到很大可以吗?
可以止血但不治本。长时间占用连接会拖垮 worker 和后端,长任务更适合改成异步队列加轮询。
Cloudflare 的 524 和 504 一样吗?
类似。524 是 Cloudflare 等你源站超过 100 秒(免费版)没回应,调大 nginx 超时也没用,需要让请求在 100 秒内返回。
用工具解决
相关报错
推广位(待接入)
这里以后会放 VPS / CDN 推荐,并标明「推广链接」。目前没有任何返佣链接。
这里以后会放 VPS / CDN 推荐,并标明「推广链接」。目前没有任何返佣链接。