Chapter 8 · Lesson 2 of 8
Web servers and proxies

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.

By the end you will

Run a Node app under systemd on localhost and proxy to it with nginx, with correct headers, path handling and timeouts.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • An Ubuntu server with nginx installed
  • A Node app that listens on a port you choose

nginx sits in front of your Node app

nginx listens on the public ports, ends HTTPS and uses proxy_pass to hand each request to a Node app that only listens on 127.0.0.1.
  1. The visitor connects to nginx on port 80 or 443, the only ports open to the internet.
  2. nginx forwards the request with proxy_pass to the app on 127.0.0.1:3000.
  3. proxy_set_header passes Host and X-Forwarded-For so the app knows the real host and client.
  4. The app answers on its private port and sends the response back to nginx.
  5. nginx returns the response to the visitor over HTTPS.
Static diagram
  1. Visitorport 443nginx
  2. nginxproxy_passNode app
  3. nginxheadersNode app
  4. Node appresponsenginx
  5. 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:

ini
[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.target

Then:

bash
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
curl -I http://127.0.0.1:3000

What 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:

nginx
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 sends 127.0.0.1:3000 as 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: http or https, 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#

nginx
# 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 /users

If 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#

nginx
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#

bash
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 3000

The 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#

  • $host drops the port, $http_host keeps it. Use $host unless the app needs the port as typed.
  • proxy_set_header in a child block replaces the parent’s list. If a location sets any proxy_set_header, it does not inherit the ones from server. Repeat all of them.
  • localhost may resolve to IPv6. proxy_pass http://localhost:3000 can try ::1 while the app listens on IPv4 only. Use 127.0.0.1.
  • Uploads stop at 1 MB. client_max_body_size defaults to 1m and returns 413. Raise it for upload routes.
  • A trailing slash on the location matters for redirects. /api without 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:3000 so only the proxy can reach it.

Troubleshooting#

SymptomLikely causeFix
502 Bad GatewayApp stopped or wrong portsystemctl status myapp, check proxy_pass port. See fix 502
connect() failed (111: Connection refused) while connecting to upstreamNothing listens on 127.0.0.1:3000Start the app or fix the port
upstream timed out (110: Connection timed out) while reading response header from upstreamApp slower than proxy_read_timeoutFix the slow path or raise the timeout for that location
504 Gateway Time-outSame timeout, seen by the clientAs above
413 Request Entity Too LargeBody over client_max_body_sizeRaise it in the server or location
App logs every client as 127.0.0.1App does not trust the proxyEnable trusted proxy setting
Redirect loop or http links on an https siteMissing X-Forwarded-ProtoPass it and make the app read it
API returns 404 only through nginxPrefix not strippedAdd a slash to proxy_pass

Quick reference#

nginx
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;
}
bash
sudo systemctl enable --now myapp
sudo journalctl -u myapp -n 50 --no-pager
sudo tail -n 50 /var/log/nginx/error.log

Next#

Add a certificate in Nginx HTTPS with certbot, or try Caddy first in Caddy from scratch.

Check what you learned4 questions
1Your app must see the original Host header. Which line does that?
2location /api/ { proxy_pass http://127.0.0.1:3000/; } receives /api/users. What does the app get?
3Why bind the Node app to 127.0.0.1 instead of 0.0.0.0?
4A request that takes 90 seconds returns 504. Which directive is the first suspect?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios