要让Nginx稳定支撑高并发WebSocket连接,必须协同调优协议透传(proxy_http_version 1.1、proxy_set_header Upgrade $http_upgrade、proxy_set_header Connection "upgrade")、连接生命周期(proxy_read_timeout/proxy_send_timeout设为86400、proxy_buffering off、proxy_cache off)和系统资源(增大nofile限制、优化内核参数、配置worker_rlimit_nofile与worker_connections)。

要让 Nginx 稳定支撑高并发 WebSocket 连接,关键不在“改几个超时值”,而在于协议透传、连接生命周期控制和系统资源三者协同。漏掉任意一环,都可能引发 101 握手失败、连接秒断、TIME_WAIT 泛滥或上游连接耗尽。
协议头必须精准透传
WebSocket 握手依赖 HTTP/1.1 的 Upgrade 机制,Nginx 默认会过滤 Upgrade 和 Connection 头,导致返回 200 而非 101 —— 这是“连不上”的最常见原因。
- location 块中必须包含:proxy_http_version 1.1;
- proxy_set_header Upgrade $http_upgrade;(用变量,不是字符串 "Upgrade")
- proxy_set_header Connection "upgrade";(引号不能省,也不能写成 $http_connection 或空值)
- 更健壮的做法是在 http 块中加 map 指令:
map $http_upgrade $connection_upgrade { default upgrade; '' close; },再在 location 中写 proxy_set_header Connection $connection_upgrade;
超时与缓冲需彻底适配长连接
WebSocket 是全双工长连接,Nginx 默认按短连接逻辑处理,必须覆盖默认行为,否则空闲几十秒就会被静默断开。
- proxy_read_timeout 86400;(24 小时),应略大于客户端心跳间隔(如设为 90 秒心跳,则至少设为 120)
- proxy_send_timeout 86400;,避免大消息分片发送中途中断
- proxy_buffering off;,关闭响应缓冲,保证消息实时透传
- proxy_cache off;,显式禁用缓存,防止 Upgrade 请求被缓存命中返回 200
系统级资源必须同步扩容
Nginx 配置再优,也受限于操作系统能力。worker_connections 设再高,若系统文件描述符或端口不够,照样撑不住。
- 增大文件描述符上限:
echo '* soft nofile 1048576' >> /etc/security/limits.conf
echo '* hard nofile 1048576' >> /etc/security/limits.conf,并确认 Nginx 启动用户生效 - 优化内核参数(/etc/sysctl.conf):
net.core.somaxconn = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1 - Nginx 主配置启用高并发支持:
worker_rlimit_nofile 1048576;
events { worker_connections 65535; }
验证是否真正生效
别只 reload 配置就以为调优完成,得看运行态指标:
- 用 ss -s | grep estab 查看当前 ESTABLISHED 连接数
- 检查 Nginx 进程打开的文件数:lsof -p $(pgrep nginx) | wc -l
- 抓包验证握手是否返回 101:curl -i -H "Connection: upgrade" -H "Upgrade: websocket" https://yourdomain.com/ws
- 监控 TIME_WAIT 数量:ss -s | grep -i time_wait,过高说明端口复用或 fin_timeout 仍需调整



















