Configuring Nginx as a Reverse Proxy for Node.js Applications
Proxy headers, WebSocket upgrades, compression and timeouts: an Nginx config you can reason about.
- nginx
- node.js
- reverse-proxy
- devops
On this page · 14 sections
Running Node.js directly on port 80 or 443 works on a laptop and causes problems in production: you need root privileges to bind low ports, TLS configuration lives inside your app, slow clients hold connections open, and a second app on the same server has nowhere to go. A reverse proxy solves all of this. Nginx is the common choice because it is fast, stable and well understood.
This guide builds a production-minded Nginx configuration for a Node.js app: proxy basics, forwarded headers, keep-alive connections, WebSockets, compression, timeouts, rate limiting, security headers and the usual causes of 502 errors.
The request path
- 1Client
HTTPS on port 443
- 2Nginx
TLS, compression, rate limits, headers
- 3Node.js upstream
HTTP on 127.0.0.1:3000
A minimal working configuration
Place it in /etc/nginx/sites-available/my-app and enable it with a symlink into sites-enabled:
server { listen 80; server_name app.example.com; location / { proxy_pass http://127.0.0.1:3000; 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; }}What each piece does:
proxy_passsends requests to your app.proxy_http_version 1.1is required for keep-alive upstream connections and WebSockets (the default is 1.0).Hostpreserves the hostname the client used.X-Real-IP/X-Forwarded-Forcarry the client's address.X-Forwarded-Prototells the app whether the original request was HTTP or HTTPS, which matters for redirects and secure cookies.
Always test before reloading:
sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl reload nginxMake the app trust the proxy
Your framework needs to know a proxy is in front of it, or it will log Nginx's address and think every request is plain HTTP:
// Expressapp.set("trust proxy", 1); // trust one hop (Nginx)Only trust as many hops as you actually have. Trusting arbitrary forwarded headers lets clients spoof their IP address.
Use an upstream with keep-alive
Opening a new TCP connection to Node for every request wastes time. An upstream block with keepalive reuses connections and lets you add more app instances later:
upstream app_backend { server 127.0.0.1:3000; # server 127.0.0.1:3001; # add instances here for load balancing keepalive 32;}server { listen 80; server_name app.example.com; location / { proxy_pass http://app_backend; proxy_http_version 1.1; proxy_set_header Connection ""; # required for upstream keep-alive 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; }}Support WebSockets
WebSocket connections start as an HTTP request with an Upgrade header. Nginx must pass it through, and it must pick the right Connection value for both normal and upgrade requests. A map in the http context does this:
# in nginx.conf, inside the http { } block (or a file included there)map $http_upgrade $connection_upgrade { default upgrade; '' close;}location /socket.io/ { 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 3600s; # keep idle sockets open longer}Without a raised proxy_read_timeout, Nginx closes idle connections after 60 seconds by default, which looks like random disconnects.
Add HTTPS and redirect HTTP
Certificates from Let's Encrypt are free. The Certbot Nginx plugin edits your config and installs renewal:
sudo certbot --nginx -d app.example.comsudo certbot renew --dry-runThe resulting setup looks like this (Certbot writes the certificate lines for you):
server { listen 80; server_name app.example.com; return 301 https://$host$request_uri;}server { listen 443 ssl; http2 on; server_name app.example.com; ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem; # ... proxy configuration as above ...}Compression, body size and timeouts
server { # ... client_max_body_size 10m; # reject larger uploads early (413) gzip on; gzip_comp_level 5; gzip_min_length 1024; gzip_types text/plain text/css application/json application/javascript image/svg+xml; location / { proxy_pass http://app_backend; # ... proxy_connect_timeout 5s; proxy_send_timeout 30s; proxy_read_timeout 30s; }}Tune timeouts to your slowest legitimate request. Very long timeouts hide hung upstreams and tie up connections.
Compress in one place only. If Node already compresses responses, disable one side to avoid double work.
Serve static assets directly
Nginx is far more efficient than Node at serving files. If your build produces static assets, serve them from disk with long cache headers and let only dynamic requests reach Node:
location /assets/ { root /var/www/my-app/public; expires 1y; add_header Cache-Control "public, immutable"; access_log off;}Rate limiting and basic hardening
Limit abusive request rates before they reach your app:
# http { } contextlimit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;# server/location contextlocation /api/ { limit_req zone=api_limit burst=20 nodelay; limit_req_status 429; proxy_pass http://app_backend;}Add a few safe defaults:
server_tokens off; # do not advertise the Nginx versionadd_header X-Content-Type-Options "nosniff" always;add_header X-Frame-Options "DENY" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;Only add HSTS when you are certain every subdomain you list will work over HTTPS. Rate limits at Nginx complement, not replace, application-level limits for authenticated routes.
Troubleshooting 502 Bad Gateway
502 means Nginx reached a problem talking to the upstream. Work through it in order:
- Is the app running?
pm2 statusorsystemctl status my-app. - Is it on the expected port?
ss -tlnp | grep 3000. If the app binds to a different port, or only to a Unix socket,proxy_passwill fail. - Does it answer locally?
curl -i http://127.0.0.1:3000/health. - What does Nginx say?
sudo tail -n 50 /var/log/nginx/error.logusually names the exact problem (connect() failed,upstream timed out,upstream prematurely closed connection). - Is the app crashing mid-request? Check the application logs.
- Is something blocking the connection? On systems with SELinux,
setsebool -P httpd_can_network_connect 1may be required.
Other common status codes:
| Status | Usual cause |
|---|---|
504 Gateway Timeout | Upstream too slow; raise proxy_read_timeout only after finding why |
413 Request Entity Too Large | Upload exceeds client_max_body_size |
400 Bad Request with large headers/cookies | Increase large_client_header_buffers |
| Redirect loops | App thinks the request is HTTP; forward X-Forwarded-Proto and trust the proxy |
| Wrong client IP in logs | Missing forwarded headers or trust proxy |
Testing the configuration
sudo nginx -t # syntax checkcurl -I http://app.example.com # expect a 301 to HTTPScurl -I https://app.example.com/health # expect 200curl -sI -H "Accept-Encoding: gzip" https://app.example.com/ | grep -i content-encodingcurl -s -o /dev/null -w "%{http_code} %{time_total}s\n" https://app.example.com/For WebSockets, connect with a client and confirm the connection stays open past 60 seconds.
Production considerations
Keep logs rotating (logrotate is configured by default for Nginx packages), monitor 5xx rates, reload rather than restart for config changes, store configuration in version control, and apply security updates regularly. When traffic grows, consider enabling proxy_cache for cacheable responses, or put a CDN in front of Nginx.
Best practices
- Run
nginx -tbefore every reload. - Forward
Host,X-Forwarded-ForandX-Forwarded-Proto, and trust the proxy in your app. - Use
upstreamwithkeepaliveandproxy_http_version 1.1. - Keep Node bound to localhost so only Nginx is public.
- Serve static files from Nginx, compress once, and set explicit timeouts.
Conclusion
An Nginx reverse proxy turns a Node.js process into a production service: it owns the public ports and TLS, shields the app from slow clients and abuse, and gives you a clean place to add caching, compression and load balancing. Start with the minimal block, add the forwarded headers, then layer on the pieces your application actually needs.
Frequently asked questions
+Why put Nginx in front of Node.js?
Nginx terminates TLS, serves on ports 80 and 443 without running Node as root, buffers slow clients, compresses responses, applies rate limits, serves static files efficiently and lets several apps share one server.
+Why do I get 502 Bad Gateway?
Nginx could not get a valid response from the upstream. The app is not running, it listens on a different port or interface than proxy_pass points to, it crashed during the request, or SELinux/firewall rules block the connection. Check the Nginx error log first.
+How do I proxy WebSockets through Nginx?
Use HTTP/1.1 and forward the Upgrade and Connection headers, typically with a map block that sets Connection to upgrade when an Upgrade header is present. Also raise proxy_read_timeout so idle connections are not closed.
+Why does my app see Nginx's IP instead of the client's?
Because the request comes from the proxy. Forward the client address with X-Forwarded-For and X-Real-IP, and tell your framework to trust the proxy (for Express, app.set('trust proxy', 1)).
+What does proxy_set_header Host $host do?
It passes the original Host header to the application. Without it, Nginx sends the upstream's address, which breaks apps that generate absolute URLs or route by hostname.
+How do I reload Nginx without dropping connections?
Run nginx -t to validate the configuration, then reload with systemctl reload nginx. A reload starts new workers with the new configuration and lets old workers finish existing requests.
+Should Nginx or Node handle gzip compression?
Prefer Nginx. It is efficient at compression and keeps CPU work out of your Node process. Avoid compressing twice.