Skip to main content

Web servers and networking · Intermediate · 17 min

Proxy WebSocket connections through Nginx

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Nginx 1.30.8 · Node.js 26.13.1 · ws 8.23.0

You will put Nginx 1.30 in front of a Node.js WebSocket app, see the handshake fail without the upgrade headers, fix it, keep idle connections alive with pings, and route a chat room to one of two app servers.

On this page

A WebSocket starts life as an ordinary HTTP request. The browser sends GET with two extra headers, Upgrade: websocket and Connection: Upgrade, and the server answers 101 Switching Protocols. From then on the same TCP connection carries messages in both directions for as long as both sides keep it open, which can be hours.

A reverse proxy gets in the way of both halves of that. Upgrade and Connection are hop-by-hop headers: they describe one link, so Nginx does not forward them unless you tell it to, and the app never learns that the client wanted a WebSocket. And once the connection is open, Nginx closes it if nothing arrives from the app for 60 seconds, which is exactly what a quiet chat looks like.

In this tutorial you will build a small chat server with Node.js and the ws package, proxy it through Nginx, and break and fix each of these in turn. At the end you will run two copies of the app and make Nginx send everyone in the same chat room to the same copy.

Step 1 · Write a small WebSocket chat server

Nginx must already be installed from nginx.org, as in /tutorials/install-nginx-on-ubuntu-26-04, and Node.js 26 from nodejs.org, as in /tutorials/nginx-reverse-proxy-for-a-node-app. Check both:

Bash
nginx -v
node -v

Make a project folder and install ws, the most widely used WebSocket library for Node.js. The exact version is pinned so the steps behave as written:

Bash
mkdir -p ~/ws-demo
cd ~/ws-demo
npm init -y > /dev/null
npm install ws@8.23.0

The server keeps chat rooms in memory. A client picks a room with ?room= in the URL, gets a welcome message that names the app instance it reached, and every message it sends goes to everyone in the same room on that instance. A plain HTTP request, without the upgrade headers, gets 426 Upgrade Required. Two settings come from the environment: PORT, and PING_MS, how often to ping clients (0 means never), which you will use later.

Bash
cat > ~/ws-demo/server.js <<'JS'
const http = require('node:http');
const { WebSocketServer } = require('ws');

const PORT = Number(process.env.PORT || 8081);
const PING_MS = Number(process.env.PING_MS || 0);
const NAME = `app-${PORT}`;

// Requests that arrive without an upgrade end up here.
const server = http.createServer((req, res) => {
  res.writeHead(426, { 'Content-Type': 'text/plain', Upgrade: 'websocket', Connection: 'Upgrade' });
  res.end('This endpoint expects a WebSocket upgrade\n');
});

const wss = new WebSocketServer({ server, path: '/ws' });
const rooms = new Map();

wss.on('connection', (socket, req) => {
  const room = new URL(req.url, 'http://localhost').searchParams.get('room') || 'lobby';
  if (!rooms.has(room)) rooms.set(room, new Set());
  rooms.get(room).add(socket);

  socket.isAlive = true;
  socket.on('pong', () => { socket.isAlive = true; });

  socket.send(`welcome from ${NAME}, room ${room}`);
  socket.on('message', (data) => {
    for (const peer of rooms.get(room)) {
      if (peer.readyState === peer.OPEN) peer.send(`${NAME} ${room}: ${data}`);
    }
  });
  socket.on('close', () => rooms.get(room).delete(socket));
});

if (PING_MS > 0) {
  // Ping every client; drop any that did not answer the previous ping.
  setInterval(() => {
    for (const socket of wss.clients) {
      if (!socket.isAlive) { socket.terminate(); continue; }
      socket.isAlive = false;
      socket.ping();
    }
  }, PING_MS);
}

server.listen(PORT, '127.0.0.1', () => {
  console.log(`${NAME} listening on 127.0.0.1:${PORT}, ping every ${PING_MS || 'never'} ms`);
});
JS

Now a test client. It opens a connection, prints the status of the handshake, sends one message and prints what comes back. If the handshake fails it prints the error and exits with code 1:

Bash
cat > ~/ws-demo/echo-test.js <<'JS'
const WebSocket = require('ws');

const socket = new WebSocket(process.argv[2]);
const timer = setTimeout(() => {
  console.log('error: no reply within 5 seconds');
  process.exitCode = 1;
  socket.terminate();
}, 5000);

socket.on('upgrade', (res) => console.log(`handshake: HTTP ${res.statusCode}`));
socket.on('open', () => socket.send('hello through nginx'));
socket.on('message', (data) => {
  const text = data.toString();
  console.log(`received: ${text}`);
  if (text.endsWith('hello through nginx')) socket.close();
});
socket.on('error', (err) => {
  console.log(`error: ${err.message}`);
  process.exitCode = 1;
});
socket.on('close', () => clearTimeout(timer));
JS

In your first extra terminal, start the app on port 8081. It stays in the foreground:

Bash
cd ~/ws-demo
PORT=8081 node server.js

It prints app-8081 listening on 127.0.0.1:8081, ping every never ms. The app listens only on the loopback address, so nothing outside the server can reach it except through Nginx.

Check it worked

Back in your main terminal, talk to the app directly, first as a WebSocket client and then as plain HTTP:

Bash
cd ~/ws-demo
node echo-test.js ws://127.0.0.1:8081/ws
curl -i http://127.0.0.1:8081/ws

The client prints handshake: HTTP 101, then received: welcome from app-8081, room lobby and received: app-8081 lobby: hello through nginx. curl sends no upgrade headers, so it gets HTTP/1.1 426 Upgrade Required and the text This endpoint expects a WebSocket upgrade. Remember that 426: it is what the app says when the upgrade headers go missing.

Step 2 · Proxy it the usual way and watch the handshake fail

Start with the reverse proxy config you would write for any HTTP app. It listens on port 8080 so it does not disturb any site you already serve on port 80; on your own site you would put the location block inside the existing server block instead.

Bash
sudo tee /etc/nginx/conf.d/ws-demo.conf > /dev/null <<'CONF'
server {
    listen 8080;
    server_name _;

    location /ws {
        proxy_pass http://127.0.0.1:8081;
        proxy_set_header Host $host;
    }
}
CONF
sudo nginx -t

Apply it:

Bash
sudo systemctl reload nginx

Now connect through Nginx on port 8080:

Bash
cd ~/ws-demo
node echo-test.js ws://127.0.0.1:8080/ws

The client prints error: Unexpected server response: 426. Nginx passed the GET /ws request on, but dropped Upgrade and Connection along the way, as it does with every hop-by-hop header. The app saw a plain HTTP request and answered with its 426. Other frameworks answer the same mistake with a 400 or a 404, and some libraries fall back to slower long-polling without telling you, so the failure can look like a slow app rather than a broken proxy.

Check it worked

Look at the last line of the access log:

Bash
sudo tail -n 1 /var/log/nginx/access.log

The line contains "GET /ws HTTP/1.1" 426. A failed upgrade always shows up here as a normal status code, never as 101.

Step 3 · Pass the upgrade handshake to the app

Three lines fix it. Nginx has to send Upgrade and Connection to the app itself, and it has to speak HTTP/1.1 to the app, because the protocol switch does not exist in HTTP/1.0.

The Connection value needs care. Hard-coding Connection: upgrade would also send it with ordinary requests to the same location. A map sets it from the client's request instead: upgrade when the client sent an Upgrade header, close when it did not. A map lives at http level, outside any server block; files in conf.d are already included at that level.

Bash
sudo tee /etc/nginx/conf.d/ws-demo.conf > /dev/null <<'CONF'
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 8080;
    server_name _;

    location /ws {
        proxy_pass http://127.0.0.1:8081;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
CONF
sudo nginx -t

proxy_http_version 1.1 is already the default from Nginx 1.29.7, so on 1.30 the line changes nothing. Keep it anyway: Ubuntu's own nginx package is 1.28, where the default is 1.0, and the same config then works on both. If nginx -t reports a duplicate connection_upgrade variable, another file already defines this map; delete the map block here and use the existing one.

Apply it:

Bash
sudo systemctl reload nginx

Check it worked

Bash
cd ~/ws-demo
node echo-test.js ws://127.0.0.1:8080/ws

The client prints handshake: HTTP 101 and both messages, the same as when it talked to the app directly. Nginx now saw the 101 from the app and turned the request into a tunnel that copies bytes both ways. Check the log again:

Bash
sudo tail -n 1 /var/log/nginx/access.log

The newest line contains "GET /ws HTTP/1.1" 101. Nginx writes the line when the WebSocket closes, not when it opens, so a connection that is still open has no log line yet.

Step 4 · See the idle timeout close a quiet connection

Once the tunnel is open, proxy_read_timeout decides how long Nginx waits for the app to send something. The default is 60 seconds, and the timer restarts with every read, so a busy connection lives forever and a quiet one dies after a minute. To see this without waiting a minute, set it to 5 seconds for now. Nginx logs the timeout at info level, which the default error log, set to notice, leaves out, so this config also sends the demo's errors to a file of their own at info level:

Bash
sudo tee /etc/nginx/conf.d/ws-demo.conf > /dev/null <<'CONF'
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 8080;
    server_name _;
    error_log /var/log/nginx/ws-demo-error.log info;

    location /ws {
        proxy_pass http://127.0.0.1:8081;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 5s;
    }
}
CONF
sudo nginx -t
Bash
sudo systemctl reload nginx

This client connects and then sends nothing. It reports whether the connection survived, and how many pings it received:

Bash
cat > ~/ws-demo/idle-test.js <<'JS'
const WebSocket = require('ws');

const [url, secondsArg] = process.argv.slice(2);
const seconds = Number(secondsArg || 10);
const started = Date.now();
let pings = 0;
let finished = false;

const socket = new WebSocket(url);
socket.on('ping', () => { pings += 1; });
socket.on('open', () => console.log(`open, staying idle for ${seconds}s`));

const timer = setTimeout(() => {
  finished = true;
  console.log(`still open after ${seconds}s, pings received: ${pings}`);
  socket.close();
}, seconds * 1000);

socket.on('close', (code) => {
  clearTimeout(timer);
  if (finished) return;
  const after = ((Date.now() - started) / 1000).toFixed(1);
  console.log(`closed after ${after}s with code ${code}, pings received: ${pings}`);
});
socket.on('error', (err) => console.log(`error: ${err.message}`));
JS

Stay idle for 8 seconds:

Bash
cd ~/ws-demo
node idle-test.js ws://127.0.0.1:8080/ws 8

The client prints closed after 5.0s with code 1006, pings received: 0 (the fraction can differ slightly). Code 1006 means the connection ended without a WebSocket close message: Nginx cut the TCP connection. In a browser this is the close event your app gets with no warning.

Check it worked

Bash
sudo grep 'timed out' /var/log/nginx/ws-demo-error.log | tail -n 1

The log has a line like upstream timed out (110: Connection timed out) while proxying upgraded connection. When users report that a live page "stops updating after a minute", this line is what to look for; on your own site, raise the level of the site's error_log to info while you look, and lower it again afterwards, because info also logs every client that disconnects. The configs in the next steps leave the line out again.

Step 5 · Keep connections alive with pings

You could raise proxy_read_timeout to hours, but then Nginx also holds on to connections whose client vanished long ago, such as a phone that lost signal. The better fix is for the app to send a WebSocket ping every so often. A ping is a tiny control frame. It counts as data for Nginx, so the timer restarts, and the client must answer with a pong, so the app learns which clients are really gone. Browsers send the pong by themselves; your front-end code does nothing. The server you wrote already pings when PING_MS is set, and terminates any client that missed the previous ping.

In the app's terminal, stop the app with Ctrl+C and start it again with a ping every 2 seconds:

Bash
PORT=8081 PING_MS=2000 node server.js

Run the same idle client:

Bash
cd ~/ws-demo
node idle-test.js ws://127.0.0.1:8080/ws 8

It prints still open after 8s, pings received: 3 or 4. The pings arrived more often than the 5-second timeout, so Nginx never closed the connection.

Now set values you would keep. A common pairing is a ping every 30 seconds with a read timeout a little over twice that, so one late ping does not drop anyone:

Bash
sudo tee /etc/nginx/conf.d/ws-demo.conf > /dev/null <<'CONF'
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 8080;
    server_name _;

    location /ws {
        proxy_pass http://127.0.0.1:8081;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 75s;
    }
}
CONF
sudo nginx -t
Bash
sudo systemctl reload nginx

Every ping wakes a phone's radio and uses a little data. For users on prepaid mobile data, an interval of tens of seconds is a fair trade; an interval of one or two seconds, as in the test above, is not. Mobile networks also drop idle connections on their own, so the client should always reconnect after a close event, waiting a little longer after each failed attempt.

Check it worked

Bash
grep -c 'proxy_read_timeout 75s' /etc/nginx/conf.d/ws-demo.conf

It prints 1. The app's terminal still shows ping every 2000 ms; in the next step you start it with PING_MS=30000.

Step 6 · Route a chat room to one of two app servers

Each copy of this app keeps its rooms in its own memory. With two copies behind Nginx, two people in the same room can end up on different copies and never see each other's messages. Note that once a WebSocket is open it always stays on the copy it reached: the problem is which copy each new connection reaches.

Stop the app with Ctrl+C. Then start two copies, one per extra terminal, with a 30-second ping:

Bash
cd ~/ws-demo
PORT=8081 PING_MS=30000 node server.js
Bash
cd ~/ws-demo
PORT=8082 PING_MS=30000 node server.js

Put both in an upstream block and point proxy_pass at it. The zone line shares the group's state between Nginx worker processes, so they all follow one rotation:

Bash
sudo tee /etc/nginx/conf.d/ws-demo.conf > /dev/null <<'CONF'
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream chat_backends {
    zone chat_backends 64k;
    server 127.0.0.1:8081;
    server 127.0.0.1:8082;
}

server {
    listen 8080;
    server_name _;

    location /ws {
        proxy_pass http://chat_backends;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 75s;
    }
}
CONF
sudo nginx -t
Bash
sudo systemctl reload nginx

This client plays two people in the room lagos. Amara joins, Bola joins, Bola says hello, and the client reports whether Amara heard it:

Bash
cat > ~/ws-demo/room-test.js <<'JS'
const WebSocket = require('ws');

const url = process.argv[2];

function join(name) {
  return new Promise((resolve, reject) => {
    const socket = new WebSocket(url);
    socket.once('message', (data) => {
      console.log(`${name}: ${data}`);
      resolve(socket);
    });
    socket.once('error', reject);
  });
}

(async () => {
  const amara = await join('amara');
  const bola = await join('bola');
  const heard = new Promise((resolve) => {
    const timer = setTimeout(() => resolve(null), 1000);
    amara.once('message', (data) => { clearTimeout(timer); resolve(data.toString()); });
  });
  bola.send('hello from bola');
  const message = await heard;
  console.log(message ? `amara heard: ${message}` : 'amara heard nothing');
  amara.close();
  bola.close();
})().catch((err) => {
  console.log(`error: ${err.message}`);
  process.exitCode = 1;
});
JS
cd ~/ws-demo
node room-test.js 'ws://127.0.0.1:8080/ws?room=lagos'

The welcome lines show Amara on one copy and Bola on the other, for example amara: welcome from app-8081, room lagos and bola: welcome from app-8082, room lagos, and the last line is amara heard nothing. Round robin sent each new connection to the next copy.

Fix it by choosing the copy from the room name. hash $arg_room consistent hashes the room query parameter, so every connection for lagos reaches the same copy. consistent means that adding or removing a copy moves only a share of the rooms, not all of them. Add it as the first line of the upstream block:

Bash
sudo tee /etc/nginx/conf.d/ws-demo.conf > /dev/null <<'CONF'
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream chat_backends {
    hash $arg_room consistent;
    zone chat_backends 64k;
    server 127.0.0.1:8081;
    server 127.0.0.1:8082;
}

server {
    listen 8080;
    server_name _;

    location /ws {
        proxy_pass http://chat_backends;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 75s;
    }
}
CONF
sudo nginx -t
Bash
sudo systemctl reload nginx

The other option is ip_hash, which picks the copy from the client's address. It keeps one person on one copy across reconnects, but not two people in one room. It also hashes only the first three parts of an IPv4 address, and many mobile networks put thousands of users behind a few shared public addresses, so one copy can end up with most of your mobile traffic.

Check it worked

Bash
cd ~/ws-demo
node room-test.js 'ws://127.0.0.1:8080/ws?room=lagos'

Both welcome lines now name the same copy, and the last line is amara heard: app-8081 lagos: hello from bola (or app-8082, whichever the room hashes to). Try another room name, such as room=accra; it may land on the other copy, which is how the rooms share the load.

Hashing is a fair stopgap, but a room that outgrows one copy has nowhere to go, and a restart of that copy drops the whole room. Once you run several copies for real, have them share messages through a pub/sub service such as Valkey, so any copy can serve any room and Nginx can go back to plain round robin.

Step 7 · Clean up

Stop both app servers with Ctrl+C in their terminals.

Remove the demo config and folder, then reload Nginx. Check that the path is ~/ws-demo before you run rm -rf:

Bash
sudo rm /etc/nginx/conf.d/ws-demo.conf /var/log/nginx/ws-demo-error.log
sudo nginx -t
rm -rf ~/ws-demo
Bash
sudo systemctl reload nginx

On a live site, keep in mind that a reload leaves the old worker processes running until their WebSocket connections close, which can take hours. The worker_shutdown_timeout directive in the main nginx.conf, for example worker_shutdown_timeout 30s;, closes them after a set time, and clients then reconnect to the new workers.

Check it worked

Bash
curl -s -o /dev/null http://127.0.0.1:8080/ || echo "nothing listens on 8080"
ls ~/ws-demo 2>/dev/null || echo "demo folder removed"

It prints nothing listens on 8080 and demo folder removed.

Next steps

  • Put HTTPS in front so browsers can use wss://, which they require on any page served over HTTPS: /tutorials/free-https-with-lets-encrypt-and-nginx.
  • Compare WebSockets with one-way Server-Sent Events, which need no upgrade at all: /tutorials/stream-updates-with-server-sent-events.
  • Learn the other balancing methods and how Nginx handles a failed copy: /tutorials/load-balance-with-nginx-upstream.
  • Go back to the plain HTTP version of this proxy: /tutorials/nginx-reverse-proxy-for-a-node-app.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.