解决 Nginx 报错 504 Gateway Time-out 向上游建立 TCP 连接超时
分析 Nginx 向上游建立 TCP 握手超时诱因,详解 proxy_connect_timeout 调优与内网防火墙排查。
问题现象
客户端请求经由 Nginx 反代时报错 504,Nginx error.log 记录:
[error] 1234#0: *5678 upstream timed out (110: Connection timed out) while connecting to upstream,
upstream: "http://10.0.0.5:8080/api"
触发根因
区别于读取响应超时,这是在 TCP 三次握手阶段就发生了超时,说明 Nginx 根本连不上上游的目标 IP 与端口:
- 上游后端服务未启动或监听端口错误。
- 上游宿主机的防火墙(iptables/ufw)或云内网安全组未放行 8080 端口。
解决方案
在 Nginx 主机上直接测试连通性:
nc -zv 10.0.0.5 8080
若超时,登录 10.0.0.5 放行内网网段白名单:
sudo ufw allow from 10.0.0.0/24 to any port 8080 proto tcp
验证方法
再次发起代理测试,TCP 握手毫秒级建立,504 彻底根治。


