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.
- Updated Nov 27, 2026
- Markdown
Balance traffic across two backends with nginx, choose a method, set failure handling and decide how to treat sessions.
- 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
- Every request from a visitor arrives at the load balancer first.
- With round robin, the nginx upstream sends the first request to backend A.
- The next request goes to backend B, and the two take turns.
- When backend A stops answering, nginx marks it down after max_fails failed attempts.
- New requests go only to backend B until A answers again.
Static diagram
- VisitorrequestLoad balancer
- Load balancerround robinBackend A
- Load balancernext requestBackend B
- Load balancerA failsBackend A
- 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):
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#
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#
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#
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:
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#
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:
for i in $(seq 1 6); do curl -s http://example.com/whoami; echo; done
sudo tail -n 20 /var/log/nginx/error.logRound 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
backupor a static error page is your only answer. - A server marked down comes back by itself. After
fail_timeoutnginx sends it a real request, so a still-broken server fails once more for some user. ip_hashcannot usebackup. 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_hashhashes 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
downparameter 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#
| Symptom | Likely cause | Fix |
|---|---|---|
nginx: [emerg] host not found in upstream "app" | proxy_pass names an upstream that is not defined | Define upstream app { ... } in the http context |
host not found in upstream "backend1.internal" | Name does not resolve at startup | Fix DNS or use the IP address |
no live upstreams while connecting to upstream | All servers marked down | Start 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 stopped | Start it, nginx uses the other meanwhile |
| Users logged out at random | In-memory sessions on two backends | Use a shared session store |
| One backend gets nearly all traffic | ip_hash, or weights set unevenly | Use round robin or least_conn, check weight |
upstream timed out (110: Connection timed out) while connecting to upstream | Backend unreachable over the network | Check the firewall and route between hosts |
nginx: [emerg] "least_conn" directive is duplicate | Two method lines | Keep one |
Quick reference#
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 "";
}Related lessons#
- What is a reverse proxy: the concept this builds on.
- Zero-downtime deploys: rotate backends while serving traffic.
- Blue-green vs rolling deploys: two ways to use two copies.
- Zero-downtime deploys with Docker and rollback: a worked example.
Next#
Apps with state need a database, so continue with install Postgres and connect with psql.
Check what you learned
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
Keep going: guides and tutorials
- Self-Hosted Static Site Hosting: Deploy a Folder With Levelrail Self-hosted static site hosting from a plain folder: one deploy command, _redirects, _headers and a custom 404 honored, plus a one command rollback.
- Deploy Next.js on a VPS With Docker, Git Push and HTTPS Deploy a Next.js app to your own VPS with Docker, a health check, HTTPS and rollback. Includes the NEXT_PUBLIC build trap that leaves variables empty.