DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

Nginx 反向代理 WebSocket 报 1006 异常断开与超时故障排查

前端与 Node/Go WebSocket 建立长连接时,经过 Nginx 代理频繁报 1006 Abnormal Closure 异常断开。本文深入解析 HTTP 协议升级头缺失、proxy_read_timeout 默认超时及 TCP 心跳保活排查方案。

在实时聊天、监控看板、协同编辑等场景中,WebSocket 是实现全双工长连接的核心协议。当客户端通过 Nginx 反向代理连接后端服务时,常遇到连接建立数秒或整整 60 秒后猝然断开,浏览器端捕获到 WebSocket connection to 'wss://...' failed: Error during WebSocket handshake 或控制台触发 onclose 事件,关闭状态码为 1006 (Abnormal Closure)。

故障现象与报错特征

  1. 连接初次建立阶段失败:浏览器控制台提示握手失败:
WebSocket connection to 'wss://example.com/ws/' failed: Error during WebSocket handshake: Unexpected response code: 200

(返回了 200 而非预期的 101 Switching Protocols)。

  1. 连接成功建立但每隔 60 秒定时断开: 客户端并未收到服务器发送的关闭帧,而是直接触发 event.code === 1006,没有任何详细原因。

根本原因剖析

  1. 缺少 HTTP 协议升级请求头转发:WebSocket 握手依赖于 HTTP Upgrade: websocket 与 Connection: Upgrade 请求头。默认情况下,Nginx 反向代理会将 Connection: close 发往上游,导致后端认为这是一次普通 HTTP 请求,直接返回 200 导致握手破裂。
  2. Nginx 默认读写超时时间触顶:proxy_read_timeout 的默认值为 60s。如果客户端与服务端在 60 秒内没有数据帧往来,且没有应用层心跳(Ping/Pong),Nginx 会单方面关闭该 TCP 连接。
  3. 中间网络防火墙与 NAT 超时:云厂商负载均衡器(SLB/ALB)或家用路由器 NAT 表项通常对空闲连接设定了 30 秒至 120 秒的淘汰机制。

诊断排查步骤

  1. 使用 wscat 工具在命令行模拟握手:
# 测试直连后端
wscat -c ws://127.0.0.1:8080/ws
# 测试经过 Nginx 代理
wscat -c wss://example.com/ws

观察经过 Nginx 时返回的 HTTP 响应头。

  1. 检查 Nginx 访问与错误日志: 查看 /var/log/nginx/error.log:
2026/01/01 12:00:00 [info] 12345#12345: *1 client prematurely closed connection, client: 1.2.3.4, server: example.com, request: "GET /ws HTTP/1.1", upstream: "http://127.0.0.1:8080/ws"

或者出现 upstream timed out (110: Connection timed out)。

解决方案与标准配置

步骤一:配置 map 指令动态传递 Connection 头

在 nginx.conf 的 http 块中定义协议升级映射关系:

http {
    # 动态匹配 Upgrade 头
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    server {
        listen 443 ssl http2;
        server_name example.com;

        # SSL 证书配置省略...

        location /ws/ {
            proxy_pass http://backend_pool;
            
            # 关键协议升级指令
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;

            # 保持主机与真实客户端 IP
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # 延长长连接读写超时时间(例如设为 1 小时或根据业务需求调整)
            proxy_read_timeout 3600s;
            proxy_send_timeout 3600s;

            # 禁用缓冲防止流式数据被暂存
            proxy_buffering off;
        }
    }
}

步骤二:应用层实现 Ping/Pong 心跳机制

单纯依靠无限放大 proxy_read_timeout 并非最佳工程实践。当客户端意外掉电或切换 Wi-Fi 时,过长的超时会导致服务端大量积压死连接。

在前端或客户端实现定时保活探测:

// 客户端每隔 25 秒发送一次 ping 心跳
setInterval(() => {
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({ type: 'ping' }));
    }
}, 25000);

步骤三:验证与热重载

检查 Nginx 语法并平滑加载:

nginx -t
nginx -s reload

重载完成后再次使用客户端连接,验证空闲状态下长连接是否能稳定维持。