You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

proxy_pass超时后如何回收NGINX进程并实现自动重试连接?

解决NGINX代理超时后无法自动恢复连接的问题

核心原因

你当前配置使用了proxy_http_version 1.1和proxy_set_header "Connection" "",这会让NGINX与后端服务器建立长连接。当某次请求超时导致连接失效后,NGINX默认不会主动检测连接状态,后续请求仍会复用这条失效的长连接,从而持续返回504错误,直到重启或重载NGINX。

解决方案

通过以下配置调整,让NGINX自动回收失效连接并重试:

  1. 限制长连接复用规则与超时
    在location块或全局proxy配置中添加以下参数,控制长连接的生命周期和重试逻辑:

    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_connect_timeout 10s;          # 与后端建立连接的超时阈值
    proxy_send_timeout 10s;             # 向后端发送请求的超时阈值
    proxy_read_timeout 10s;             # 从后端读取响应的超时阈值
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;  # 指定触发重试的场景
    proxy_next_upstream_tries 3;        # 最大重试次数
    proxy_next_upstream_timeout 30s;    # 重试的总时长限制
    keepalive_requests 100;             # 每个长连接最多处理的请求数,达到后自动关闭连接
    keepalive_timeout 60s;              # 长连接空闲超时时间,超时后自动释放
    
  2. 启用上游服务器健康检测(需对应模块支持)
    如果将后端配置为upstream服务器组,可以通过健康检测自动剔除失效连接。注意:该功能需要NGINX Plus或第三方模块(如nginx_upstream_check_module,开源版需自行编译安装)支持:

    upstream static_server {
        server some.website.url;
        keepalive 32;                   # 维持的长连接池大小
        check interval=3000 rise=2 fall=3 timeout=1000 type=http;  # 每3秒检测一次,2次成功标记可用,3次失败标记不可用
        check_http_send "HEAD /version/ HTTP/1.0\r\nHost: some.website.url\r\n\r\n";
        check_http_expect_alive http_2xx http_3xx;
    }
    
    location /some_location {
        proxy_pass http://static_server/version/;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        # 保留原有proxy_set_header参数...
    }
    
  3. 禁用长连接(快速临时方案)
    如果不需要长连接特性,可以直接回退到HTTP/1.0,每次请求都会建立新连接,避免复用失效连接:

    location /some_location {
        proxy_pass http://some.website.url/version/;
        proxy_http_version 1.0;
        proxy_set_header Connection "close";
        # 保留原有proxy_set_header参数...
    }
    

验证方法

修改配置后执行nginx -s reload使配置生效,模拟后端故障再恢复的场景,观察请求是否能自动恢复正常,无需重启NGINX。

内容的提问来源于stack exchange,提问作者Jacques Gingras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:15:27