Nginx reverse proxy for a Node app: headers, paths, timeouts
An nginx reverse proxy for a Node app forwards requests to a local port with proxy_pass and passes headers so the app still knows the real host, client IP and scheme.
- Updated Nov 27, 2026
- Markdown
Run a Node app under systemd on localhost and proxy to it with nginx, with correct headers, path handling and timeouts.
- An Ubuntu server with nginx installed
- A Node app that listens on a port you choose
nginx sits in front of your Node app
- The visitor connects to nginx on port 80 or 443, the only ports open to the internet.
- nginx forwards the request with proxy_pass to the app on 127.0.0.1:3000.
- proxy_set_header passes Host and X-Forwarded-For so the app knows the real host and client.
- The app answers on its private port and sends the response back to nginx.
- nginx returns the response to the visitor over HTTPS.
Static diagram
- Visitorport 443nginx
- nginxproxy_passNode app
- nginxheadersNode app
- Node appresponsenginx
- nginxHTTPS replyVisitor
A Node app should not listen on port 80 or 443 and should not hold certificates. Run it on a high port on localhost and let nginx face the internet. The part people get wrong is not the proxy_pass line, it is everything around it: headers, slashes, timeouts and making the app believe what the proxy tells it.
How it works#
Nginx accepts the public request, opens a second connection to the app and copies the response back. This is a reverse proxy, described more generally in what is a reverse proxy. The app sees the nginx connection, not the browser, so anything about the original request (host, client address, HTTPS or not) must be passed in headers.
The app runs under systemd so it starts at boot and restarts on a crash. Nginx only needs to know the address. If the app is down, nginx still answers, with 502.
Step 1: Run the app under systemd#
Assume the app is in /srv/myapp and starts with node server.js, listening on 127.0.0.1:3000. Bind to localhost in your code (app.listen(3000, '127.0.0.1')). Create /etc/systemd/system/myapp.service:
[Unit]
Description=My Node app
After=network.target
[Service]
User=www-data
WorkingDirectory=/srv/myapp
Environment=NODE_ENV=production
Environment=PORT=3000
ExecStart=/usr/bin/node server.js
Restart=on-failure
[Install]
WantedBy=multi-user.targetThen:
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
curl -I http://127.0.0.1:3000What you should see: a response straight from the app. Fix this before touching nginx. Secrets belong in an environment file, not in the unit. The node path may differ, check with which node.
Step 2: Write the proxy server block#
Create /etc/nginx/sites-available/example.com:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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;
}
}Host $host: without it nginx sends127.0.0.1:3000as the host, which breaks virtual hosts and absolute URLs in the app.X-Real-IP $remote_addr: the connecting client address.X-Forwarded-For $proxy_add_x_forwarded_for: appends the client address to any list that already came in, so a chain of proxies stays readable.X-Forwarded-Proto $scheme:httporhttps, so the app can build correct links and decide on secure cookies.
Enable and apply it as in the nginx from scratch lesson: link, sudo nginx -t, sudo systemctl reload nginx.
Step 3: Understand the slash on proxy_pass#
# Request /api/users
location /api/ { proxy_pass http://127.0.0.1:3000; } # app gets /api/users
location /api/ { proxy_pass http://127.0.0.1:3000/; } # app gets /usersIf proxy_pass has no URI part, the original path is sent unchanged. If it has any URI part, even a bare /, nginx replaces the matched location prefix with it. Use the second form when the app does not know about the /api/ prefix. Test one nested URL after every change.
Step 4: Set timeouts on purpose#
location / {
proxy_pass http://127.0.0.1:3000;
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}proxy_connect_timeout is the time to open the connection, so a dead app fails fast. proxy_read_timeout is the wait between two reads, not the total request time. Raise it for one slow endpoint rather than the whole site, and see fix 504 gateway timeout when requests are cut off.
Step 5: Make the app trust the proxy#
The headers are only words until the app reads them. In Express, set app.set('trust proxy', 'loopback') so req.ip, req.protocol and secure cookies use X-Forwarded-*. Trust only the proxy address, never true for every hop, or a client can forge X-Forwarded-For. Other frameworks have the same switch, usually named trusted proxies.
Check it worked#
sudo nginx -t && sudo systemctl reload nginx
curl -I http://example.com
curl -s http://127.0.0.1:3000/health
sudo ss -tlnp | grep 3000The ss line should show the app on 127.0.0.1:3000, not 0.0.0.0:3000. From your laptop, curl http://203.0.113.10:3000 should fail to connect. For HTTPS next, go to Nginx HTTPS with certbot.
Edge cases and gotchas#
$hostdrops the port,$http_hostkeeps it. Use$hostunless the app needs the port as typed.proxy_set_headerin a child block replaces the parent’s list. If alocationsets anyproxy_set_header, it does not inherit the ones fromserver. Repeat all of them.localhostmay resolve to IPv6.proxy_pass http://localhost:3000can try::1while the app listens on IPv4 only. Use127.0.0.1.- Uploads stop at 1 MB.
client_max_body_sizedefaults to 1m and returns 413. Raise it for upload routes. - A trailing slash on the location matters for redirects.
/apiwithout a slash redirects to/api/only if a slash location exists, so test both. - The app restarts but nginx keeps a stale error. nginx does not cache upstream failures for long, so a started app works on the next request without a reload.
- Docker apps need a loopback publish. Use
-p 127.0.0.1:3000:3000so only the proxy can reach it.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
502 Bad Gateway | App stopped or wrong port | systemctl status myapp, check proxy_pass port. See fix 502 |
connect() failed (111: Connection refused) while connecting to upstream | Nothing listens on 127.0.0.1:3000 | Start the app or fix the port |
upstream timed out (110: Connection timed out) while reading response header from upstream | App slower than proxy_read_timeout | Fix the slow path or raise the timeout for that location |
504 Gateway Time-out | Same timeout, seen by the client | As above |
413 Request Entity Too Large | Body over client_max_body_size | Raise it in the server or location |
| App logs every client as 127.0.0.1 | App does not trust the proxy | Enable trusted proxy setting |
| Redirect loop or http links on an https site | Missing X-Forwarded-Proto | Pass it and make the app read it |
| API returns 404 only through nginx | Prefix not stripped | Add a slash to proxy_pass |
Quick reference#
location / {
proxy_pass http://127.0.0.1:3000;
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_connect_timeout 5s;
proxy_read_timeout 60s;
}sudo systemctl enable --now myapp
sudo journalctl -u myapp -n 50 --no-pager
sudo tail -n 50 /var/log/nginx/error.logRelated lessons#
- Run a service with systemd: unit file options in more depth.
- Read logs with journalctl: see why the app crashed.
- Deploy an Express app with Docker on a VPS: the containerized version.
Next#
Add a certificate in Nginx HTTPS with certbot, or try Caddy first in Caddy from scratch.
Check what you learned
Frequently asked questions
What does proxy_pass do in nginx?
It forwards the request to the address you give, such as http://127.0.0.1:3000, and sends the response back to the client. It lives inside a location block.
Why does my Node app see 127.0.0.1 as the client IP?
The connection to the app comes from nginx on the same machine. Pass X-Forwarded-For and X-Real-IP, and tell the app to trust the proxy so it reads them.
Does a trailing slash on proxy_pass matter?
Yes. With no path after the address, nginx passes the original URI. With a path or just a slash, nginx replaces the part of the URI that matched the location.
How do I fix 502 Bad Gateway from nginx to Node?
It almost always means nothing is listening where proxy_pass points. Check that the app runs, that the port matches, and read the nginx error log for the exact message.
Sources
Keep going: guides and tutorials
- Self-Hosted Static Site Hosting: Deploy a Folder With Levelrail Self-hosted static site hosting from a plain folder: one deploy command, _redirects, _headers and a custom 404 honored, plus a one command rollback.
- Deploy Next.js on a VPS With Docker, Git Push and HTTPS Deploy a Next.js app to your own VPS with Docker, a health check, HTTPS and rollback. Includes the NEXT_PUBLIC build trap that leaves variables empty.