An Nginx reverse proxy for Node.js is the standard way to put a production Node app on the internet. Your Node app listens on a private port like 3000, and Nginx faces the world on ports 80 and 443, forwarding traffic inward. This setup gives you free SSL termination, fast static file serving, working WebSockets, and room to run several apps on one server — all things Node handles awkwardly on its own. In this guide you’ll go from a bare VPS to a hardened, HTTPS-served Node deployment, with every directive explained.
Last verified: 2 October 2026. Commands checked against the official Nginx, Certbot, and PM2 documentation.
Why Put Node.js Behind Nginx?
Node’s built-in HTTP server is excellent at application logic and terrible at being a public web server. Running your app behind an Nginx reverse proxy buys you:
- SSL termination. Nginx handles HTTPS with Let’s Encrypt certificates, so your Node app keeps speaking plain HTTP internally — no crypto code in your app.
- Multiple apps, one server. Route
/apito one Node process,/adminto another, and a static site to a third, all on port 443. - Security. Your Node process never touches the public internet directly. It binds to
127.0.0.1, and only Nginx is exposed. - Fast static files and load balancing. Nginx serves assets directly and can spread traffic across several Node workers with an
upstreamblock.
Prerequisites
- A VPS running Ubuntu 22.04 or 24.04 with sudo access.
- A domain name with an A record pointing at your server’s IP (needed later for SSL).
- Node.js installed. If you don’t have it yet:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo bash -
sudo apt-get install -y nodejs
node -v && npm -v
Step 1: Get Your Node App Running on Localhost
Before Nginx enters the picture, your app must answer on a local port. Create a minimal app (or use your real one) and — this matters — bind it to 127.0.0.1 so it isn’t reachable directly from the internet:
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node behind Nginx\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Listening on 127.0.0.1:3000');
});
Never run production Node with node app.js & — the process dies when your SSH session ends and never restarts after a crash. Use PM2, the standard Node process manager:
sudo npm install -g pm2
pm2 start app.js --name node-app
pm2 save
pm2 startup
pm2 start launches the app and restarts it if it crashes. pm2 save freezes the process list, and pm2 startup prints a command you run once with sudo so PM2 — and your app — come back automatically after a server reboot. Confirm it’s alive before moving on:
curl http://127.0.0.1:3000
# expected: Hello from Node behind Nginx
If curl returns your app’s response, the backend half is done.
Step 2: Install Nginx
sudo apt update
sudo apt install -y nginx
sudo systemctl enable --now nginx
sudo systemctl status nginx
Visit http://your-server-ip in a browser — you should see the Nginx welcome page. If you use UFW, open the web ports now:
sudo ufw allow 'Nginx Full'
Step 3: Write the Reverse Proxy Server Block
This is the heart of the Nginx reverse proxy Node.js setup. Create a site config at /etc/nginx/sites-available/nodeapp:
sudo nano /etc/nginx/sites-available/nodeapp
server {
listen 80;
server_name example.com www.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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_cache_bypass $http_upgrade;
}
}
Replace example.com with your domain (or your server’s IP while you’re testing). Here’s what each directive actually does — none of these are decoration:
proxy_pass— the whole point: every request to this location is forwarded to your Node app on port 3000. This is the directive the official proxy module docs build their examples around.proxy_http_version 1.1plus theUpgradeandConnectionheaders — required for WebSocket connections (Socket.io, live dashboards). HTTP/1.1’sUpgradeheader is hop-by-hop, so Nginx’s own WebSocket proxying guide says these must be passed explicitly.Host $host— without this, your app sees127.0.0.1:3000as the host instead of your real domain. Virtual hosting and Express’sreq.hostnamebreak without it.X-Real-IPandX-Forwarded-For— without these, every visitor looks like127.0.0.1in your Node logs. These headers carry the real client IP through the proxy.X-Forwarded-Proto $scheme— tells the app whether the original request was HTTP or HTTPS, so redirects andreq.securebehave correctly once you add SSL below.proxy_cache_bypass $http_upgrade— keeps WebSocket upgrade requests out of any proxy cache.
One gotcha worth knowing: proxy_pass trailing slashes change path handling. location /api/ { proxy_pass http://127.0.0.1:3000/; } strips the /api/ prefix before forwarding, while proxy_pass http://127.0.0.1:3000; (no trailing slash) forwards the full path. This is the single most common source of double-prefix 404s behind Nginx.
Step 4: Enable the Site and Reload Nginx
sudo ln -s /etc/nginx/sites-available/nodeapp /etc/nginx/sites-enabled/
# optional: remove the default site so it doesn't intercept your domain
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl reload nginx
nginx -t tests the config for syntax errors before applying it — always run it before a reload, because a broken config can leave old workers running while blocking new ones. reload (unlike restart) applies the new config without dropping active connections.
Now visit http://example.com. You should see your Node app’s response, served through Nginx. Check the plumbing end to end:
curl -I http://example.com
# look for "Server: nginx" in the response headers
Step 5: Make WebSockets Reliable
The config from Step 3 already proxies WebSocket upgrades correctly. One more thing to know: by default, Nginx closes a proxied connection if the upstream server sends no data for 60 seconds. For long-lived WebSocket connections (chat, live notifications), either raise the timeout:
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_read_timeout 86400s; # 24 hours for idle sockets
# ... rest of headers
}
…or have your app send periodic WebSocket ping frames, which resets the timeout and doubles as a liveness check. Nginx documents both approaches in its WebSocket proxying guide.
Step 6: Add Free HTTPS with Certbot
SSL termination is one of the main reasons to run an Nginx reverse proxy for Node.js in the first place. Certbot fetches a free Let’s Encrypt certificate and edits your Nginx config for you. Your domain’s A record must already point at the server:
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
Certbot asks for an email, agrees to the terms on your behalf after prompting, validates that you control the domain, rewrites your server block with ssl_certificate paths pointing at /etc/letsencrypt/live/example.com/, and asks whether to redirect HTTP to HTTPS — say yes. Renewal is automatic (a systemd timer ships with the package); verify it works with:
sudo certbot renew --dry-run
From this point on, your Node app still speaks plain HTTP on port 3000 — Nginx decrypts everything at the edge. That’s the entire point of terminating TLS at the proxy.
Step 7: Run Multiple Apps with Upstream Blocks
One server, several Node apps. Use an upstream group to spread traffic across multiple processes of the same app, or route different paths to different apps:
upstream node_api {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
keepalive 32;
}
server {
listen 443 ssl;
server_name example.com;
# API -> load-balanced across two Node processes
location /api/ {
proxy_pass http://node_api/;
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;
}
# Admin panel -> a different Node app entirely
location /admin/ {
proxy_pass http://127.0.0.1:4000/;
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;
}
}
Nginx distributes requests across the upstream servers round-robin by default. keepalive 32 reuses connections to the backends instead of opening a new TCP connection per request. (SSL certificate lines omitted for brevity — Certbot will have added them.)
Troubleshooting: Fixing 502 Bad Gateway
A 502 means Nginx is alive but can’t get a valid response from your Node app. Work through this checklist in order:
- Is the app actually listening?
curl http://127.0.0.1:3000must return a response. If it doesn’t, the problem is your app, not Nginx. Checkpm2 statusandpm2 logs node-app. - Port mismatch? The port in
proxy_passmust exactly match the port your app binds to. A typo here is the #1 cause of 502s. - Read the error log.
sudo tail -50 /var/log/nginx/error.logusually names the cause:connect() failed(app down),upstream prematurely closed connection(app crashed mid-request). - Did the app bind to localhost only? If your app listens on
127.0.0.1butproxy_passpoints at the server’s public IP, the connection is refused. - Config actually applied? After every edit:
sudo nginx -t && sudo systemctl reload nginx. Check the active config withsudo nginx -T | grep -A5 server_name.
Bonus: Let Nginx Serve Your Static Files
Node is slow at serving static assets compared to Nginx. If your app has a public/ folder, serve it directly and never hit Node for those requests:
location /static/ {
alias /var/www/nodeapp/public/;
expires 30d;
access_log off;
}
location / {
proxy_pass http://127.0.0.1:3000;
# ... proxy headers
}
Nginx handles caching headers and compression for these files far more efficiently than Express’s express.static ever will.
Wrapping Up
You now have the full production pattern: a Node app bound to localhost and kept alive by PM2, an Nginx reverse proxy in front handling ports 80/443, WebSocket upgrades that actually work, free auto-renewing HTTPS via Certbot, and a troubleshooting checklist for the inevitable 502. The config is small enough to keep in your head and boring enough to never surprise you at 2am — which is exactly what you want from infrastructure.
Further Reading & References
- Nginx official docs: WebSocket proxying — the canonical reference for Upgrade/Connection header handling.
- Nginx official docs: Module ngx_http_proxy_module — every proxy_* directive documented.
- PM2 official quick start — process management, startup scripts, and ecosystem files.
- Certbot — the EFF’s official Let’s Encrypt client with per-OS setup instructions.
- Docker Compose + Nginx: Deploy a Node.js Application with a Reverse Proxy (YouTube) — hands-on video walkthrough of the same architecture.
- Nginx Virtual Hosts + Reverse Proxy for Node.js on AWS EC2 (Medium) — step-by-step with screenshots.
- GitHub gist: Set up nginx as a reverse proxy to node.js — a classic community config including static-file handling.



