Load balancing with Nginx: a complete guide, from two servers to a site that stays up

What load balancing is, when it helps and how to set it up step by step with Nginx on Ubuntu 24.04: two backend web servers, SSL, round robin, least_conn and ip_hash, failed server detection, real visitor IPs, sessions and testing.

Wiptor Team
6 November 202612 min read

What load balancing is

Load balancing means splitting the visitors of a site or an application across several servers instead of sending all of them to one.

In front sits a dedicated server called the load balancer. Visitors connect to it, and it forwards each request to one of the servers behind it (the backends), then returns the response. Nothing changes for the visitor: same domain, same address.

text
                    ┌──────────────┐
visitors ─────────► │ load balancer│
                    │   (Nginx)    │
                    └──────┬───────┘
                 ┌─────────┴─────────┐
                 ▼                   ▼
          ┌────────────┐      ┌────────────┐
          │  web1      │      │  web2      │
          │ (backend)  │      │ (backend)  │
          └────────────┘      └────────────┘

Why it helps

1. Your site stays up when a server goes down. If web1 stops (an update, a crash, a full disk), the load balancer notices and sends all traffic to web2. Visitors never see an error page.

2. You handle more traffic. Two servers serve almost twice as much as one. When traffic grows, you add a third backend without touching DNS or anything visitors see.

3. Updates without downtime. Take one server out of rotation, update it, put it back, then move to the next. The site stays online the whole time.

4. One place for SSL and protection. The certificate, rate limits and security rules live on the load balancer, not on every server.

When you do NOT need load balancing

Honestly: for most small sites, one good VPS is enough. Load balancing adds servers, which means cost and more to manage. It is worth it when:

  • the site makes money and every minute of downtime matters (online shop, SaaS, a platform with customers);
  • one server is constantly at its limit and a bigger server costs more than two smaller ones;
  • you want to update without taking the site offline.

It is not worth it if the real problem is an unoptimized site. A WordPress install with 40 plugins and no cache will be slow on two servers too. Fix the cause first, then split the traffic.

Game servers are a different story. A CS 1.6, CS2 or Minecraft server keeps the match and the connected players in memory. You cannot split the players of one match across two servers. For games, "balancing" is done differently: several separate servers, each with its own players, or a dedicated proxy (for example Velocity for Minecraft networks).

What we are building

A classic setup on Ubuntu 24.04 with three servers:

RoleExample IPRuns
load balancer203.0.113.10 (public), 10.0.0.10 (private)Nginx, the SSL certificate
web110.0.0.11Nginx + PHP (or your app)
web210.0.0.12Nginx + PHP (or your app)

The addresses are examples; use your own. Ideally the backends talk to the load balancer over a private network and only the load balancer is visible from the internet. Without a private network it also works over public IPs, with a firewall (step 7).

Your domain (for example example.com) must point in DNS only to the load balancer.

Step 1: prepare the backends

On web1 and web2, install your application exactly the same way. For a simple test site:

bash
apt update && apt install -y nginx

To see which server answered during testing, give each one a different page. On web1:

bash
echo "Response from web1" > /var/www/html/index.html

On web2:

bash
echo "Response from web2" > /var/www/html/index.html

Then, on each backend, add a health page the load balancer can call. In /etc/nginx/sites-available/default, inside the server block:

nginx
location = /health {
    access_log off;
    return 200 "ok\n";
}
bash
nginx -t && systemctl reload nginx

From the load balancer, check you can reach both:

bash
curl http://10.0.0.11/
curl http://10.0.0.12/

On a real site both servers run the same code, the same version and the same settings. Anything that differs between them will cause problems that are hard to track down.

Step 2: install Nginx on the load balancer

bash
apt update && apt install -y nginx

Ubuntu 24.04 ships Nginx 1.24, which has everything we need (the upstream module is built in).

Step 3: define the server group

Create /etc/nginx/conf.d/upstream-site.conf:

nginx
upstream site_backend {
    server 10.0.0.11:80 max_fails=3 fail_timeout=15s;
    server 10.0.0.12:80 max_fails=3 fail_timeout=15s;

    keepalive 32;
}

What it means:

  • upstream site_backend is the group name; we use it below;
  • each server line is a backend;
  • max_fails=3 fail_timeout=15s: if a server fails 3 times within 15 seconds, Nginx marks it as down and sends it nothing for 15 seconds, then tries again. The defaults are max_fails=1 and fail_timeout=10s; we use 3 so a single slow response does not take a server out of rotation;
  • keepalive 32 keeps connections to the backends open so a new one is not created for every request. Faster, and lighter on the servers.

Step 4: configure the site on the load balancer

Create /etc/nginx/sites-available/example.com:

nginx
server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        proxy_pass http://site_backend;

        proxy_http_version 1.1;
        proxy_set_header Connection "";

        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;

        proxy_next_upstream error timeout http_502 http_503 http_504;
        proxy_connect_timeout 5s;
        proxy_read_timeout 60s;
    }
}

The important lines:

  • proxy_pass http://site_backend sends the request to the group defined above;
  • proxy_http_version 1.1 and Connection "" are required for keepalive from step 3 to work. Very recent Nginx versions (1.29.7+) set them by default, but on Ubuntu 24.04 you must write them;
  • the proxy_set_header lines tell the backend the requested domain, the visitor's real IP and whether the visitor came over HTTPS;
  • proxy_next_upstream: if a backend does not answer or returns 502/503/504, the request is retried on the other one automatically. The visitor never sees the error;
  • proxy_connect_timeout 5s: if a backend does not accept the connection within 5 seconds, Nginx moves on to the next one.

Enable and reload:

bash
ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx

Step 5: SSL on the load balancer

The certificate goes only on the load balancer. Traffic to the backends stays HTTP on the private network.

bash
apt install -y certbot python3-certbot-nginx
certbot --nginx -d example.com -d www.example.com

Certbot adds the listen 443 ssl block, the certificate and the HTTP to HTTPS redirect by itself, and renewal is automatic. Check renewal with:

bash
certbot renew --dry-run

If the backends are reached over the internet rather than a private network, encrypt that leg too (HTTPS on the backends, with proxy_pass https://...), otherwise data travels unencrypted between servers.

Step 6: test

From your computer:

bash
for i in 1 2 3 4 5 6; do curl -s https://example.com/; done

You should see the responses alternate:

text
Response from web1
Response from web2
Response from web1
Response from web2
...

Now the test that matters: stop a server. On web1:

bash
systemctl stop nginx

Run the loop again. Every response must come from web2, with no errors. Start web1 again (systemctl start nginx) and within 15 seconds at most it receives traffic again.

Step 7: firewall on the backends

The backends should not be reachable directly from the internet, or someone can bypass the load balancer (and the protection on it). On web1 and web2, with UFW:

bash
ufw allow OpenSSH
ufw allow from 10.0.0.10 to any port 80 proto tcp
ufw enable

Use the load balancer's address as the backends see it: the private one if you have a private network, the public one otherwise. Then check from your computer that curl http://web1-IP/ no longer answers.

Step 8: real visitor IPs on the backends

On the backends, every request seems to come from the load balancer. Logs, statistics and any IP blocking only see its address. To let the backend see the real IP, add this on web1 and web2, in /etc/nginx/conf.d/real-ip.conf:

nginx
set_real_ip_from 10.0.0.10;
real_ip_header X-Forwarded-For;

set_real_ip_from is the load balancer's address as the backend sees it. The header is accepted only from that address; if you accepted it from anyone, a visitor could set a fake IP.

bash
nginx -t && systemctl reload nginx

In PHP applications the real IP then shows up normally in $_SERVER['REMOTE_ADDR'].

Load balancing methods

By default Nginx uses round robin: requests go to each server in turn. There are a few alternatives, set on the first line of the upstream block.

MethodHow it picks a serverWhen to use it
round robin (default)in turnequal servers, similar requests
least_connthe server with the fewest active connectionsrequests with very different durations (reports, uploads, APIs)
ip_hashthe same visitor always goes to the same serverapps that keep sessions on local disk
hash $request_uri consistentthe same page URL always goes to the same servercache servers

Example with least_conn:

nginx
upstream site_backend {
    least_conn;
    server 10.0.0.11:80 max_fails=3 fail_timeout=15s;
    server 10.0.0.12:80 max_fails=3 fail_timeout=15s;
    keepalive 32;
}

Useful details from the Nginx documentation:

  • weight: if one server is twice as powerful, give it weight=2 and it gets twice the requests. Every server has weight=1 by default;
  • backup: a server marked backup only receives traffic when all others are down. It cannot be used with ip_hash, hash or random;
  • down: takes a server out of rotation, for example during an update. With ip_hash this is the recommended way, because it keeps the visitor distribution on the other servers;
  • ip_hash uses the first three parts of the IPv4 address (for example 86.120.45). All visitors from the same /24 network land on the same server, so the split can be uneven if many come from one network.

Full example:

nginx
upstream site_backend {
    server 10.0.0.11:80 weight=2 max_fails=3 fail_timeout=15s;
    server 10.0.0.12:80 max_fails=3 fail_timeout=15s;
    server 10.0.0.13:80 backup;
    keepalive 32;
}

Detecting failed servers: what free Nginx does and does not do

Free Nginx has passive checks: it only learns a server is down when a real request fails (hence max_fails and fail_timeout). Thanks to proxy_next_upstream, that request is retried on another server, so the visitor still sees no error.

Active checks (the load balancer calls /health every few seconds by itself, even with no traffic) are part of the commercial NGINX Plus subscription. If you want them for free, you have two options:

  • HAProxy, free and open source, which includes active checks (option httpchk GET /health and check on each server);
  • a small script, run every few seconds, that calls /health on each backend and alerts you when one does not answer.

For most sites, passive checks plus proxy_next_upstream are enough.

Where most people go wrong: shared data

Load balancing works perfectly for static pages. Problems start when the application keeps data on the server it runs on. Three things must be solved before going to production.

1. Sessions (user logins). PHP saves sessions on disk by default, on the server that answered. If the next request lands on the other server, the user looks logged out. Solutions:

  • sessions in a shared place, for example Redis or the database. The right way;
  • ip_hash, so each visitor sticks to the same server. The quick way, but if that server goes down the visitor loses the session.

2. The database. Do not run a separate database on each backend; they will drift apart immediately. Use one separate database server that both backends connect to.

3. User uploads. A picture uploaded to web1 does not exist on web2. Solutions: shared storage (NFS), S3-compatible object storage, or automatic sync between servers.

A concrete case, WordPress: identical code on both servers, the database on a separate server, wp-content/uploads shared or on S3 storage, and in wp-config.php a line telling WordPress the visitor came over HTTPS through the load balancer:

php
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
    $_SERVER['HTTPS'] = 'on';
}

Without it, WordPress can end up in a redirect loop between HTTP and HTTPS.

What if the load balancer goes down?

We moved the problem: now the load balancer is the one point that stops everything if it fails. For most projects that is an acceptable risk, because a load balancer does very little work and rarely fails. If you need more:

  • two load balancers and a floating IP, moved automatically from one to the other with keepalived (the VRRP protocol). Your provider must allow moving the IP between servers;
  • DNS with several addresses and health checks at your DNS provider. Simpler, but failover takes as long as the DNS cache time (TTL).

FAQ

Does load balancing protect me from DDoS attacks?

Only partly. It spreads the load, but a large attack hits the load balancer first. DDoS protection happens at the network level, before traffic reaches your servers.

Can I load balance on a single VPS?

Technically yes (several app processes on different ports), and it sometimes makes sense for Node.js or Python. But it does not protect you when the server goes down, which is the main reason to do it.

How many servers do I need?

At least two backends. With one, you only have a proxy, not balancing.

Nginx or HAProxy?

Nginx if you already use it and want SSL, caching and sites in one place. HAProxy if you want free active checks, detailed statistics and balancing for non-HTTP TCP traffic too.

Summary

  1. identical backends with a /health page;
  2. Nginx on the load balancer with upstream and max_fails/fail_timeout;
  3. proxy_pass, keepalive and proxy_next_upstream;
  4. SSL only on the load balancer, with Certbot;
  5. the test with one server stopped;
  6. a firewall on the backends and real IPs with set_real_ip_from;
  7. shared sessions, database and files before production.

At Wiptor

For a setup like this you need a few VPS servers with root access: a small one for the load balancer and two stronger ones for the backends. Wiptor VPS plans come with NVMe storage, DDoS protection included and root access from the first minute.

If you just want your site to run without managing servers, Wiptor web hosting with Wiptor Cloud Panel is the simpler option.

See Wiptor VPS plans · See web hosting

Was this helpful?
Wiptor Team

We write these guides from what we do every day on our customers' servers: game servers, VPS and web hosting. If you get stuck on a step, message us on live chat.