Sub topic 12
Proxying WebSocket Connections
This chapter assumes you can already write a server and location block that uses proxy_pass. It also assumes you know what an upstream group is and how proxy_set_header works. If upstream groups are new to you, read the earlier chapters on them first.
Why WebSockets need special handling
A WebSocket is a long-lived, two-way connection between a browser and a server. It starts as an ordinary HTTP/1.1 request that asks to switch protocols. If the server agrees, it answers 101 Switching Protocols. From then on both sides send small messages in either direction over the same TCP connection, and HTTP is no longer used on it.
A plain proxy_pass breaks this handshake for three reasons:
- Nginx talks to backends with HTTP/1.0 by default, and the upgrade mechanism needs HTTP/1.1.
UpgradeandConnectionare hop-by-hop headers. They describe a single network hop, so Nginx does not forward them to the backend.- Nginx sets
Connection: closeon upstream requests unless told otherwise, which tells the backend not to keep the connection open.
The result is that the backend never sees an upgrade request. Depending on the application you get a plain 400, a 426 Upgrade Required, or a normal HTTP response that the browser rejects.
The handshake through Nginx
Nginx must see the client's upgrade request, repeat it to the backend, and then relay the 101 response. After that it acts as a tunnel and copies bytes in both directions.
The standard configuration
This configuration passes the handshake through and sets a suitable timeout. The map block must be in the http context, not inside server or location. Put it in nginx.conf or in a file under conf.d.
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream app_backend {
server 127.0.0.1:3000;
}
server {
listen 80;
server_name example.com;
location /ws/ {
proxy_pass http://app_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_read_timeout 300s;
}
}What each part does:
proxy_http_version 1.1makes Nginx speak HTTP/1.1 to the backend, which is required forUpgrade.proxy_set_header Upgrade $http_upgradecopies the client'sUpgradevalue (normallywebsocket) to the backend.proxy_set_header Connection $connection_upgradesetsConnection: upgradewhen the client asked for an upgrade, andcloseotherwise.mapcomputes$connection_upgradefrom$http_upgrade. An emptyUpgradeheader means a normal request, so the value becomesclose.proxy_read_timeout 300sraises the idle limit, as explained below.
Hard-coding proxy_set_header Connection "upgrade" also works, but then every request to that location asks for an upgrade, including ordinary HTTP requests. The map makes the location safe for both kinds of traffic.
Testing the handshake
Check the syntax first, then reload. Then send a handshake by hand with curl:
sudo nginx -t && sudo systemctl reload nginx
curl -i -N --http1.1 \
-H "Connection: Upgrade" \
-H "Upgrade: websocket" \
-H "Sec-WebSocket-Version: 13" \
-H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
http://example.com/ws/A working setup answers with HTTP/1.1 101 Switching Protocols, an Upgrade: websocket header, and a Sec-WebSocket-Accept header. curl then waits, because the connection stays open. Press Ctrl+C to stop it. Any other status code means the handshake did not reach the backend intact.
Timeouts for idle connections
proxy_read_timeout is the maximum time Nginx waits between two reads from the backend. Its default is 60 seconds. A WebSocket can sit idle for much longer than that, for example a chat room with no messages. If nothing arrives from the backend within the timeout, Nginx closes the connection and the client sees an abnormal closure (close code 1006 in browsers).
You have two ways to deal with this, and they work well together:
- Raise
proxy_read_timeouton the WebSocket location. Choose a value that matches how long you accept an idle connection to live. - Have the application or client send ping and pong frames at an interval shorter than the timeout. Each frame counts as traffic and resets the timer.
proxy_send_timeout applies in the other direction. It limits the time between two writes to the backend, and its default of 60 seconds rarely needs a change. Buffering settings do not matter once the connection is upgraded, because Nginx just copies data between the two sockets.
Interaction with upstream keepalive
The keepalive directive in an upstream group keeps idle connections to backends open for reuse. A connection that has been upgraded is dedicated to one client for its whole life, so it is never returned to that pool.
Two consequences follow:
- Give WebSocket traffic its own
location, such as/ws/. Keep the keepalive-friendly settings (proxy_http_version 1.1andproxy_set_header Connection "") in the other locations. - If you must serve both kinds of requests from one location, a map that returns an empty string for a non-upgrade request removes the
Connectionheader. Plain requests can then reuse pooled connections:
map $http_upgrade $connection_upgrade {
default upgrade;
'' '';
}With the close version of the map, every ordinary request in that location tells the backend to close the connection afterwards, and you lose the benefit of keepalive.
Load balancing long-lived connections
Round robin spreads new connections evenly, but WebSocket connections last for minutes or hours. After a restart or a scale-out, the older servers can end up holding most of the open connections while a new server sits nearly idle. Three measures help:
- Use
least_connso new connections go to the server with the fewest active ones. - Use
ip_hashorhashif the application keeps per-connection state on one server and the client must return to it. Note thatip_hashgroups clients behind one NAT or proxy onto a single backend. - Share state between servers (for example with a message broker) so any backend can handle any client. This is the most robust choice.
Capacity and reloads
Each proxied WebSocket uses two connections in the Nginx worker: one to the client and one to the backend. Both count against worker_connections, and both use a file descriptor. If you expect thousands of simultaneous sockets, raise worker_connections and worker_rlimit_nofile, and check the LimitNOFILE value of the systemd unit.
A graceful reload starts new workers and tells the old ones to finish their current work and exit. An old worker keeps running while any WebSocket it handles is still open, so after a reload you may see old and new workers side by side for a long time. If you want to cap this, set worker_shutdown_timeout in the main context. Nginx will then close the remaining connections after that time, and clients should reconnect.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Browser reports handshake failure; backend log shows a plain HTTP request | Missing `proxy_http_version 1.1` or the `Upgrade` and `Connection` headers | Add the three directives shown above |
| `400` or `426` from the backend | The backend did not receive `Upgrade: websocket` | Check the `map` is in the `http` context and the header names are spelled correctly |
| Connection drops after about 60 seconds of silence | Default `proxy_read_timeout` | Raise it and add ping frames |
| `502 Bad Gateway` on `/ws/` | Backend is down or the port is wrong | Check `error.log` for connect errors and test the backend directly |
| Handshake works over `http://` but fails over `https://` | Another proxy or load balancer in front of Nginx drops the upgrade headers | Make sure every hop forwards them |
| `403` from the application after upgrade | The backend checks the `Origin` header against the `Host` it sees | Pass `Host $host` and allow the public origin in the application |
Logging WebSocket requests
Nginx writes the access log line when a request ends. For a WebSocket that means when the connection closes, which may be hours after it started. The logged status is 101, and $request_time is the total lifetime of the connection. The $upstream_addr field in the upstream_log format from the logging chapter shows which backend held the connection. When you debug, remember that a WebSocket you are watching right now will not appear in the log until it ends.
Exercise
A WebSocket through your Nginx proxy connects fine, but it always closes after exactly 60 seconds when no messages are sent. Which directive is responsible, what are two ways to fix it, and why does proxy_set_header Connection "" not belong in the WebSocket location?
Show answer
The default proxy_read_timeout of 60 seconds closes the connection when the backend sends nothing for that long. You can raise proxy_read_timeout in the WebSocket location (for example to 300s), and you can make the application or client send ping and pong frames more often than the timeout. Setting Connection "" removes the Connection header, so the backend never receives Connection: upgrade and the handshake fails. The WebSocket location needs Connection $connection_upgrade instead. The empty value is only right for normal requests that use upstream keepalive.