
反向代理场景下,502 与 504 的含义不同,排查方向也不同:
先看错误日志,不要凭感觉改配置:
tail -n 200 /var/log/nginx/error.log
# 常见关键字
# connect() failed (111: Connection refused) while connecting to upstream
# upstream timed out (110: Connection timed out) while reading response header from upstream
# upstream prematurely closed connection while reading response header from upstream日志路径以你的安装方式为准,可用 nginx -V 2>&1 | grep -o 'error-log-path=[^ ]*' 确认。
ss -lntp | grep 8080
curl -sv http://127.0.0.1:8080/health -o /dev/nullConnection refused 说明上游没监听或监听在其它地址(例如只监听了 127.0.0.1 而 Nginx 代理到了内网 IP)。
resolver 配合变量。prematurely closed connection 往往是上游进程异常退出,去查应用日志、dmesg | grep -i oom 判断是否被 OOM Killer 杀掉。getsebool httpd_can_network_connect。log_format timing '$remote_addr "$request" $status '
'rt=$request_time urt=$upstream_response_time uct=$upstream_connect_time';
access_log /var/log/nginx/access.log timing;urt 接近 proxy_read_timeout(默认 60s)说明上游确实慢;uct 很大则是建连慢,多为网络或上游 backlog 满。
location /api/export/ {
proxy_pass http://backend;
proxy_connect_timeout 5s;
proxy_send_timeout 120s;
proxy_read_timeout 120s;
}上游启用 keepalive 可减少建连开销,也能避免高并发下端口耗尽:
upstream backend {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
keepalive 32;
}
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}proxy_next_upstream 默认对 error 和 timeout 重试下一台。注意非幂等请求(如 POST 下单)重试有重复提交风险,需要时显式限制。
如果 Nginx 前面还有云上负载均衡或 CDN,它们也有各自的空闲/回源超时。出现 504 时先确认是哪一层返回的:对比响应头和各层访问日志的时间点,具体超时上限以对应产品控制台和文档为准。
upstream_response_time,定位慢接口,再针对性调超时。nginx -t 校验,再 nginx -s reload。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。