Reverse proxies and load balancers with nginx

Intermediate · 20 min

Put nginx in front of your app: one public entry point that terminates TLS, spreads requests over a pool of backends, and routes around one that dies.

Before thisRunning services with systemdDNS records and TTLs in practice

NeuralNine · 44 min · from 16:54

Reverse proxies and load balancers with nginx

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by NeuralNineReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A reverse proxy is the public entry point that clients connect to. It forwards each request to an app server the client never sees.
  • Putting one proxy in front lets you terminate TLS, serve static files, and add or restart app servers without touching DNS.
  • In nginx, an upstream block names a pool of backends, and proxy_pass sends requests to it. Round robin is the default, and least_conn is one alternative.
  • Open-source nginx health-checks passively. A backend that refuses or times out is skipped for fail_timeout after max_fails failures.
  • The proxy must pass Host, X-Forwarded-For and X-Forwarded-Proto, or the app sees every request as coming from the proxy over plain HTTP.

One app, many jobs

Your notes API listens on port 8080 as a systemd service. Now the requirements pile up. It needs HTTPS. It needs to serve some static files fast. You want three copies of it for capacity, and you want to restart one without dropping users. You could teach the app to do all of that. Or you could put one program in front of it whose whole job is handling connections.

That program is a reverse proxy. Clients connect to it, and it forwards each request to an application server they never see. When it spreads requests over several application servers, we call it a load balancer as well. Web servers, application servers and reverse proxies covers why an app developer wants one. This lesson is about running it.

Think of a restaurant’s front of house. Diners never walk into the kitchen. The host takes them in, seats them across the tables evenly, and if a section closes, stops seating people there. The kitchen can change cooks without the diners noticing.

How nginx is laid out

nginx is the most common choice. I pulled the official nginx image from Docker Hub and read its stock /etc/nginx/nginx.conf (comments trimmed):

user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log notice;
pid        /run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    access_log  /var/log/nginx/access.log  main;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}

One master process runs as root just to bind port 80 and 443, then worker_processes auto starts one worker per CPU core, as the unprivileged nginx user. The http block pulls in everything in conf.d/, which is where your site goes. In this image, access.log and error.log are symlinks to /dev/stdout and /dev/stderr, so a container platform collects them. On a normal server they are real files.

A load-balancing config

This is the config for three API copies, written from the nginx docs for ngx_http_upstream_module and ngx_http_proxy_module. I did not run it, because there is no nginx on this machine.

# /etc/nginx/conf.d/notes.conf
upstream notes_api {
    least_conn;
    server 10.0.2.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.2.12:8080 max_fails=3 fail_timeout=10s;
    server 10.0.2.13:8080 max_fails=3 fail_timeout=10s;
}

server {
    listen 80;
    server_name notes.example.com;

    location /static/ {
        root /srv/notes;
    }

    location / {
        proxy_pass http://notes_api;
        proxy_set_header Host              $host;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
  • upstream names the pool. The default method is round robin. least_conn picks the server with the fewest active connections, which helps when requests vary in length. The trade-offs between methods belong to load-balancing algorithms.
  • max_fails and fail_timeout are passive health checks. Open-source nginx notices failures on real requests: after 3 within 10 seconds, it stops using that server for 10 seconds, then tries again. Active probing with a health URL is a commercial NGINX Plus feature, or a job for your cloud load balancer.
  • The three headers matter more than they look. Without them, the app sees the proxy’s address as every client’s address, and sees plain HTTP even when the user came in over HTTPS, so it builds http:// redirect URLs.

Apply changes with nginx -t && sudo systemctl reload nginx. The reload sends HUP, as the unit file in the systemd lesson showed, and nginx swaps in new workers while old ones finish their requests.

Watching a pool route around a failure

To see the mechanism run, I wrote a toy reverse proxy in about 25 lines of Python: three tiny backends on ports 9001 to 9003, and a proxy on 8080 that goes round robin, forwards Host and X-Forwarded-For, and moves on to the next backend when one refuses. It is not nginx, but it makes the same decisions nginx makes by default.

$ for i in 1 2 3 4; do curl -s -H 'Host: notes.example.com' http://127.0.0.1:8080/; done
backend :9001 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
backend :9002 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
backend :9003 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
backend :9001 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
$ kill $B2        # backend 9002 dies
$ for i in 1 2 3 4; do curl -s -H 'Host: notes.example.com' http://127.0.0.1:8080/; done
backend :9003 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
backend :9001 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
backend :9003 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
backend :9001 saw Host=notes.example.com X-Forwarded-For=127.0.0.1
$ cat lb.log
proxy: 127.0.0.1:9002 failed ([Errno 61] Connection refused), trying next
proxy: 127.0.0.1:9002 failed ([Errno 61] Connection refused), trying next

Every client request still succeeded. The proxy paid for the dead backend with a failed connection attempt each time round, which is exactly what max_fails and fail_timeout stop: after a few failures, nginx would skip it without trying. With all three backends killed, the proxy returned 502 Bad Gateway, the status you will see from nginx when nothing behind it answers.

nginx retries like this by default (proxy_next_upstream error timeout), with one exception from its docs: since 1.9.13 a non-idempotent request, such as a POST, is not sent to a second server once it has reached the first, because the first may already have created the record.

About the video

The embed is a clip, from 16:54 to 36:34, of NeuralNine’s “NGINX Crash Course: Web Server, Reverse Proxy & Load Balancer”, published March 2025. The full video is 43 minutes and 37 seconds. The clip covers its “Reverse Proxy”, “HTTPS & SSL Termination” and “Load Balancer” chapters. The earlier chapters on installing nginx and serving static files, and the later ones on caching and Docker Compose, are outside this lesson. It does not mention max_fails or forwarded headers by name in its chapter list, so treat those parts of this lesson as the addition. English was judged from the title, description, channel and its English auto-caption track. The two official NGINX videos in deeper go further on balancing methods and session persistence.

Where this fits

The proxy is where HTTPS usually ends. Next, where its certificates come from and how they renew themselves: TLS certificates and automated renewal. For L4 versus L7 balancing, see the system design lesson.

Check yourself

  1. 01Your app logs show every client IP as 127.0.0.1 after you put nginx in front. Why, and what fixes it?

    The app's TCP connection now comes from nginx. Set proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for and have the app trust that header from the proxy only.

  2. 02One of three backends crashes. What does nginx do with the next request that was routed to it?

    The connection fails, nginx counts the failure and, by default, retries the request on the next server in the pool. After max_fails failures it stops sending traffic there for fail_timeout.

  3. 03Why might nginx not retry a failed POST on another backend?

    Since nginx 1.9.13, a non-idempotent request such as POST is not passed to the next server once it has been sent upstream, because the first server may already have acted on it.

  4. 04How do you apply a config change without dropping live connections?

    Run nginx -t to check the syntax, then reload with systemctl reload nginx, which sends HUP. nginx starts new workers with the new config and lets old ones finish their requests.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark