nginx in front of a Node app on a VPS

Terminate TLS at nginx, bind the Node process to loopback, and pass Host and forwarded headers so Express sees the real client and the original scheme.

I do not let a Node process accept public HTTPS. nginx terminates TLS, the Express app listens on loopback, and only nginx talks to the internet. That is the layout I use for chrishacia.com on a single VPS, and it is the layout I would set up again.

The app still does the work. nginx does the part that should sit at the edge: certificates, host routing, request size limits, and the headers that tell Express who the client was.

This is a tutorial for that split, not a tour of every nginx module.

Why the app should not own port 443

A site of mine usually runs as a Docker Compose stack. The API listens on port 4000 inside the container. Compose publishes that port to `127.0.0.1:4100` on the host, not to `0.0.0.0`. If you can reach Express from the public internet without going through nginx, the rest of this post is decoration.

I want one place that holds the certificate, one place that decides which host name goes to which process, and one place that can reject an oversized upload before it touches the app. nginx is good at those jobs. Express is good at routes, validation, and talking to Postgres. I have already written about why [Express is still a solid default](/journal/express-still-a-solid-default-for-a-typescript-api) for that inner work, and about [release folders and a symlink](/journal/release-folders-and-a-symlink-so-a-deploy-can-roll-back) so a bad deploy has a way back. This post is the piece that sits in front of both.

Binding the published port to loopback is the rule I care about most. If Docker publishes `4100:4000` without the `127.0.0.1` prefix, the container port is reachable on the public interface. I have seen that typo more than once. The proxy can be perfect and still be beside the point.

A server block that is enough

I keep a site in `/etc/nginx/sites-available/` and symlink it into `sites-enabled`, which is the usual Debian layout. The block below is the shape I use for an API that already lives on loopback. Replace the server name and the upstream port with your own.

upstream chrishacia_api {
    server 127.0.0.1:4100;
    keepalive 16;
}

server {
    listen 80;
    listen [::]:80;
    server_name chrishacia.com www.chrishacia.com;

    # Certbot places the HTTP-01 challenge here.
    location /.well-known/acme-challenge/ {
        root /var/www/letsencrypt;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name chrishacia.com www.chrishacia.com;

    ssl_certificate     /etc/letsencrypt/live/chrishacia.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/chrishacia.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    client_max_body_size 25m;

    location / {
        proxy_pass http://chrishacia_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;
        proxy_set_header Connection        "";

        proxy_connect_timeout 5s;
        proxy_send_timeout    60s;
        proxy_read_timeout    60s;
    }
}

A few choices in that block are easy to get wrong, and they are the ones I check first.

`proxy_pass` points at the upstream name and has no path after the port. That matters. If you write `proxy_pass http://127.0.0.1:4100/;` with a trailing URI, nginx replaces the matching part of the request URI. A request to `/api/v1/journal` can arrive at the app as `/` plus a surprise. For an app that already owns the full path, omit the URI.

`Host` is set to `$host`, not left at the default `$proxy_host`. The default would send `127.0.0.1:4100` (or the upstream name) as the host. Virtual-host checks, redirects, and cookie domains then see the loopback address instead of the name the browser used. The proxy_set_header documentation is clear about the default, and it is still the mistake I look for in a new vhost.

`X-Forwarded-Proto` is `$scheme`. Without it, Express will think every request is HTTP, even when the browser used HTTPS, and a redirect or a `Secure` cookie will misbehave.

`Connection` is set to an empty string so the keepalive to the upstream can stay open. The nginx default for a proxied request is `Connection: close`. That is safe. It is also wasteful if every page load opens a new connection to a process on the same machine.

`client_max_body_size` is not a default I leave alone. nginx defaults to one megabyte. Studio media, a contact form with an attachment, or a JSON body that is only slightly ambitious will get a `413` from nginx, and the app will never see the request. I set the limit to the largest upload I actually allow, and I keep the same cap in the app so a bypass of nginx still cannot store more than I meant to accept.

Tell Express it sits behind one proxy

Headers do nothing useful if the app does not trust them. In Express 5 I set `trust proxy` to `1`, because exactly one reverse proxy sits in front of the process.

import express from "express";

const app = express();

// nginx is the only hop in front of this process.
app.set("trust proxy", 1);

app.get("/healthz", (req, res) => {
  res.json({
    ok: true,
    ip: req.ip,
    secure: req.secure,
    host: req.hostname,
  });
});

`req.ip` then uses `X-Forwarded-For`. `req.secure` and `req.protocol` use `X-Forwarded-Proto`. Secure cookies can be marked `secure` and will still work. If I leave `trust proxy` off, I log nginx's address as the client and I get HTTP redirects on an HTTPS site.

I do not set `trust proxy` to `true`. That trusts every address in the chain, including values a client can send. One hop is the truth for this layout.

If you want to confirm the path is right, curl the public host and the loopback port and compare the `ip` and `secure` fields:

curl -sS https://chrishacia.com/healthz
curl -sS http://127.0.0.1:4100/healthz

The first should show your client address and `secure: true`. The second should show a loopback address and `secure: false`. If the first shows `127.0.0.1`, the headers or `trust proxy` are wrong. If the second works from another machine, the bind is wrong.

Certificates

I use Certbot with the nginx plugin, or a webroot challenge against the `/.well-known/acme-challenge/` location above. Either way, the certificate lives on the host, and nginx reads the files from `/etc/letsencrypt/live/`. The app container does not need the private key.

A typical first pass, once the HTTP vhost is in place and nginx is serving the challenge directory, looks like this:

sudo certbot --nginx -d chrishacia.com -d www.chrishacia.com
sudo nginx -t && sudo systemctl reload nginx

I reload only after `nginx -t` succeeds. A broken vhost should not take down every other site on the box. I have more than one product on a VPS, which is a trade-off I already wrote about in [one VPS per product versus a multi-tenant app](/journal/one-vps-per-product-versus-one-multi-tenant-app). A failed `nginx -t` is a cheap way to keep those products from sharing an outage.

Renewal is a timer, not a calendar reminder. After Certbot is installed I confirm the timer is active and I do a dry run when I change the vhost:

sudo systemctl status certbot.timer
sudo certbot renew --dry-run

If a renew needs nginx to be able to serve the challenge path, that location has to stay on port 80 even after the rest of the site redirects to HTTPS. I have broken renewals by redirecting `/.well-known` along with everything else.

Timeouts, WebSockets, and the files I do not proxy

The 60 second read timeout in the block above is a starting point for ordinary JSON and page requests. A long download, a large upload, or a request that waits on a slow upstream may need more. I would rather raise the timeout for that location than raise it for the whole server.

If a path needs a WebSocket, the headers change. You have to pass the upgrade:

location /ws {
    proxy_pass http://chrishacia_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;
    proxy_set_header Upgrade           $http_upgrade;
    proxy_set_header Connection        "upgrade";
    proxy_read_timeout 3600s;
}

I only add that block when I actually have a WebSocket endpoint. Putting `Connection "upgrade"` on every location will break ordinary keepalive.

Static files are a judgment call. For chrishacia.com the public site and the API share a release, and I am fine letting the app serve the HTML. If I had a purely static front-end, I would let nginx serve the built files from the current release folder and proxy only `/api/`. That is a simpler cache story. It is also a second root to keep in sync with the symlink layout, so I do not do it just to feel tidy.

What I check before I call it done

1. `nginx -t` is clean, and a reload does not drop the other vhosts on the box. 2. `ss -lntp` (or `ss -lnt`) shows port 4100 bound to `127.0.0.1`, not `0.0.0.0` or `*`. 3. `https://` of the public host returns the app, and `http://` redirects to `https://` without a certificate warning. 4. `/healthz` through the public host reports a real client IP and `secure: true`. 5. An upload just under `client_max_body_size` succeeds, and one just over it returns `413`. 6. A Certbot dry run still works after the redirect to HTTPS is in place.

If something fails, I look at `/var/log/nginx/error.log` before I restart the app. A `connect() failed (111: Connection refused)` is a down or mis-bound upstream. A `no live upstreams` is the same problem with a different message. A blank `413` in the browser with no app log line is the body-size cap.

What I would not do

I would not put a self-signed certificate on the Node process and then "also" have nginx do TLS. One terminator is enough.

I would not run `proxy_pass` to a public IP of the same machine. That path leaves the VPS, or at least leaves loopback, and it is a good way to fight your own firewall.

I would not copy a 40-line SSL cipher block from a blog post when Certbot already dropped a maintained `options-ssl-nginx.conf` on the box. I would rather include that file and follow Mozilla's SSL config if I need to change it on purpose.

I would not start this work by inventing a load-balanced upstream. One process on loopback, one nginx in front, certificates that renew, and a bind I can prove with `ss` will carry a personal site. The day I have two app processes, I can add a second server line to the upstream block. I would not start there.

The test I trust is still the simple one. Curl the public URL. Confirm the app never had to see the internet. Then leave nginx to do the job I actually hired it for.

Back to Journal