How to Set Up Load Balancing With Nginx Upstream in 2026

When one server starts to struggle under traffic, adding a second server only helps if requests actually reach it. That is the job of nginx upstream load balancing: Nginx sits in front of two or more backend servers and hands each request to one of them, so no single machine takes the full load. This guide sets up a working two-server setup on a VPS, covers weighting and failover, and shows how to test that traffic really spreads across backends.

Before you start, size the front-end machine for the job. A proxy that runs out of CPU or memory becomes the new bottleneck, so read the guide on how much VPS you need before you pick specs for the load balancer itself.

What an upstream block does

An upstream block is a named group of backend servers. You define it once, then point a proxy_pass directive at the group name instead of a single IP address. Nginx then picks a backend for each request. The backends can run the same app on different machines, or different containers on one machine behind different ports. The setup works the same way either way.

A basic nginx upstream block looks like this:

upstream app_backend {
    server 10.0.0.11:8080;
    server 10.0.0.12:8080;
}

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

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

Put the upstream block in the http context, usually in /etc/nginx/conf.d/upstream.conf or directly in nginx.conf outside any server block. Putting it inside a server block is a common mistake, and Nginx will refuse to start with a clear error if you do it.

How nginx upstream load balancing picks a server

By default, Nginx uses round robin. The first request goes to backend one, the second to backend two, the third back to backend one, and so on. This is the right default when your backends have similar specs and your requests cost roughly the same to serve.

Nginx offers three other built-in methods. least_conn sends each new request to the backend with the fewest active connections, which fits workloads where some requests run long and others finish fast. ip_hash sends the same client IP to the same backend every time, which helps apps that keep session data in local memory. A third option, a hash of a key you choose, works when you want requests for the same URL or header value to land on the same backend.

Here is a nginx load balancer configuration that uses least_conn:

upstream app_backend {
    least_conn;
    server 10.0.0.11:8080;
    server 10.0.0.12:8080;
}

Start with nginx round robin, and switch only after you see uneven load or session handling forces it.

Prerequisites and backend checks

Check three things before you write the config. First, each backend must answer on its own, without the proxy. Run curl http://10.0.0.11:8080/health from the proxy machine, or at least curl http://10.0.0.11:8080/ if the app has no health endpoint. Second, the backends must serve the same app version. A load balancer that mixes an old release and a new release sends users into inconsistent behaviour that looks like a bug in the app. Third, confirm the proxy can reach the backends on the backend port through the firewall. On Ubuntu, check with ss -tlnp on the backend and ufw status on both machines.

Use private IPs between the proxy and the backends when they share a private network.

Weighting backends with different specs

Round robin in its plain form treats every backend as equal. When one machine has twice the CPU of the other, equal shares waste the stronger machine. Weights fix this. A weight of 2 sends twice as many requests to that server as a server with weight 1.

upstream app_backend {
    server 10.0.0.11:8080 weight=3;
    server 10.0.0.12:8080 weight=1;
}

In this example, backend one takes three out of every four requests. Start with upstream server weights that match CPU cores, then adjust from real CPU graphs.

Two extra parameters help during maintenance. backup marks a server that only receives traffic when every other server is down, which gives you a standby machine without a second proxy. down takes a server out of rotation at once, so you can drain it for updates:

upstream app_backend {
    server 10.0.0.11:8080;
    server 10.0.0.12:8080;
    server 10.0.0.13:8080 backup;
}

Health checks and failover behaviour

The open-source build of Nginx does not run active health checks that probe backends on a timer. It uses passive checks instead: when a backend fails to answer or returns an error, Nginx marks it unavailable for a time and stops sending it traffic. Two parameters control this behaviour:

  • max_fails=3: after three failed attempts, Nginx treats the server as unavailable.
  • fail_timeout=30s: the server stays out of rotation for 30 seconds, then Nginx tries it again.
upstream app_backend {
    server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
    server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
}

Set max_fails low enough that a dead backend leaves rotation fast, but not so low that one slow response knocks out a healthy server. Three fails over 30 seconds is a sane starting point for most small apps. Tune proxy_connect_timeout and proxy_read_timeout in the location block too: a connect timeout of 5 seconds stops one dead backend from holding up requests while Nginx moves on.

Failover still needs monitoring. A backend can sit in failed state for hours while the other server quietly absorbs double traffic, and you only notice when the second server also fails. Set up an external check that alerts you per backend, not only on the public URL. The comparison of Uptime Kuma vs Checkly vs Better Uptime covers self-hosted and hosted options for exactly this kind of per-backend check.

Session persistence without shared storage

Load balancing breaks apps that store login sessions in local files or memory on one backend. A user logs in on backend one, the next request lands on backend two, and the app treats them as logged out. Three fixes exist, in order of preference.

First, store sessions in a shared place both backends can read, such as Redis or a shared database. This is the cleanest fix because any backend can serve any request. Second, use ip_hash so the same client IP keeps hitting the same backend. This works until a user changes networks, or many users share one office IP and pile onto one backend. Third, use sticky cookies with Nginx Plus, which the open-source build does not include. For a self-hosted setup, the shared session store is the fix worth building.

Test that traffic actually spreads

Do not trust the config file alone. Test it. First, check the syntax and reload:

sudo nginx -t
sudo systemctl reload nginx

Next, give each backend a page that names itself. A tiny endpoint that returns the server hostname is enough. On each backend, confirm curl http://localhost:8080/hostname prints a different name. Then hit the proxy ten times and watch the names alternate:

for i in $(seq 1 10); do curl -s http://app.example.com/hostname; echo; done

If all ten replies name the same backend, check that you reloaded Nginx, that proxy_pass points at the upstream name and not a single IP, and that the backend you expect is not marked down by max_fails. Check the error log at /var/log/nginx/error.log for upstream connection errors, which usually point at a firewall rule or a wrong port.

Also test failure. Stop the app on backend one, run the loop again, and confirm every reply comes from backend two with no errors shown to the client. Then start backend one again, wait past fail_timeout, and confirm it rejoins rotation. This five-minute test catches most production surprises before users do.

Protect the proxy itself

A load balancer concentrates risk: every request passes through it, so abuse aimed at the proxy hits every backend behind it. Add rate limiting in Nginx on login and API paths before you expose the setup, and read the DDoS protection basics guide for the limits a small VPS can realistically absorb. Rate limits belong on the proxy, not on each backend, because the proxy sees the full request stream and can count per client IP in one place.

Keep the proxy config in version control, keep backend IPs out of public repos, and reload rather than restart Nginx when you change weights or add a backend. A reload keeps existing connections alive, while a restart drops them. With those habits, adding a third backend later is a one-line edit plus a reload, not a maintenance window.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.