Nginx Reverse Proxy for Node.js on a VPS (2026): Production Config + 502 Fixes

Most Nginx + Node.js tutorials stop at a five-line proxy_pass block. That works for a demo, but in production it quietly causes problems: every user shows up as 127.0.0.1, keepalive to Node is disabled, Socket.io falls back to polling and errors under PM2 cluster mode, and the first slow endpoint returns a 504.
This guide is the Nginx part of the stack only — a config you can actually run in production, and a table for diagnosing the errors you’ll hit. It assumes Node.js is already running under PM2 on the server. If it isn’t:
- Server from scratch: Node.js VPS hosting guide (or the Hetzner-specific setup)
- PM2 cluster config: PM2 VPS optimization guide
Tested on Ubuntu 24.04 with the distro Nginx package (1.24).
Step 1: Bind Node.js to 127.0.0.1, Not 0.0.0.0
Before touching Nginx, make sure Node only listens on the loopback interface:
app.listen(3000, "127.0.0.1");
If Node listens on 0.0.0.0 (the default for many frameworks), anyone can bypass Nginx by hitting http://YOUR_IP:3000 — skipping your SSL, rate limits and headers. A firewall usually blocks it too, but don’t rely on a single layer.
Also use 127.0.0.1 rather than localhost in Nginx. On Ubuntu, localhost can resolve to ::1 (IPv6) first; if Node is only on IPv4, Nginx logs connect() failed (111: Connection refused) while connecting to upstream, upstream: "http://[::1]:3000" and you get intermittent 502s.
Step 2: Minimal Config, Then SSL
Install Nginx and Certbot:
sudo apt update
sudo apt install -y nginx certbot python3-certbot-nginx
Create /etc/nginx/sites-available/myapp with a minimal HTTP block — just enough for Certbot to validate the domain:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
}
}
Enable it, remove the default site, and get a certificate:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d example.com -d www.example.com
Certbot creates the certificate under /etc/letsencrypt/live/example.com/ and sets up auto-renewal (systemctl list-timers | grep certbot to confirm). Now replace the minimal file with the production config below.
Step 3: The Production Config
First, a shared snippet so proxy headers aren’t copy-pasted into every location. Create /etc/nginx/snippets/proxy-node.conf:
proxy_http_version 1.1;
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;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
Then /etc/nginx/sites-available/myapp:
# WebSocket requests get "Connection: upgrade"; everything else gets an
# empty Connection header so keepalive to the upstream keeps working.
map $http_upgrade $connection_upgrade {
default upgrade;
'' '';
}
upstream node_app {
server 127.0.0.1:3000;
keepalive 32;
}
limit_req_zone $binary_remote_addr zone=auth:10m rate=10r/m;
# HTTP -> HTTPS, and www -> apex
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
server_tokens off;
client_max_body_size 20m;
gzip on;
gzip_proxied any;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript image/svg+xml;
# Static files straight from disk — Node never sees these requests
location /assets/ {
alias /var/www/myapp/current/public/assets/;
expires 30d;
access_log off;
}
# Brute-force protection on auth endpoints
location ~ ^/api/(login|register|reset-password) {
limit_req zone=auth burst=5 nodelay;
limit_req_status 429;
include snippets/proxy-node.conf;
proxy_pass http://node_app;
}
location / {
include snippets/proxy-node.conf;
proxy_pass http://node_app;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
}
sudo nginx -t && sudo systemctl reload nginx
What each part fixes:
| Directive | Without it |
|---|---|
map $http_upgrade $connection_upgrade |
Hard-coding Connection 'upgrade' (as most tutorials do) sends it on every request and disables upstream keepalive |
upstream { keepalive 32; } |
A new TCP connection to Node for every request — measurable extra latency under load |
X-Forwarded-Proto |
Your app thinks every request is HTTP: wrong redirect URLs, secure cookies not set |
client_max_body_size |
Uploads over 1 MB (Nginx default) fail with 413 |
limit_req on auth routes |
Login endpoints are open to credential stuffing |
http2 on listen |
On Nginx ≥ 1.25.1 use http2 on; instead; Ubuntu 24.04 ships 1.24, so the listen form is correct here |
The /assets/ path is an example — point alias at wherever your app keeps public files. The nginx worker user (www-data) needs read access to the files and execute permission on every parent directory, otherwise you get 403.
Step 4: Make Node Trust the Proxy
Nginx now sends the real client IP, but your framework ignores proxy headers by default. Tell it to trust Nginx — and only Nginx:
// Express
app.set("trust proxy", "loopback");
// Fastify
const app = Fastify({ trustProxy: "127.0.0.1" });
After this, req.ip is the visitor’s IP and req.protocol is https. Don’t set trust proxy to true unconditionally — that lets clients spoof their IP by sending their own X-Forwarded-For.
Also turn off compression in Node (e.g. remove the compression middleware) since Nginx now does it. Compressing twice wastes CPU on a small VPS.
Step 5: Real IPs Behind Cloudflare
If your domain is proxied through Cloudflare (orange cloud), Nginx sees Cloudflare’s IPs, not visitors’. Rate limiting then throttles Cloudflare itself — every visitor shares one bucket.
Generate a realip config from Cloudflare’s published ranges:
{
for ip in $(curl -s https://www.cloudflare.com/ips-v4) $(curl -s https://www.cloudflare.com/ips-v6); do
echo "set_real_ip_from $ip;"
done
echo "real_ip_header CF-Connecting-IP;"
} | sudo tee /etc/nginx/conf.d/cloudflare-realip.conf
sudo nginx -t && sudo systemctl reload nginx
Nginx’s $remote_addr (and therefore X-Real-IP and limit_req) now uses the visitor IP. Re-run it occasionally; Cloudflare rarely changes the list, but it does change.
Also set Cloudflare’s SSL mode to Full (strict). With Flexible, Cloudflare talks HTTP to your server, your server redirects to HTTPS, and the browser gets ERR_TOO_MANY_REDIRECTS.
Step 6: WebSockets, Socket.io and Server-Sent Events
The map + snippet above already handle the WebSocket upgrade. Two more things matter in practice.
Long-lived connections. proxy_read_timeout 60s closes a WebSocket that’s silent for 60 seconds. Socket.io sends pings every 25 seconds by default, so it’s fine; raw ws connections need either an app-level ping or a longer timeout on that path.
Socket.io + PM2 cluster mode. With multiple PM2 workers on one port, consecutive HTTP long-polling requests from the same client land on different workers, and you see 400 Bad Request / Session ID unknown. Nginx can’t make them sticky because all workers share port 3000. Fix it in the app:
- Force WebSocket transport on the client:
io(url, { transports: ["websocket"] }), or - Use
@socket.io/pm2for sticky sessions plus the cluster adapter so broadcasts reach clients on every worker.
Server-Sent Events need buffering off, or events arrive in bursts:
location /api/events {
include snippets/proxy-node.conf;
proxy_pass http://node_app;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 1h;
}
Step 7: Several Node.js Apps on One VPS
Each app gets its own port, its own upstream, and its own file in sites-available:
# /etc/nginx/sites-available/api
upstream api_app {
server 127.0.0.1:3001;
keepalive 16;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name api.example.com;
# ssl_certificate lines from certbot
location / {
include snippets/proxy-node.conf;
proxy_pass http://api_app;
}
}
Define the map block only once (in the first site file, or in /etc/nginx/conf.d/) — declaring the same variable in two files is a config error. Issue certificates per subdomain with sudo certbot --nginx -d api.example.com.
How many apps fit is mostly a RAM question; see the memory budget section of the PM2 guide.
Troubleshooting: Nginx Errors with Node.js
Start every investigation with the error log — it almost always names the cause:
sudo tail -f /var/log/nginx/error.log
| Symptom | Log / cause | Fix |
|---|---|---|
| 502 Bad Gateway | connect() failed (111: Connection refused) — Node isn’t running or is on another port |
pm2 status, pm2 logs, ss -ltnp | grep 3000 |
| 502 only sometimes | upstream shows [::1]:3000 |
Use 127.0.0.1 instead of localhost (Step 1) |
| 502 during deploys | pm2 restart kills all workers at once |
Use pm2 reload — see zero-downtime deploys |
| 504 Gateway Time-out | upstream timed out — handler took longer than proxy_read_timeout (60s) |
Speed up the endpoint or move work to a queue; raise the timeout only for that location |
| 413 Request Entity Too Large | Body over client_max_body_size (default 1 MB) |
Raise it in the server or upload location |
| 403 Forbidden on static files | permission denied for www-data |
namei -l /path/to/file to find the directory missing x permission |
ERR_TOO_MANY_REDIRECTS |
Cloudflare SSL mode Flexible | Switch to Full (strict) |
WebSocket fails, 400 from Socket.io |
Missing upgrade headers, or polling across PM2 workers | Snippet above; Step 6 for Socket.io |
req.ip is always 127.0.0.1 |
App doesn’t trust the proxy | Step 4 |
| Config change has no effect | File not linked, or another server block matches first |
ls -l /etc/nginx/sites-enabled/, sudo nginx -T | grep server_name |
conflicting server name warning |
Same server_name in two files |
Remove the duplicate (often the leftover default site) |
Always run sudo nginx -t before reload — a reload with a broken config is rejected, but a restart with one takes the site down.
FAQ
Do I need Nginx if Node.js can serve HTTPS itself?
You can terminate TLS in Node, but then Node handles certificates, renewals, compression, static files and slow clients on the same event loop as your app. Nginx does all of that in a few MB of RAM, and lets several apps share ports 80/443.
Should I use Caddy instead?
Caddy gets certificates automatically and has a shorter config, which makes it a good choice for simple setups. Nginx is the better fit if you need fine-grained rate limiting, the realip module, or if you’re following existing Nginx-based tooling and docs.
Does Nginx load-balance across PM2 workers?
No — in PM2 cluster mode all workers share one port and Node’s cluster module distributes connections. Nginx only needs one server in the upstream. If you run separate processes on separate ports, list each one in the upstream block and Nginx will balance between them.
How do I check the certificate will renew?
Run sudo certbot renew --dry-run. If it passes, the systemd timer installed by Certbot handles real renewals.