Chapter 8 · Lesson 8 of 8
Web servers and proxies

Load balancing across two backends with nginx upstream

Load balancing in nginx means listing several servers in an upstream block and pointing proxy_pass at it, so requests are shared and a failed server is skipped.

By the end you will

Balance traffic across two backends with nginx, choose a method, set failure handling and decide how to treat sessions.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • Two copies of your app, on two hosts or two local ports
  • nginx already proxying to one app

A load balancer spreads traffic over backends

A load balancer shares requests between backends, and an upstream block lets nginx stop sending traffic to a backend that fails.
  1. Every request from a visitor arrives at the load balancer first.
  2. With round robin, the nginx upstream sends the first request to backend A.
  3. The next request goes to backend B, and the two take turns.
  4. When backend A stops answering, nginx marks it down after max_fails failed attempts.
  5. New requests go only to backend B until A answers again.
Static diagram
  1. VisitorrequestLoad balancer
  2. Load balancerround robinBackend A
  3. Load balancernext requestBackend B
  4. Load balancerA failsBackend A
  5. Load balancerhealthy onlyBackend B

One app process is a single point of failure. Two copies behind nginx give you capacity and let you restart one while the other serves. This lesson uses two backends, either 203.0.113.10 and 203.0.113.11 or two local ports, and covers the choices that matter: method, failure handling, keepalive and state.

How it works#

An upstream block names a group of servers. When you write proxy_pass http://app; and app is an upstream, nginx picks one server per request using the group’s method. If a connection to the chosen server fails or times out, nginx can retry the request on the next server, and after enough failures it stops sending traffic there for a while.

This is a reverse proxy with a choice step added. The load balancer also becomes the single point of failure, so keep its config simple and the machine healthy. The two apps must be interchangeable, which means no local files or in-memory sessions that only one copy has.

Step 1: Define the upstream#

In the http block, or at the top of your site file (outside server):

nginx
upstream app {
    server 203.0.113.10:3000;
    server 203.0.113.11:3000;
}

For two copies on one host use server 127.0.0.1:3000; and server 127.0.0.1:3001;. Keep each app bound to its address, so only nginx reaches them. The upstream name is a label, not a host name.

Step 2: Point the proxy at it#

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://app;
        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;
    }
}

Headers work as in nginx reverse proxy for a Node app. Run sudo nginx -t && sudo systemctl reload nginx. With no method set, nginx uses round robin, so requests alternate between the two.

Step 3: Choose a method#

nginx
upstream app {
    least_conn;
    server 203.0.113.10:3000 weight=3;
    server 203.0.113.11:3000;
}
  • Round robin (default): each server in turn. Good when requests cost about the same.
  • least_conn: the server with the fewest active connections. Better when some requests take much longer than others.
  • ip_hash: the client address picks the server, so one client keeps hitting the same one. Use only as a crude stickiness tool.
  • weight=N: a bigger share for a stronger machine. A weight of 3 against 1 sends three of every four requests to the first.

Pick one method line per upstream.

Step 4: Failure handling and backup#

nginx
upstream app {
    server 203.0.113.10:3000 max_fails=3 fail_timeout=30s;
    server 203.0.113.11:3000 max_fails=3 fail_timeout=30s;
    server 203.0.113.12:3000 backup;
    keepalive 16;
}

max_fails and fail_timeout are passive health checks. nginx watches real requests: after max_fails failed attempts within fail_timeout, the server is skipped for the same fail_timeout, then tried again. Open source nginx has no active checks that probe a health URL on a timer. Those are a feature of the commercial NGINX Plus, so on the open source build a server can fail a few real requests before it is removed. Your app’s own health check still matters for the orchestrator or monitor.

backup takes traffic only when all the others are down. keepalive 16 keeps up to 16 idle connections to the upstream open, which avoids a new TCP handshake per request. It needs two more lines in the location:

nginx
proxy_http_version 1.1;
proxy_set_header Connection "";

Control retries with proxy_next_upstream error timeout http_502 http_503; so an error page from one backend moves on to the other. Do not retry non-idempotent requests blindly: by default nginx does not retry a POST that was already sent.

Step 5: Think about state#

Two backends only work if either can handle any request. Sessions held in one app’s memory log users out when the other server answers. Move sessions to a shared store, keep uploads on shared storage or object storage, and run database migrations once, not per copy. ip_hash hides the problem until a mobile client changes address, or an office shares one address and sends every user to one backend. For websockets, balancing needs the same care, see websockets through a proxy. A deploy can take one backend out at a time, as described in zero-downtime deploys.

Step 6: The Caddy version#

output
example.com {
    reverse_proxy 203.0.113.10:3000 203.0.113.11:3000 {
        lb_policy least_conn
        health_uri /health
        health_interval 10s
    }
}

Caddy lists several backends on one reverse_proxy. lb_policy picks the method (the default is random, and round_robin, least_conn and ip_hash are among the options). health_uri turns on active checks that request that path on a timer. See Caddy from scratch for the basics.

Check it worked#

Make each backend identify itself, for example with a /whoami route, then run:

bash
for i in $(seq 1 6); do curl -s http://example.com/whoami; echo; done
sudo tail -n 20 /var/log/nginx/error.log

Round robin should alternate between the two answers. Stop one app (sudo systemctl stop myapp on one host) and repeat: every request should still succeed through the other, with a few lines in the error log about the failed upstream. Start it again and it returns after fail_timeout.

Edge cases and gotchas#

  • All servers down means 502 or 503. With every backend marked failed nginx has nothing to try, and a backup or a static error page is your only answer.
  • A server marked down comes back by itself. After fail_timeout nginx sends it a real request, so a still-broken server fails once more for some user.
  • ip_hash cannot use backup. It also treats a whole NAT or carrier as one client, and for IPv4 it hashes only the first three octets.
  • Behind another proxy, ip_hash hashes the proxy. Use the real client address module first.
  • Uneven load is normal with round robin. Long requests pile up on a busy server. Switch to least_conn.
  • Draining a server. Add the down parameter to a server line and reload. New requests skip it while existing ones finish.
  • Config split across hosts drifts. Two apps with different environment values will behave differently, see environment variables and secrets.

Troubleshooting#

SymptomLikely causeFix
nginx: [emerg] host not found in upstream "app"proxy_pass names an upstream that is not definedDefine upstream app { ... } in the http context
host not found in upstream "backend1.internal"Name does not resolve at startupFix DNS or use the IP address
no live upstreams while connecting to upstreamAll servers marked downStart the backends, check max_fails settings
connect() failed (111: Connection refused) while connecting to upstream, upstream: "http://203.0.113.11:3000/"One backend is stoppedStart it, nginx uses the other meanwhile
Users logged out at randomIn-memory sessions on two backendsUse a shared session store
One backend gets nearly all trafficip_hash, or weights set unevenlyUse round robin or least_conn, check weight
upstream timed out (110: Connection timed out) while connecting to upstreamBackend unreachable over the networkCheck the firewall and route between hosts
nginx: [emerg] "least_conn" directive is duplicateTwo method linesKeep one

Quick reference#

nginx
upstream app {
    least_conn;
    server 203.0.113.10:3000 max_fails=3 fail_timeout=30s;
    server 203.0.113.11:3000 max_fails=3 fail_timeout=30s weight=2;
    server 203.0.113.12:3000 backup;
    keepalive 16;
}

location / {
    proxy_pass http://app;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
}

Next#

Apps with state need a database, so continue with install Postgres and connect with psql.

Check what you learned4 questions
1What does nginx use when an upstream block has no method directive?
2What do max_fails=3 and fail_timeout=30s mean together?
3Which approach scales best for user sessions across two backends?
4What does the backup parameter on a server line do?

Frequently asked questions

How do I load balance two servers with nginx?

Define an upstream block with a server line for each backend, then use proxy_pass http://name; in a location. Without any other setting nginx uses round robin.

What is the difference between round robin, least_conn and ip_hash?

Round robin rotates through servers in turn. least_conn picks the server with the fewest active connections. ip_hash sends the same client address to the same server.

Does open source nginx have active health checks?

No. Open source nginx only has passive checks through max_fails and fail_timeout, which react to real failed requests. Active health checks are part of the commercial NGINX Plus.

How do I keep a user on the same backend?

Use ip_hash for a rough approach, or better, keep sessions in a shared store such as a database or Redis so any backend can serve any request.

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