15 min read
What is a reverse proxy and how to set up nginx
In one sentence: A reverse proxy is a server that receives visitors' requests and passes them on to your program, which stays behind, out of sight. In the shop it's nginx: it listens on ports 80 and 443, passes each request on to the API on 127.0.0.1, tells it who made it with X-Forwarded-For, and answers itself, with a 502 or a 504, when the API can't.
What you will learn
- Explain what a reverse proxy does and why almost every website has one in front.
- Read the shop's nginx file, block by block, and install it on your server.
- Make the API know each visitor's IP, trusting X-Forwarded-For only when nginx sends it.
- Tell a 502 from a 504 and find out in nginx's error.log what happened.
Before you start, read: 03-production.md
The problem
Section titled “The problem”The shop already works on your server, but nobody can get in. Marta opens http://192.168.5.15:3000 and nothing comes back: in lesson 3, the API was published only on 127.0.0.1, on purpose.
You could publish it for everyone, but Node would have to take care of HTTPS, and the API would bypass the firewall, as you saw in lesson 2. And the day it hangs, Marta will see a tab that loads forever.
Almost every website solves it the same way: in front of the program they put another server that faces the world for it. In this lesson, that server is nginx.
The analogy
Section titled “The analogy”The analogy
Think of a company’s switchboard. You call a single number, the company’s, and the operator puts you through to the extension you’re looking for.
As she puts you through, she tells her colleague which number you’re calling from. If nobody picks up the extension, she’s the one who answers you: “I can’t put you through.” And if two colleagues handle the same thing, she shares the calls between them.
Where the analogy breaks down
- The operator understands the conversation; nginx doesn’t. It doesn’t know what an order is or check passwords: the API does that.
- An operator can see whether her colleague is at their desk. nginx doesn’t ask: it finds out when a real request fails.
How it really works
Section titled “How it really works”A server that faces the world for another
Section titled “A server that faces the world for another”A proxy is a go-between. An office’s proxy works for whoever is browsing: it goes out to the internet on their behalf. A Reverse proxyA server that receives visitors’ requests and passes them on to the programs behind it, which stay out of sight. It usually takes care of HTTPS, spreads the work across several copies and answers with an error if the program behind it fails. nginx and Caddy are two of the most used.Go to definition works for the server: it receives what arrives from the internet and passes it on to the program behind it.
- API (127.0.0.1:3000) → nginx (port 443)200 and the products
- nginx (port 443) → Marta's browser200 and the products
What having it in front gives you:
- A single door. Only nginx listens outside, on the 80 and 443 you opened in the firewall: the web server we promised you in Phase 7. With several names, it passes each one on to its program.
- HTTPS, in one place. nginx decrypts, and the API speaks plain HTTP inside.
- A cushion for slow clients. nginx collects the API’s response and hands it to the visitor at their own pace, and the API is free again.
- Clear errors and several copies. If the API doesn’t answer, nginx says so with a code; and it can share the work between two copies.
In Phase 1 we told you your program would listen on 3000 as its own user, and nginx, on 80, would pass the requests on to it. Here it is.
The shop’s site: nginx/shop.conf
Section titled “The shop’s site: nginx/shop.conf”The 35-production folder brings the shop’s nginx site, nginx/shop.conf. First, who it passes the requests on to:
# The copies of the API nginx knows: the one on port 3000 and the one on 3001 (docker compose up# --scale api=2). With a single copy, 3001 is empty: nginx tries it, it fails and it stops trying# for fail_timeout. This is nginx's passive health check: it doesn't ask whether a copy is alive, it# looks at what happens with the real requests. With both down, the visitor gets 502 (Bad Gateway).upstream shop { server 127.0.0.1:3000 max_fails=1 fail_timeout=10s; server 127.0.0.1:3001 max_fails=1 fail_timeout=10s;}An upstream is a group of servers with a name, shop. It has two because the API is published on the range 127.0.0.1:3000-3001: a single copy can land on either port, and in our tests it went from 3000 to 3001 when we started it again.
With a single copy, the empty port leaves a connect() failed line in the error.log now and then, even though the shop answers fine: nginx tries it, fails, moves on to the other one and sets it aside for 10 seconds.
Port 80 only redirects:
# Port 80: everything is redirected to HTTPS, except the challenge Let's Encrypt uses to check that# the domain is yours (certbot answers it; lesson 5).server { listen 80; listen [::]:80; server_name shop.example;
location /.well-known/acme-challenge/ { root /var/www/html; }
location / { return 301 https://$host$request_uri; }}server_name: the name it answers to. With a single site enabled, it answers to any; in lesson 5 you’ll put yours.return 301 https://$host$request_uri: a RedirectAn HTTP response that says “what you’re looking for is at another address.” It carries a code starting with 3, such as 301, and the Location header with the new address. The browser requests it on its own, without you doing anything.Go to definition to the same address, withhttps./.well-known/acme-challenge/: the exception Let’s Encrypt will need.
Port 443 decrypts the HTTPS:
# Port 443: HTTPS, and the shop behind (the block goes on: what follows is inside it).server { listen 443 ssl; listen [::]:443 ssl; http2 on; server_name shop.example;
# The server's certificate and its key. In lesson 4, a provisional self-signed one (curl -k); # lesson 5 replaces it with one signed by your own certificate authority (openssl). That way it # works without a domain: the browser warns because it doesn't know that authority, and curl # --cacert accepts it. ssl_certificate /etc/ssl/shop/shop.crt; ssl_certificate_key /etc/ssl/shop/shop.key; # With a domain and Let's Encrypt, certbot --nginx replaces the two lines above with these (or # you replace them), with your domain's name in the folder: # ssl_certificate /etc/letsencrypt/live/shop.example/fullchain.pem; # ssl_certificate_key /etc/letsencrypt/live/shop.example/privkey.pem;listen 443 ssl needs the certificate and its key, in /etc/ssl/shop/: without them, nginx -t fails. Today you’ll create a provisional one, and the real one comes in lesson 5. http2 on turns on HTTP/2HTTP stands for HyperText Transfer Protocol.The 2015 version of HTTP. It says the same as HTTP/1.1, but cut into pieces and in a format made for machines, not text, and it carries many requests at once over a single TCP connection. Browsers only use it with HTTPS.Go to definition.
And what happens with each request:
# HTTP/1.1 with the API, for long connections, and the switch to WebSocket.proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_header;
location / { proxy_pass http://shop;}proxy_pass http://shop: pass it on to theshopgroup, overhttp: inside the server there’s no need to encrypt.proxy_http_version 1.1,UpgradeandConnection: what a WebSocket needs, with thismapfrom the top of the file:
# What a connection that switches to WebSocket asks for (the /echo route): if the browser sends# Upgrade, nginx passes it to the API; if not, it doesn't send the Connection header.map $http_upgrade $connection_header { default upgrade; '' '';}Upgrade and Connection only count for one hop: a proxy doesn’t forward them, so nginx sets them by hand. The map gives $connection_header the value upgrade when the browser asks to switch to WebSocket, and leaves it empty (nginx doesn’t send it) when it doesn’t.
The visitor’s IP: X-Forwarded-For
Section titled “The visitor’s IP: X-Forwarded-For”Behind nginx, the API sees every request arrive from 172.18.0.1, the GatewayThe router your computer sends everything that isn’t for its own local network to. At home it is your router, for example 192.168.1.1.Go to definition of Compose’s network: Docker forwards what comes in through a published port, and the API sees it coming from there. That’s why lesson 3 pinned the subnet.
With that address alone, Phase 6’s attempt limit counts the whole internet as one IP. We checked it with no TRUSTED_PROXY in .env:
$ docker compose -f compose.production.yaml exec redis redis-cli --scan"limits:accounts-ip:172.18.0.1"…Five accounts an hour for the whole shop: a single attacker would leave everyone else out. We warned you in Phase 6: behind a proxy, everything comes from it. The fix is a few headers nginx adds:
# What the API needs to know about whoever makes the request, because it only sees nginx. All# the locations below inherit them (if a location sets a proxy_set_header of its own, it stops# inheriting them).# Host the address the visitor typed# X-Forwarded-For what the header already carried (which the visitor could have written)# and, at the end, the visitor's IP, which nginx adds: the API reads the# last entry. It only trusts the header if the connection comes from# TRUSTED_PROXY, the address nginx talks to it from (with Docker, the# network's gateway), which isn't the visitor's# X-Forwarded-Proto https: the visitor used HTTPS, even if it reaches the API over httpproxy_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: the name the visitor typed.X-Real-IP: their IP, alone. The API doesn’t use it.- X-Forwarded-ForThe header in which a proxy tells the program behind it which IP the request came from, because that program only sees the proxy’s. Each proxy adds an address to the end of the list. Anyone can write it, so the only entry to trust is the one your own proxy added.Go to definition: with
$proxy_add_x_forwarded_for, whatever the request already carried and, at the end, the visitor’s IP. If Marta sendsX-Forwarded-For: 203.0.113.7, the API gets203.0.113.7, 192.168.5.100. Marta wrote the first one; nginx, the last. X-Forwarded-Proto:https, the protocol the visitor used. The shop doesn’t use it; a program that builds links does.
The API only trusts nginx
Section titled “The API only trusts nginx”Anyone can write the header. That’s why the API only reads it if the request comes from the address in TRUSTED_PROXY, 172.18.0.1, and then keeps the last entry:
// The IP of whoever makes the request. By default, the one on the other side of the connection.// Behind a proxy (Nginx, Phase 8) that would always be the proxy's (with Docker, the network's// gateway, like 172.18.0.1), and the real one arrives in X-Forwarded-For. But anyone can write that// header, so it's only read if the connection comes from an IP in TRUSTED_PROXY; from any other, it// is ignored. And the last entry of the list is taken, the one our proxy added: the earlier ones// could have been written by the client. With app.request (in the tests) there's no connection, and// the one the test passes is used, or "unknown".export function ipOfWithProxies(c: Context, proxies: string[]): string { let connection: string; try { connection = getConnInfo(c).remote.address ?? 'unknown'; } catch { return 'unknown'; } if (!proxies.map(normalizeIp).includes(normalizeIp(connection))) return connection; const last = c.req.header('X-Forwarded-For')?.split(',').at(-1)?.trim(); return last ? last : connection;}
export function ipOf(c: Context): string { return ipOfWithProxies(c, config.TRUSTED_PROXY);}getConnInfo(c).remote.address: the address on the other side of the connection. If it isn’t a trusted proxy’s, the header is ignored..split(',').at(-1): splits the list at the commas and takes the last entry, nginx’s.
It’s this step’s code change. It has a gap: whatever connects to 127.0.0.1:3000 from the server itself also arrives from 172.18.0.1, and can write any header it wants:
$ curl -sS -i -H 'X-Forwarded-For: 203.0.113.7' --json '{"email":"fake@shop.example","password":"long-password-of-the-fake-account"}' http://127.0.0.1:3000/v2/accounts | grep -iE '^HTTP|^ratelimit:'HTTP/1.1 201 Createdratelimit: "accounts-ip";r=4;t=3600$ docker compose -f compose.production.yaml exec redis redis-cli --scan"limits:accounts-ip:203.0.113.7""limits:accounts-ip:192.168.5.100"Only you log in to your server, so it isn’t serious. On a shared one, anyone with an account could get around the limit.
When the API fails: 502 and 504
Section titled “When the API fails: 502 and 504”In Phase 2 you saw that 502 and 504 say “the one behind me failed.” Now the one in front is yours:
| Code | What happened to nginx | In nginx’s error.log |
|---|---|---|
502 Bad Gateway |
It couldn’t talk to the API: nobody is listening on the port | connect() failed (111: Connection refused) |
504 Gateway Time-out |
The API accepted the request, but didn’t answer within 60 seconds | upstream timed out (110: Connection timed out) |
The 60 seconds are proxy_read_timeout. The error.log always says what happened: it’s the first place to look.
When a server in the upstream fails, nginx tries the next one, and gives you the code of the last attempt. It’s proxy_next_upstream: by default it moves on if it couldn’t connect or the time ran out; a 500 from the API is passed through as it is. A POST already sent isn’t retried (since nginx 1.9.13, no method that isn’t IdempotentSaid of an operation that leaves things in the same state whether you do it once or ten times. In HTTP, GET, PUT and DELETE are idempotent and POST isn’t, so repeating a POST can create two orders.Go to definition, as you saw in Phase 2): it could happen twice. In “Try it”, a sign-in waited 60 seconds and got 504, without trying the other port.
Two copies, and nginx finds out on its own
Section titled “Two copies, and nginx finds out on its own”With two copies of the API, like Phase 7’s --scale api=2, nginx shares out the requests: it’s a Load balancerWhat spreads requests across several copies of the same program, so that none of them carries everything and, if one goes down, the others keep serving. It can be a program, like nginx with its upstream block, or a service from a cloud provider.Go to definition.
nginx doesn’t ask Docker’s HealthcheckA command Docker runs every few seconds inside a container to find out whether its program really works, not just whether it’s running. If it ends well, the container is healthy; after several failures in a row, it’s unhealthy. Compose uses it to wait for a service before starting the ones that depend on it.Go to definition from Phase 7. It watches the real requests: with max_fails=1, one failure sets that copy aside for fail_timeout=10s. It’s a passive check; the active ones belong to NGINX Plus, the paid version. The healthcheck is used by Compose and, in lesson 6, by the deployment.
Something we saw while testing: if every copy failed within those 10 seconds, nginx answers 502 straight away, even if the API is already back:
2026/10/18 02:05:47 [error] 11339#11339: *25 no live upstreams while connecting to upstream, client: 192.168.5.100, server: shop.example, request: "GET /health HTTP/2.0", upstream: "http://shop/health", host: "192.168.5.15"Events that don’t wait: SSE and WebSocket
Section titled “Events that don’t wait: SSE and WebSocket”An order’s events, from Phase 4, are a response that doesn’t end. There we promised you proxy_buffering off:
# An order's events (Server-Sent Events): a response that never ends and arrives in chunks.# It gets its own location for two reasons:# - proxy_buffering off: with buffering (the default), nginx keeps what the API sends until it# has a whole block. Measured in the lesson: over HTTP/1.1, almost never does# even the first event get through; over HTTP/2, nginx does let them out as they come.# - proxy_read_timeout 1h: if the API goes 60 seconds without sending anything (the default),# nginx cuts the connection. Measured: at exactly 60 s, an nginx error in the log.location ~ ^/v2/orders/[^/]+/events$ { proxy_pass http://shop; proxy_buffering off; proxy_read_timeout 1h;}We measured it by removing this location, following an order and cancelling it after 3 seconds:
- Over HTTP/1.1, almost nothing arrived: nginx held on to the events. Only the first request after reloading it got them. Over HTTP/2, they did arrive.
- After 60 seconds without events, nginx cut the connection.
- With the
location, the events always arrived right away, and nginx waits up to an hour between one and the next.
The cut, following an order with Marta’s session: -N makes curl write each event as soon as it arrives, without holding on to it, and marta.txt is the cookie file where curl saved her session when she signed in (-c), which -b sends.
$ time curl -k -N -b marta.txt https://192.168.5.15/v2/orders/34/eventsevent: statusdata: {"id":34,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-18T00:09:08.935Z","customerId":2}
curl: (92) HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2)
real 0m59.828s…proxy_read_timeout 1h only applies to this route: raising it for all of them would hide a slow API.
The WebSocket echo, /echo, also goes quiet for long stretches:
# The WebSocket echo (/echo): a connection that can go a long time without sending anything. With# the default 60 seconds, nginx would cut it; here, an hour.location = /echo { proxy_pass http://shop; proxy_read_timeout 1h;}With Phase 4’s request to switch protocols, nginx answers HTTP/1.1 101 Switching Protocols.
Caddy, the alternative
Section titled “Caddy, the alternative”Caddy is another reverse proxy, more modern, that gets and renews HTTPS certificates on its own. We use nginx because you already installed it in Phase 2, and it’s the one you’ll find most on servers and in job offers.
Try it
Section titled “Try it”The goal: get from your computer to the shop through nginx, make the API know your IP even if you try to fool it, and see a 502 and a 504 with your own eyes.
The outputs are from lesson 3’s VM, 192.168.5.15: use your server’s IP. “Your computer” was another machine, 192.168.5.100; your IP, your times, IDs and ports will be different. On the server, work in /opt/shop.
Install the site
Section titled “Install the site”On a freshly rented VPS, first install nginx with sudo apt install -y nginx. On the server, look at what nginx has now:
1. The enabled sites
ls -l /etc/nginx/sites-enabled/What you will see:
total 0lrwxrwxrwx 1 root root 34 Oct 18 02:02 default -> /etc/nginx/sites-available/defaultlrwxrwxrwx 1 root root 31 Oct 18 02:02 shop -> /etc/nginx/sites-available/shopNow a provisional certificate, self-signed: it’s signed by its own key, with no authority vouching for it. nginx starts with it, but neither curl nor the browser trusts it; lesson 5 replaces it.
2. A provisional certificate
sudo mkdir -p /etc/ssl/shopsudo openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 30 \-subj "/CN=shop.example" -keyout /etc/ssl/shop/shop.key -out /etc/ssl/shop/shop.crtsudo ls -l /etc/ssl/shopWhat you will see:
-----total 8-rw-r--r-- 1 root root 583 Oct 18 02:04 shop.crt-rw------- 1 root root 241 Oct 18 02:04 shop.keyopenssl req -x509 creates a key and a certificate signed with it, for shop.example, valid for 30 days. -nodes leaves the key without a password, so nginx can read it when it starts. Look at -rw-------: the key, for root only.
3. Copy it, enable it and reload
sudo cp nginx/shop.conf /etc/nginx/sites-available/shopsudo ln -sf /etc/nginx/sites-available/shop /etc/nginx/sites-enabled/shopsudo rm /etc/nginx/sites-enabled/defaultsudo nginx -t && sudo systemctl reload nginxWhat you will see:
nginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successfulcpoverwrites Phase 2’s shop, andln -sfcreates the link or replaces it.rm …/defaultturns off the welcome page, the default site on 80: if it stays, whoever types the IP will see “Welcome to nginx.”nginx -t && … reload, as in Phase 2.
If nginx -t says cannot load certificate, repeat step 2. Now curl localhost:8080/ gives Failed to connect: Phase 2’s shop is gone.
The shop, from your computer
Section titled “The shop, from your computer”On your computer, ask for the shop over http:
4. Over http, a redirect
curl -i http://192.168.5.15/healthcurl.exe -i http://192.168.5.15/healthWhat you will see:
HTTP/1.1 301 Moved PermanentlyServer: nginx/1.28.3 (Ubuntu)…Location: https://192.168.5.15/health…nginx answers on its own: 301 to the same address with https. On Windows, curl.exe: in PowerShell, curl is a different command.
5. Over https
curl https://192.168.5.15/healthcurl -k -i https://192.168.5.15/healthcurl.exe https://192.168.5.15/healthcurl.exe -k -i https://192.168.5.15/healthWhat you will see:
curl: (60) SSL: certificate subject name 'shop.example' does not match target hostname '192.168.5.15'…HTTP/2 200server: nginx/1.28.3 (Ubuntu)…strict-transport-security: max-age=15552000; includeSubDomains…x-request-id: 04aeb734-a084-4e99-92fd-735fc84d148ex-xss-protection: 0
{"status":"ok"}On its own, curl refuses. (60): the certificate is for shop.example, not for the IP, and no authority curl knows signed it (the text changes depending on your system). -k skips that check: the connection is encrypted, but without knowing who you’re talking to. Use it only to test your own server; lesson 5 shows you how to drop it.
With -k, HTTP/2 200 and {"status":"ok"}: the API answers you through nginx, with server: nginx next to its headers. If you get 502, the API is stopped.
Who are you to the API?
Section titled “Who are you to the API?”On the server, check that TRUSTED_PROXY, in .env since lesson 3, is the network’s gateway:
6. The trusted address
docker network inspect shop_default --format "{{(index .IPAM.Config 0).Gateway}}"grep ^TRUSTED_PROXY .envWhat you will see:
172.18.0.1TRUSTED_PROXY=172.18.0.1They must match. If they don’t, change TRUSTED_PROXY and recreate the API: docker compose -f compose.production.yaml up -d api.
From your computer, create Marta’s account, and another one with a made-up X-Forwarded-For:
7. Two new accounts
curl -k -sS -i --json '{"email":"marta@shop.example","password":"a-long-password-for-marta-27"}' https://192.168.5.15/v2/accounts | grep -iE '^HTTP|^ratelimit|^\{'curl -k -sS -i -H 'X-Forwarded-For: 203.0.113.7' --json '{"email":"pablo@shop.example","password":"another-long-password-for-pablo-38"}' https://192.168.5.15/v2/accounts | grep -iE '^HTTP|^ratelimit|^\{''{"email":"marta@shop.example","password":"a-long-password-for-marta-27"}' | Set-Content marta.json'{"email":"pablo@shop.example","password":"another-long-password-for-pablo-38"}' | Set-Content pablo.jsoncurl.exe -k -sS -i -H "Content-Type: application/json" --data "@marta.json" https://192.168.5.15/v2/accountscurl.exe -k -sS -i -H "X-Forwarded-For: 203.0.113.7" -H "Content-Type: application/json" --data "@pablo.json" https://192.168.5.15/v2/accountsWhat you will see:
HTTP/2 201ratelimit: "accounts-ip";r=4;t=3600ratelimit-policy: "accounts-ip";q=5;w=3600{"id":2,"email":"marta@shop.example","role":"customer"}HTTP/2 201ratelimit: "accounts-ip";r=3;t=3600ratelimit-policy: "accounts-ip";q=5;w=3600{"id":3,"email":"pablo@shop.example","role":"customer"}Look at r, the accounts you have left this hour: 4 and then 3. The made-up header didn’t work: both come out of your IP’s count. On Windows, the JSON goes in a file, because PowerShell handles quotes differently.
If you get r=4 twice, go back over step 6.
8. What Redis wrote down
docker compose -f compose.production.yaml exec redis redis-cli --scanWhat you will see:
"limits:accounts-ip:192.168.5.100"On the server, --scan lists Redis’s keys. Just one, with your computer’s IP: neither 172.18.0.1 nor 203.0.113.7.
A 502: the API stopped
Section titled “A 502: the API stopped”On the server, stop the API:
9. Stop the API
docker compose -f compose.production.yaml stop apiWhat you will see:
[+] stop 1/1✔ Container shop-api-1 Stopped 0.1snginx keeps running; behind it, nobody.
10. From your computer
curl -k -i https://192.168.5.15/healthcurl.exe -k -i https://192.168.5.15/healthWhat you will see:
HTTP/2 502server: nginx/1.28.3 (Ubuntu)date: Sun, 18 Oct 2026 00:04:36 GMTcontent-type: text/htmlcontent-length: 166
<html><head><title>502 Bad Gateway</title></head><body><center><h1>502 Bad Gateway</h1></center><hr><center>nginx/1.28.3 (Ubuntu)</center></body></html>The page is nginx’s, and it arrives straight away.
11. What nginx says, and the way back
sudo tail -2 /var/log/nginx/error.logdocker compose -f compose.production.yaml start apiWhat you will see:
2026/10/18 02:04:36 [error] 11339#11339: *16 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.5.100, server: shop.example, request: "GET /health HTTP/2.0", upstream: "http://127.0.0.1:3001/health", host: "192.168.5.15"2026/10/18 02:04:36 [error] 11339#11339: *16 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.5.100, server: shop.example, request: "GET /health HTTP/2.0", upstream: "http://127.0.0.1:3000/health", host: "192.168.5.15"…One line per port in the upstream: Connection refused on both. client is your computer. start starts the API again.
A 504: the API hung
Section titled “A 504: the API hung”docker compose pause freezes the container: it accepts connections, but doesn’t answer. On the server:
12. Freeze the API
docker compose -f compose.production.yaml pause apiWhat you will see:
[+] pause 1/1✔ Container shop-api-1 Paused 0.0sPaused: the API’s process, stopped dead.
From your computer, Marta signs in, a POST nginx doesn’t retry. It takes a minute.
13. A minute of waiting
time curl -k -i --json '{"email":"marta@shop.example","password":"a-long-password-for-marta-27"}' https://192.168.5.15/v2/sessioncurl.exe -k -i -H "Content-Type: application/json" --data "@marta.json" https://192.168.5.15/v2/sessionWhat you will see:
HTTP/2 504server: nginx/1.28.3 (Ubuntu)date: Sun, 18 Oct 2026 00:07:07 GMTcontent-type: text/htmlcontent-length: 176
<html><head><title>504 Gateway Time-out</title></head><body><center><h1>504 Gateway Time-out</h1></center><hr><center>nginx/1.28.3 (Ubuntu)</center></body></html>
real 0m59.783suser 0m0.010ssys 0m0.007stime measures almost 60 seconds, the proxy_read_timeout (PowerShell has no time). With a GET you could see a 502 after that minute: nginx retries it on the empty port.
14. The API wakes up… and handles it
sudo tail -1 /var/log/nginx/error.logdocker compose -f compose.production.yaml unpause apidocker compose -f compose.production.yaml logs api --since 90s | grep -v /healthWhat you will see:
2026/10/18 02:07:07 [error] 11339#11339: *30 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.5.100, server: shop.example, request: "POST /v2/session HTTP/2.0", upstream: "http://127.0.0.1:3001/v2/session", host: "192.168.5.15"[+] unpause 1/1✔ Container shop-api-1 Unpaused 0.0sapi-1 | {"level":30,"time":1792282028062,"pid":1,"hostname":"d7cad8257879","requestId":"d2cfcce7-e1bd-4856-b26e-375e138e5ef8","method":"POST","path":"/v2/session","status":200,"ms":80,"msg":"request"}upstream timed out: the 504. And the surprising part: when it woke up, the API handled the sign-in, with "status":200, even though nginx had already answered Marta. A 504 doesn’t undo anything: the request may have gone through, or not.
Two copies behind nginx
Section titled “Two copies behind nginx”15. Two copies
docker compose -f compose.production.yaml up -d --scale api=2docker compose -f compose.production.yaml ps api --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"What you will see:
…NAME STATUS PORTSshop-api-1 Up 6 minutes (healthy) 127.0.0.1:3001->3000/tcpshop-api-2 Up 12 seconds (healthy) 127.0.0.1:3000->3000/tcpOne copy on each port of the upstream.
From your computer, four requests; then, on the server, who handled them:
16. Who answers?
for i in 1 2 3 4; do curl -k -s -o /dev/null -w "%{http_code} " https://192.168.5.15/v2/products; done; echo# on the server:docker compose -f compose.production.yaml logs api --since 20s | grep /v2/products | cut -c1-901..4 | ForEach-Object { curl.exe -k -s -o NUL -w "%{http_code} " https://192.168.5.15/v2/products }# on the server:docker compose -f compose.production.yaml logs api --since 20s | grep /v2/products | cut -c1-90What you will see:
200 200 200 200api-2 | {"level":30,"time":1792282244175,"pid":1,"hostname":"2b20e29acf11","requestId":"bapi-2 | {"level":30,"time":1792282244214,"pid":1,"hostname":"2b20e29acf11","requestId":"4api-1 | {"level":30,"time":1792282244201,"pid":1,"hostname":"d7cad8257879","requestId":"aapi-1 | {"level":30,"time":1792282244226,"pid":1,"hostname":"d7cad8257879","requestId":"5The for loop repeats the curl four times, and -w writes only the code. Two for each copy: nginx shares them out.
Now bring one copy down and ask again:
17. One copy down
docker stop shop-api-2# on your computer, the four requests again; then, on the server:sudo tail -2 /var/log/nginx/error.logdocker start shop-api-2What you will see:
shop-api-2200 200 200 200…2026/10/18 02:10:44 [error] 21465#21465: *195 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.5.100, server: shop.example, request: "GET /v2/products HTTP/2.0", upstream: "http://127.0.0.1:3000/v2/products", host: "192.168.5.15"shop-api-2All four, 200. One ran into the copy that was down, the one on 3000: nginx passed it on to the other one and set that copy aside for 10 seconds. It’s the passive check. docker start starts it again.
docker compose -f compose.production.yaml up -d, without --scale, goes back to one copy. The shop is left with nginx in front: lesson 5 gives it a name and a real certificate.
On a VPS, everything is the same with its public IP, but from now on anyone on the internet can get in. The provider’s firewall must also let 80 and 443 through (lesson 2).
You have already seen it
Section titled “You have already seen it”- This website.
curl -I https://backenddesdecero.comanswers withserver: cloudflare: there’s a reverse proxy in front, Cloudflare’s. - Other websites’ error pages. A “502 Bad Gateway” with
nginxorcloudflareat the bottom isn’t from the website: it’s from the proxy, saying the website behind it isn’t answering.
Common mistakes
Section titled “Common mistakes”- Leaving the
defaultsite. Over http, the server’s IP shows “Welcome to nginx” instead of redirecting to the shop. - Reading the first entry of
X-Forwarded-For, or trusting it wherever it comes from. Only the last one, and only if the connection comes from your proxy. - A
TRUSTED_PROXYthat isn’t your network’s gateway. All your visitors share one limit. - A
locationwith its ownproxy_set_header. It stops inheriting the outer ones and losesX-Forwarded-For. If you add one, repeat them all. - Raising
proxy_read_timeoutfor everything. It hides hangs: raise it only where it’s needed.
Summary
Section titled “Summary”- A reverse proxy receives the requests and passes them on to your program, which stays behind: one door, HTTPS in one place and clear errors.
proxy_pass http://shoppasses each request on to theupstream, with the API’s two possible ports.- The API reads the last entry of
X-Forwarded-For, nginx’s, and only if the request comes fromTRUSTED_PROXY. 502: nobody answers.504: the API didn’t respond within 60 seconds. Theerror.logsays which.- SSE events need
proxy_buffering offand a longproxy_read_timeout, only on their route.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Module ngx_http_proxy_module, from nginx’s documentation:
proxy_pass,proxy_set_header,proxy_buffering,proxy_read_timeoutandproxy_next_upstream. - Module ngx_http_upstream_module:
upstream,max_failsandfail_timeout. - WebSocket proxying: the
mapand theUpgradeandConnectionheaders. - X-Forwarded-For, on MDN: what it contains and why you shouldn’t trust it.
- Automatic HTTPS, from Caddy’s documentation: how it gets the certificates on its own.