Reverse Proxy & Load Balancing — DevOps

A reverse proxy (here nginx) is a server in front of an app: nginx takes requests from the internet and passes them to the app with proxy_pass…

notes-api's rate limit (a limit on how many requests each IP may send) suddenly blocks everyone at once. You open the log: every request, from any visitor, is recorded as coming from the same IP, 127.0.0.1.

127.0.0.1 is web-1's own address. So all those requests came through another program on web-1: a reverse proxy, a server that stands in front of an app. It takes requests from the internet, passes them on to the app, then returns the app's answer to the sender. Picture a waiter in a restaurant. Guests don't walk into the kitchen. They order from the waiter, the waiter takes the order to the kitchen, then brings the food back. The kitchen can't be seen from outside. If the kitchen is closed, the waiter is the one who says "sorry, the kitchen is closed". And if there are two cooks, the waiter gives them the orders in turns. Here the waiter is nginx, the kitchen is the notes-api app, and the guests are the visitors. Two cooks are two running copies of the app.

Nginx in front of notes-api

In the Nginx Basics lesson, nginx on web-1 served static files. Now the requests that match location / are passed on to notes-api's Express app, which listens (waits for requests) on 127.0.0.1:3000:

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

    location ^~ /attachments/ {
        alias /srv/notes-api/storage/attachments/;
    }

    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;
    }
}

What a reverse proxy gives you:

The headers lost along the way

From Express's point of view, what connects to the app isn't the browser on Budi's laptop (a visitor, IP 198.51.100.23) but nginx, from 127.0.0.1. Without proxy_set_header, nginx only sends Host: 127.0.0.1:3000 (the address in proxy_pass). The table shows what Express sees. req.ip is the sender's IP, req.hostname the domain name, and req.protocol is http or https:

Config req.ip req.hostname req.protocol
proxy_pass only 127.0.0.1 127.0.0.1 http
+ the four proxy_set_header 127.0.0.1 notes.example.com http
+ headers + trust proxy 198.51.100.23 notes.example.com from X-Forwarded-Proto

The first row: req.ip holds 127.0.0.1, the IP that filled the log at the start of this lesson. Every visitor seems to come from the same IP, so per-IP rate limits and logs become useless.

Headers alone aren't enough. Express doesn't trust X-Forwarded-For unless you tell it to, because anyone can send that header. Tell Express which proxy to trust:

const app = express();
app.set("trust proxy", "loopback"); // trust the proxy on 127.0.0.1, which is nginx
app.get("/health", (req, res) => {
  res.json({ status: "ok", port: 3000 });
});
app.listen(3000, "127.0.0.1");

"loopback" means the localhost addresses such as 127.0.0.1, where nginx connects from. Express then reads X-Forwarded-For from the right (the end nginx adds to), skips the trusted addresses, and stops at the first one it doesn't trust: 198.51.100.23. That is what req.ip holds. req.protocol comes from X-Forwarded-Proto.

When the app is down: 502

Stop the app with sudo systemctl stop notes-api, then run curl from Budi's laptop. -i shows the answer's headers along with its body:

$ curl -i http://notes.example.com/health
HTTP/1.1 502 Bad Gateway
Server: nginx/1.24.0 (Ubuntu)
Date: Fri, 09 Oct 2026 03:20:11 GMT
Content-Type: text/html
Content-Length: 166
Connection: keep-alive

<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.24.0 (Ubuntu)</center>
</body>
</html>

502 Bad Gateway means nginx is alive, but the app behind it isn't answering. The cause is written in /var/log/nginx/error.log:

2026/10/09 10:20:11 [error] 2841#2841: *57 connect() failed (111: Connection refused) while connecting to upstream, client: 198.51.100.23, server: notes.example.com, request: "GET /health HTTP/1.1", upstream: "http://127.0.0.1:3000/health", host: "notes.example.com"

Connection refused means nothing is listening on port 3000. upstream is nginx's word for the app behind it. If the app is alive but sends nothing at all for 60 seconds (the default proxy_read_timeout), nginx answers 504 Gateway Timeout.

Load balancing: upstream and round robin

In one Node process, your JavaScript code only uses one CPU core. To use the other cores too, notes-api runs twice, on ports 3000 and 3001. Each running copy is called an instance. nginx shares the requests between them through an upstream block, a named list of servers (here notes_api). proxy_pass then uses that name:

upstream notes_api {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
}

# inside location /
proxy_pass http://notes_api;

The default method is round robin: in turns. Request 0 (the first one) goes to the first server, request 1 to the second, then back to the start. The formula is servers[i % servers.length], where servers is the list of servers and i the request's number. In the exercise, you finish the function below, which calculates that split:

function roundRobin(servers, requestCount) {
  const result = [];
  for (let i = 0; i < requestCount; i++) {
    result.push(servers[i % servers.length]);
  }
  return result;
}

console.log(roundRobin(["A", "B", "C"], 5)); // [ 'A', 'B', 'C', 'A', 'B' ]

⚠️ Misconfigurations between nginx and the app

TL;DR: A reverse proxy (here nginx) is a server in front of an app: nginx takes requests from the internet and passes them to the app with proxy_pass http://127.0.0.1:3000;. What you gain: SSL termination (nginx holds HTTPS), load balancing (sharing requests across several apps), caching and a security layer. Pass the original request's facts along with proxy_set_header Host $host, X-Real-IP, X-Forwarded-For $proxy_add_x_forwarded_for and X-Forwarded-Proto $scheme. Then set app.set("trust proxy", "loopback") in Express, so req.ip holds the sender's real IP, not 127.0.0.1 (nginx's address). An app that's down gives 502 Bad Gateway, with connect() failed (111: Connection refused) in nginx's error log. An upstream (a list of running copies of the app) shares requests in turns (round robin, servers[i % servers.length]) and skips copies that are down.

⚡ Nginx in front of the app

Write:

location / {
    proxy_pass http://127.0.0.1:3000;
}

Meaning: A reverse proxy (here nginx) takes requests from the internet, passes them on to the app behind it, then returns the answer. proxy_pass passes it on to the app at 127.0.0.1:3000 (localhost, the machine itself). The app waits for requests (listens) only on 127.0.0.1, so from the internet the only way in is through nginx.

⚡ The facts lost along the way

Write:

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;
Guess first: without these lines, whose IP does the app log for every request?

127.0.0.1, nginx's own. Every visitor seems to come from the same IP, so a per-IP rate limit (a limit on how many requests each IP may send) blocks everyone at once.

Meaning: These four headers pass facts from the original request on to the app. Host carries the domain name. X-Real-IP and X-Forwarded-For carry the sender's IP. X-Forwarded-Proto carries http or https.

⚡ Trust the proxy

Write:

app.set("trust proxy", "loopback");

Meaning: Express doesn't trust X-Forwarded-For unless you tell it to, because anyone can send that header. "loopback" tells Express to trust the proxy on localhost (127.0.0.1), which is nginx. Then req.ip holds the visitor's real IP, for example 198.51.100.23.

⚡ Split the requests with upstream

Write:

upstream notes_api {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
}

Meaning: An upstream is a named list, here holding two instances (running copies of the app) of notes-api. The default method is round robin: in turns, 3000, 3001, 3000, and so on. The formula: request i (counted from 0) goes to servers[i % servers.length]: servers is the list of servers, % the remainder. If every app is down, nginx answers 502 Bad Gateway.

What you will learn