← 中文资源

简体中文版本

如何经反向代理配置 WebSocket

正确代理 WebSocket 连接:Upgrade 头、超时、粘性路由与扩展,使 ws:// 套接字穿过代理层存活。

阅读英文原文

引言

WebSocket 连接以带 Upgrade 头的 HTTP 请求开始,随后成为长生命双向套接字。该转换正是反向代理必须被告诉允许的:默认代理可能缓冲响应、关闭空闲连接、不转发 upgrade 头,使 ws:// 连接失败或掉线。配置代理意味传递 upgrade、禁用缓冲、设长读超时,并规划它如何路由与扩展长连接。

Upgrade 需要什么

客户端发 Connection: Upgrade 与 Upgrade: websocket。服务端以 101 Switching Protocols 回答,连接成为 WebSocket。中间代理必须转发那些头且不干扰切换,否则握手失败。

代理还不得缓冲连接,因为 WebSocket 是帧流而非请求/响应对。它必须长时间保持连接打开,因此其读超时须超过预期连接寿命,否则会关闭空闲套接字。

关键头

三项设置决定升级成败:HTTP 1.1 版(Upgrade 机制需要它)、从客户端转发的 Upgrade 头、以及设为 upgrade 的 Connection 头。漏任一项代理就剥离 upgrade,客户端得到普通 HTTP 响应而非 WebSocket。

Upgrade 头值因客户端而异(websocket),因此从客户端转发($http_upgrade)而非硬编码,以防未来升级类型。Connection 头则常为该位置硬设为 upgrade,因为客户端的 Connection 头可能含其他词元。

超时与空闲连接

WebSocket 在消息间可空闲,若超时内无数据流动代理读超时会关闭它。把读超时设得长于预期空闲期,或更好,让应用发周期 ping 使有活动、连接保持存活。

空闲超时设置必须超过 ping 间隔,使 ping 在超时触发前刷新它。这与 gRPC keepalive 同纪律:应用级 ping 是使长连接穿过会超时空闲流的中间设备的东西。

粘性路由与扩展

WebSocket 是到某后端的单条长连接,因此负载均衡必须在其寿命内把它路由到该后端。若代理中途重平衡,套接字断开。用按连接稳定的均衡策略(最少连接或连接 id 哈希),不要假定按请求轮询。

扩展意味更多后端实例、连接分散其上,但每条连接被钉住。规划每实例连接数与代理持有许多打开的连接的能力,因为每条 WebSocket 在代理与后端各保持一条连接打开。

排空与部署

重启后端的部署会关闭到它的每条 WebSocket,每个客户端重连。刻意排空:停止向该实例路由新连接、告诉现有客户端重连(客户端带退避重连)、并在进程退出前给它们截止时间。

因 WebSocket 长生命,突然关闭的滚动部署造成重连风暴。错开排空,并让客户端带抖动重连,使后端不被所有客户端同时击中。

安全 WebSocket 与头

安全 WebSocket 用 wss://(WebSocket over TLS),代理如处理任何 HTTPS 流量般终止 TLS。用 proxy protocol 或 X-Forwarded-For 保留原始客户端地址,使应用看到真实客户端以供限流与日志。

认证发生在握手:客户端在 Upgrade 请求带凭据(cookie、Authorization 头或 URL 中 token),服务端在接受切换前校验。因连接长生命,连接中途 token 过期必须处理,或在套接字上重新认证或关闭它。

常见陷阱与小结

不要忘记 proxy_http_version 1.1 或 Upgrade 与 Connection 头;没有它们握手变成普通 HTTP。不要让缓冲开着,它破坏帧流。不要无应用 ping 就设短读超时。不要对长连接用按请求轮询。也不要突然关闭造成重连风暴。

反向代理必须被告知允许 WebSocket 升级:用 HTTP/1.1 转发 Upgrade 与 Connection、禁用缓冲、设被应用 ping 刷新的长读超时、保持按连接稳定的路由、并在部署时排空。于是 ws:// 或 wss:// 连接穿过代理层并保持打开,而非握手失败或空闲超时掉线。

代码示例

# nginx: proxy a WebSocket endpoint
location /ws/ {
  proxy_pass http://app;
  proxy_http_version 1.1;                       # required for Upgrade
  proxy_set_header Upgrade $http_upgrade;        # pass the Upgrade header
  proxy_set_header Connection "upgrade";         # required alongside Upgrade
  proxy_read_timeout 3600s;                       # keep long-lived sockets open
  proxy_buffering off;                            # do not buffer frames
  proxy_set_header Host $host;
}
# the three settings that matter
proxy_http_version 1.1                -> the Upgrade mechanism needs 1.1
proxy_set_header Upgrade $http_upgrade -> forward the client's Upgrade value
proxy_set_header Connection "upgrade"  -> signal the switch
# miss any => the proxy strips the upgrade; the client gets plain HTTP, not WS
# keeping the WebSocket alive
proxy_read_timeout  >  the app's ping interval
app sends a ping every N seconds -> refreshes the proxy timeout, keeps it open
# without pings, an idle socket hits the read timeout and is closed
# the ping is the keepalive; the proxy timeout just needs to be longer
# long-lived connections and balancing
[ ] balancing must be stable PER CONNECTION (least_conn / connection hash)
[ ] a rebalance mid-connection breaks the socket
[ ] each WebSocket pins a backend + a proxy connection => plan capacity
[ ] on deploy, drain: stop accepting new, let existing sockets finish or migrate
# deploy drain for WebSockets
1. stop routing NEW connections to the instance
2. signal existing clients to reconnect (or let them on close)
3. wait for a drain window, then close the remaining sockets
4. client reconnects with backoff + jitter to avoid a reconnect storm
# abrupt shutdown => every socket to that instance drops at once
# secure WebSockets
wss://  = WebSocket over TLS; the proxy terminates TLS as for HTTPS
preserve the real client (proxy protocol / X-Forwarded-For) for rate limiting
auth at the handshake: cookie, Authorization header, or token in the request
# long-lived: handle token expiry mid-connection (re-auth or close)