后台导出订单偶尔 504,不是每次都这样,一天五六次。nginx error.log 里是 upstream timed out (110: Connection timed out) while reading response header from upstream,request_time 60.003,upstream_response_time 那一栏是短横线。
短横线说明 nginx 连响应头都没等到。但 PHP 慢日志里同一个请求只花了 1.8 秒,两边对不上。这种对不上,通常不是后端真慢,是连接复用出了问题。
配置里 upstream 写了 keepalive 32,proxy_HTTP_version 却还是默认的 1.0,Connection 头也没清。后端那台 nginx 的 keepalive_timeout 是 60,比前端的 75 短。空闲连接被后端先关掉,前端还以为能用,请求发过去石沉大海,一直等到 proxy_read_timeout 60 秒才报错。
改法三行:proxy_http_version 1.1;proxy_set_header Connection "";proxy_read_timeout 从 60 提到 90。再加 proxy_next_upstream error timeout http_502,让幂等请求自动重试一次。
upstream backend {
server 10.0.8.12:80 max_fails=2 fail_timeout=10s;
keepalive 32;
keepalive_timeout 55s;
}
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_read_timeout 90s;
proxy_next_upstream error timeout http_502;
}
改完观察一周,504 从每天五六次降到零。副作用要留意:开了 next_upstream 之后,POST 超时也会重试,导出这种操作可能生成两份文件。我在后端加了请求 ID 去重,前端拿到重复的直接丢掉。
proxy_read_timeout 不是越大越好,90 秒对导出够用,对普通接口就是让用户干等一分钟。要区分就按 location 单独设,别在 http 段全局改。
