Configure Nginx Reverse Proxy for Node.js WebSockets and PM2

by Fahim Mahmud Chisti

If your WebSocket connection fails with 400 Bad Request behind Nginx, or drops after exactly 60 seconds, Nginx is not forwarding the upgrade headers or is closing the idle connection. This guide sets up an Nginx reverse proxy for Node.js WebSockets, keeps the app running with PM2, and ends with a curl test that returns 101 Switching Protocols.

Quick answer: Add a map $http_upgrade $connection_upgrade block to the http section, then in the proxied location set proxy_http_version 1.1, pass the Upgrade and Connection headers, and raise proxy_read_timeout. Add a ping/pong heartbeat in Node so idle sockets stay open.

  1. In /etc/nginx/nginx.conf, add the map block inside http { }.
  2. In the site’s location, add proxy_http_version 1.1;, proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection $connection_upgrade;.
  3. Set proxy_read_timeout 3600s; and have the server send a ping every 30 seconds.
  4. Run sudo nginx -t, then reload Nginx.
  5. Test with curl: you should get HTTP/1.1 101 Switching Protocols.
In this guide
  1. Before You Start
  2. Why Nginx Breaks WebSockets by Default
  3. Step 1: Build a Minimal Node.js WebSocket Server
  4. Step 2: Manage the Node.js Process with PM2
  5. Step 3: Define Connection Upgrades in Nginx
  6. Step 4: Configure the Reverse Proxy Server Block
  7. Step 5: Enforce Secure WebSockets (WSS) via Let’s Encrypt
  8. Step 6: Verify and Debug the WebSocket Handshake
  9. Common Problems in Production
  10. Frequently Asked Questions
  11. Next Steps

Out of the box, Nginx does not pass on the hop-by-hop headers WebSockets rely on to negotiate a connection, and versions before 1.29.7 (which includes the packages in Ubuntu 22.04 and 24.04) also speak HTTP/1.0 to the backend. The steps below use an Ubuntu server running Node.js 24 LTS.

Nginx terminal output showing HTTP 101 Switching Protocols for Node.js WebSocket connection

Before You Start

  • Server: SSH with sudo on an Ubuntu server with Nginx, Node.js 24 LTS and npm installed. If PM2 is missing, install it with sudo npm install -g pm2.
  • Domain: a domain or subdomain whose A record points at the server, for the HTTPS step.
  • Time: about 20–30 minutes.
  • Back up first: nginx.conf affects every site on the server. Copy it (sudo cp /etc/nginx/nginx.conf /root/nginx.conf.bak) and run sudo nginx -t before every reload; a failed test leaves the running config untouched.
  • Already have an app? Skip Step 1 and apply Steps 3 and 4 to your existing server block.

Why Nginx Breaks WebSockets by Default

A WebSocket connection starts as an HTTP request carrying two critical headers: Upgrade: websocket and Connection: Upgrade. If your reverse proxy doesn’t forward them intact, Node sees a regular GET request and never switches the connection to WebSocket mode.

Nginx follows the HTTP/1.1 spec by stripping hop-by-hop headers. Throw a standard proxy_pass http://localhost:3000; into your config, and Nginx immediately injects Connection: close while dropping Upgrade on the floor.

Then there’s the idle timeout. If nothing is sent over the socket for 60 seconds, Nginx hits its default proxy_read_timeout and closes the connection behind your app’s back. The fix is explicit header mapping, a timeout matched to a heartbeat, and PM2 to keep the Node process running.

Step 1: Build a Minimal Node.js WebSocket Server

Before tweaking proxy rules, get a bare-bones server running that logs each connection, so you can tell which layer is failing. This example uses the ws package with Node’s built-in HTTP module to handle both REST routes and WebSockets.

On the server, create a directory and install the dependencies:

sudo mkdir -p /var/www/realtime-app
sudo chown $USER:$USER /var/www/realtime-app
cd /var/www/realtime-app
npm init -y
npm install ws express dotenv

Add this entrypoint in server.js. It listens on a local loopback port and answers both healthchecks and socket connections:

const http = require('http');
const express = require('express');
const { WebSocketServer } = require('ws');
const app = express();
const PORT = process.env.PORT || 3001;
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', uptime: process.uptime() });
});
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
wss.on('connection', (ws, req) => {
  const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
  console.log(`[ws] Client connected from ${clientIp}`);
  ws.send(JSON.stringify({ message: 'Connected to Node.js backend' }));
  ws.on('message', (data) => {
    console.log(`[ws] Received: ${data}`);
    ws.send(`Echo: ${data}`);
  });
  ws.on('close', (code, reason) => {
    console.log(`[ws] Disconnected: code ${code}`);
  });
});
server.listen(PORT, '127.0.0.1', () => {
  console.log(`HTTP/WS server running on http://127.0.0.1:${PORT}`);
});

Notice the server binds strictly to 127.0.0.1 instead of 0.0.0.0. Don’t expose this backend port to the public internet—lock it to localhost so all incoming traffic has to go through Nginx for SSL termination and filtering.

Quick check: run node server.js, and in a second SSH session run curl http://127.0.0.1:3001/health. You should get a small JSON reply with "status":"ok". Stop the server with Ctrl+C before Step 2.

Step 2: Manage the Node.js Process with PM2

A bare node server.js command will crash on the first uncaught error and stay down after a reboot. PM2 keeps the process running in the background and restarts it automatically.

An ecosystem file keeps the settings in one place. Create ecosystem.config.js inside /var/www/realtime-app:

module.exports = {
  apps: [
    {
      name: 'realtime-backend',
      script: './server.js',
      instances: 1,
      exec_mode: 'fork',
      autorestart: true,
      watch: false,
      max_memory_restart: '300M',
      env: {
        NODE_ENV: 'production',
        PORT: 3001
      }
    }
  ]
};

A quick heads-up on exec_mode: 'fork' versus cluster mode: standard stateful WebSockets break across clustered processes unless you share session state with an adapter or set up sticky sessions. If you plan to scale across multiple CPU cores, check the PM2 Cluster Mode documentation first to see how socket state behaves across worker forks. For a single backend instance, stick with fork to avoid handshake routing issues.

Start the app and configure PM2 to resurrect it on system boots:

pm2 start ecosystem.config.js
pm2 save
pm2 startup

pm2 startup only prints a sudo env PATH=... command; run that command, or PM2 will not come back after a reboot. Then run pm2 status to confirm. You should see realtime-backend listed as online. To stop PM2’s log files from filling the disk, see our guide to configuring PM2 startup scripts and log rotation on a VPS.

Step 3: Define Connection Upgrades in Nginx

To upgrade connections reliably, Nginx needs to inspect the incoming Upgrade header and set the Connection header dynamically. If the client doesn’t send an Upgrade header, Nginx should pass Connection: close (or keep-alive). If it does send Upgrade: websocket, Nginx needs to pass Connection: "upgrade".

Handle this with a map directive inside the main Nginx config. Open /etc/nginx/nginx.conf:

sudo nano /etc/nginx/nginx.conf

Inside the http { ... } block, add this mapping near the top:

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

This evaluates $http_upgrade. If it contains a value (like websocket), Nginx sets our custom $connection_upgrade variable to upgrade. If the header is absent, it falls back to close. This lets your standard REST endpoints and WebSocket upgrades share the same reverse proxy blocks cleanly.

Add the block only once. If nginx -t later complains about a duplicate connection_upgrade variable, another file already defines this map; keep one copy.

Step 4: Configure the Reverse Proxy Server Block

Now create your application’s server block in /etc/nginx/sites-available/realtime.example.com:

upstream nodejs_backend {
    server 127.0.0.1:3001;
}
server {
    listen 80;
    server_name realtime.example.com;
    access_log /var/log/nginx/realtime_access.log;
    error_log /var/log/nginx/realtime_error.log warn;
    location / {
        proxy_pass http://nodejs_backend;
        proxy_http_version 1.1;
        # Upgrade headers
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        # Standard forwarding headers
        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;
        # WebSocket timeout configurations
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
        # Optional: only affects streamed HTTP responses such as Server-Sent Events
        proxy_buffering off;
    }
}

Here is what each of those proxy lines is doing:

  • proxy_http_version 1.1;: Required on Nginx older than 1.29.7, where the default is HTTP/1.0, which does not support protocol upgrades or persistent streams.
  • proxy_set_header Upgrade $http_upgrade;: Passes the upgrade token straight to Node.js.
  • proxy_set_header Connection $connection_upgrade;: Passes upgrade or close dynamically based on our map block.
  • proxy_read_timeout 3600s;: Stops Nginx from killing quiet TCP connections after its default 60-second inactivity limit.
  • proxy_buffering off;: Optional. Upgraded WebSocket connections are never buffered; this only helps if the same location also streams ordinary HTTP responses such as Server-Sent Events.

Enable the site and test your syntax before reloading:

sudo ln -s /etc/nginx/sites-available/realtime.example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Run the lines one at a time, and reload only after nginx -t prints syntax is ok and test is successful. Then check that plain HTTP still reaches Node: curl http://realtime.example.com/health from your own computer should return the same JSON as before.

Step 5: Enforce Secure WebSockets (WSS) via Let’s Encrypt

Modern browsers block unencrypted ws:// links outright from any page served over HTTPS due to mixed-content security rules. You need TLS terminated at Nginx and a working wss:// endpoint.

Pull an SSL certificate using Certbot with the Nginx plugin:

sudo apt update && sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d realtime.example.com

Certbot updates your config to listen on port 443 with modern SSL defaults. If you run several realtime services on different subdomains, one wildcard certificate can cover them all; see our guide to Let’s Encrypt wildcard SSL with Certbot DNS-01.

Once Certbot finishes, open your config and double-check that your new server { listen 443 ssl; ... } block kept the proxy_set_header Upgrade and proxy_read_timeout directives we added earlier.

Step 6: Verify and Debug the WebSocket Handshake

Don’t wait for your frontend to show errors. Test the upgrade handshake from your own computer’s terminal using curl:

curl -i -N --http1.1 -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" -H "Sec-WebSocket-Version: 13" https://realtime.example.com/

The --http1.1 flag stops curl from negotiating HTTP/2, where the Upgrade handshake does not exist. If Nginx and Node are talking correctly, you’ll get an HTTP 101 response back (curl then keeps the connection open; press Ctrl+C to quit). Your Server and Date lines will differ; the first line and the Upgrade header are what matter:

HTTP/1.1 101 Switching Protocols
Server: nginx/1.24.0
Date: Mon, 14 Apr 2025 10:14:22 GMT
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Accept: qGEgH3En71di5rrssAZTmtRTyFk=

If you get an ordinary HTTP response instead (a 200 or 404 from Express, or a 400 Bad Request), Nginx dropped either Upgrade or Connection before the request reached Node. Check the Nginx WebSocket documentation if you’re dealing with unusual subpaths.

Next, install wscat to open an interactive session and test bidirectional messaging:

sudo npm install -g wscat
wscat -c wss://realtime.example.com/

Type a message and hit Enter. You should get the echo back immediately with no delay and no drops.

Common Problems in Production

Two issues tend to show up only once this stack is in production.

1. The 60-Second Phantom Disconnect

Even with proxy_read_timeout 3600s;, middleboxes like mobile carrier networks, corporate proxies, and NAT firewalls can drop idle TCP connections, some after as little as 30 to 60 seconds of dead silence. If neither side transmits, the socket silently dies without ever sending a FIN packet.

The fix isn’t making Nginx timeouts longer—it’s running an application-level heartbeat. Add this to server.js below the existing wss.on('connection', …) handler (it uses the same wss object), then run pm2 restart realtime-backend. It pings each client every 30 seconds and drops clients that stop answering:

function heartbeat() {
  this.isAlive = true;
}
wss.on('connection', (ws) => {
  ws.isAlive = true;
  ws.on('pong', heartbeat);
});
const interval = setInterval(() => {
  wss.clients.forEach((ws) => {
    if (ws.isAlive === false) {
      return ws.terminate();
    }
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);
wss.on('close', () => {
  clearInterval(interval);
});

These tiny ping/pong frames reset Nginx’s proxy_read_timeout timer and stop intermediate firewalls from cutting the line.

2. Broken Handshakes in PM2 Cluster Mode

If you use libraries like Socket.io that start with HTTP long-polling before upgrading, turning on PM2 cluster mode (instances: 'max') will trigger constant 400 Session ID unknown errors.

PM2 load-balances across instances with round-robin. Request 1 (the initial handshake) hits Worker A, and Request 2 (the upgrade attempt) hits Worker B. Worker B has no idea what Worker A negotiated.

If you need cluster mode, you have two choices:

  • Force pure WebSockets right away by turning off polling fallbacks in your frontend client.
  • Run separate Node processes on distinct ports (3001, 3002, 3003) and use Nginx’s ip_hash; upstream block to lock sessions to specific workers.

Quick Error Reference

  • 400 Bad Request on connect: the Upgrade or Connection header isn’t reaching Node (Steps 3 and 4), or Socket.io in cluster mode lost its session (above).
  • 502 Bad Gateway: Node isn’t running or listens on a different port; check pm2 status.
  • Drops after about 60 seconds: proxy_read_timeout is still the default, or no heartbeat is running.
  • ws:// works but wss:// fails: the HTTPS server block Certbot edited is missing the upgrade headers or timeouts; copy them in, run sudo nginx -t and reload.

Frequently Asked Questions

Why does my WebSocket fail with a 502 Bad Gateway error?

A 502 means Nginx is running, but it can’t reach the Node process specified in proxy_pass. Run pm2 status to make sure your app hasn’t crashed, and run curl http://127.0.0.1:3001/health locally on the server to see if the port is answering.

Can I run regular REST API routes and WebSockets through the same Nginx block?

Yes. That’s why we use map $http_upgrade $connection_upgrade. When an incoming request includes the upgrade header, Nginx upgrades it. When it’s standard GET or POST traffic, Nginx passes Connection: close and handles it like an ordinary REST request.

What should proxy_read_timeout be set to?

If your app implements a 30-second ping/pong heartbeat, anywhere between 300s and 3600s is solid. Don’t set it to days without a heartbeat, or abandoned connections will hang around and leak system file descriptors.

How can I access the client’s real IP address in Node.js?

Read the x-forwarded-for header. Because Nginx connects from localhost, req.socket.remoteAddress always returns 127.0.0.1. Nginx fills the header when your config includes proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;, as the server block above does.

Next Steps

With wscat echoing messages over wss://, replace the sample server.js with your real app and keep the same Nginx block and PM2 setup. For a fuller walkthrough of hosting a Node.js app on a VPS, including DNS and cache headers, see how to deploy Node.js on a Hostinger VPS with Nginx and Namecheap DNS.

all_in_one_marketing_tool