Skip to main content

Web servers and networking · Intermediate · 18 min

Load balance web servers with HAProxy

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · HAProxy 3.4 LTS

You will put HAProxy 3.4 in front of three web backends on Ubuntu 26.04, with HTTP health checks, weights, a backup server, a password-protected stats page and a server drained through the runtime API.

On this page

A load balancer takes every request for your site and passes it to one of several identical backends. If one backend dies, it stops sending traffic there. If you need to patch one, you take it out of rotation without dropping anyone. HAProxy is built for this job: it checks backends actively, shows you live state on a stats page, and lets you change a running setup through a socket without a reload.

In this tutorial you run three small Python web servers on the same machine as HAProxy, so you can watch every decision it makes. In production the backends are separate servers, and you write their private addresses where this tutorial writes 127.0.0.1. Every command runs on the load balancer server unless a step says it runs on your laptop.

You will use HAProxy 3.4, the long-term support branch released in June 2026 and maintained until 2031. It comes from the PPA run by HAProxy's Debian maintainer. Ubuntu 26.04's own archive has HAProxy 3.2, also an LTS release; if you prefer packages from Ubuntu only, run sudo apt install haproxy instead of the PPA commands. Every directive in this tutorial works on 3.2 as well.

Step 1 · Install HAProxy 3.4 and start three backends

Add the PPA and install HAProxy from it. The haproxy=3.4.\* form keeps apt on the 3.4 branch. For what a PPA is and how to remove one, see /tutorials/add-a-third-party-apt-repository-safely.

Bash
sudo apt update
sudo apt install -y --no-install-recommends software-properties-common
sudo add-apt-repository -y ppa:vbernat/haproxy-3.4
sudo apt install -y haproxy=3.4.\* socat
haproxy -v

socat is used later to talk to HAProxy's runtime socket. Packages from the PPA get updates through sudo apt upgrade like any other package.

Now write a backend that answers with its own port, so you can see which one served each request. It has three routes: / answers at once, /slow waits five seconds, and /health answers ok unless a file named down-<port> exists next to the script, which lets you make a backend fail its health check on purpose.

Bash
mkdir -p ~/haproxy-demo
cat > ~/haproxy-demo/backend.py <<'PY'
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

port = int(sys.argv[1])
down_flag = Path(__file__).with_name(f"down-{port}")

class Handler(BaseHTTPRequestHandler):
    def reply(self, status, text):
        body = text.encode()
        self.send_response(status)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/health":
            if down_flag.exists():
                self.reply(503, "unhealthy\n")
            else:
                self.reply(200, "ok\n")
            return
        if self.path == "/slow":
            time.sleep(5)
        self.reply(200, f"backend {port}\n")

    def log_message(self, *args):
        pass

ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
PY
for port in 9101 9102 9103; do
  nohup python3 ~/haproxy-demo/backend.py "$port" > /dev/null 2>&1 &
done
sleep 1
for port in 9101 9102 9103; do curl -s "http://127.0.0.1:$port/"; done

ThreadingHTTPServer handles each request in its own thread, so a slow request does not block the health checks that HAProxy sends to the same backend.

Check it worked

haproxy -v prints a first line that starts with HAProxy version 3.4. The loop prints backend 9101, backend 9102 and backend 9103, one per line.

Step 2 · Write a first configuration and reload safely

An HAProxy configuration has four kinds of section you need here:

  • global sets process-wide options: where to log, which user to drop to, and the runtime API socket.
  • defaults sets values that every later section inherits, such as the mode and the timeouts.
  • frontend describes what HAProxy listens on, and which backend gets the traffic.
  • backend lists the servers and how to choose between them.

Keep a copy of the stock file before you replace it, because the next command empties it:

Bash
sudo cp -p /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.orig
sudo install -m 640 -o root -g haproxy /dev/null /etc/haproxy/haproxy.cfg

The install line recreates the file readable only by root and the haproxy group. A later step adds a password hash to it, so it should not be world-readable.

Write the configuration:

Bash
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
    log /dev/log local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy

defaults
    mode http
    log global
    option httplog
    option dontlognull
    option forwardfor
    timeout connect 5s
    timeout client 30s
    timeout server 30s

frontend www
    bind :80
    default_backend app

backend app
    balance roundrobin
    server web1 127.0.0.1:9101
    server web2 127.0.0.1:9102
    server web3 127.0.0.1:9103
CFG

mode http makes HAProxy parse HTTP, which the health checks, the stats page and option forwardfor need. option forwardfor adds an X-Forwarded-For header, so your app sees the visitor's address and not HAProxy's. The three timeouts stop a stuck connection from holding resources for ever. timeout client and timeout server are inactivity timeouts: they close a connection only when that side sends nothing for 30 seconds, so a slow upload that keeps sending data is not cut off. Raise them when a side can legitimately go quiet for longer, for example a backend that takes a minute to build a report before it sends the first byte, or long polling, where the server holds a request open until it has news. In both cases timeout server matters as much as timeout client.

Before every reload, check the file. haproxy -c parses the configuration without touching the running process, so a typo never takes your site down:

Bash
sudo haproxy -c -f /etc/haproxy/haproxy.cfg

When the file is valid it prints nothing and exits with status 0; when it is not, it prints each error with its file and line number and exits with a non-zero status. Add -V if you want it to say Configuration file is valid as well. Only then reload:

Bash
sudo systemctl reload haproxy

A reload starts new worker processes with the new configuration and lets the old ones finish the requests they are serving, so no visitor sees an error.

Check it worked

Send six requests through HAProxy:

Bash
for i in 1 2 3 4 5 6; do curl -s http://127.0.0.1/; done | sort | uniq -c

With roundrobin, each server takes the next request in turn, so each backend answers twice: 2 backend 9101, 2 backend 9102 and 2 backend 9103.

Step 3 · Add HTTP health checks

Right now HAProxy only learns that a backend has gone when a connection to it fails. An active health check asks each server a question every few seconds and takes it out of rotation when the answer is wrong. This catches an app that still accepts connections but can no longer do its job, for example because its database is unreachable.

Replace the configuration. Only the backend section changes:

Bash
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
    log /dev/log local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy

defaults
    mode http
    log global
    option httplog
    option dontlognull
    option forwardfor
    timeout connect 5s
    timeout client 30s
    timeout server 30s

frontend www
    bind :80
    default_backend app

backend app
    balance roundrobin
    option httpchk
    http-check send meth GET uri /health
    http-check expect status 200
    default-server check inter 2s fall 2 rise 2
    server web1 127.0.0.1:9101
    server web2 127.0.0.1:9102
    server web3 127.0.0.1:9103
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
Bash
sudo systemctl reload haproxy
  • option httpchk switches the checks from a plain TCP connect to an HTTP request.
  • http-check send sets the request: GET /health. Point it at a route that tests what your app depends on, and keep it cheap, because it runs constantly.
  • http-check expect status 200 passes only on a 200. A 503 from the app, or no answer within the check interval, is a failure.
  • default-server applies settings to every server line below it. check turns checks on, inter 2s checks every two seconds, fall 2 marks a server down after two failures in a row and rise 2 brings it back after two passes. Without these, the defaults are 2 seconds, 3 failures and 2 passes.

Check it worked

Make web1 report itself unhealthy, wait for two failed checks, and ask HAProxy for its view through the runtime socket:

Bash
touch ~/haproxy-demo/down-9101
sleep 6
echo "show stat app 4 -1" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f2,18
for i in 1 2 3 4; do curl -s http://127.0.0.1/; done | sort | uniq -c

show stat app 4 -1 lists the servers of the app backend as CSV, and cut keeps the server name and its status. After the header line you see web1,DOWN, web2,UP and web3,UP. The four requests are shared between backend 9102 and backend 9103; none reach 9101, even though its process is still running.

Bring it back:

Bash
rm ~/haproxy-demo/down-9101
sleep 6
echo "show stat app 4 -1" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f2,18

All three servers show UP again.

Step 4 · Compare roundrobin with leastconn

roundrobin ignores how busy each server is. That is fine when every request takes about the same time. When some requests are slow (reports, uploads, long polling, WebSockets), a server can pile up slow work while still getting its full share of new requests. leastconn sends each new request to the server with the fewest open connections, and rotates between servers that are tied.

Switch the backend to leastconn:

Bash
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
    log /dev/log local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy

defaults
    mode http
    log global
    option httplog
    option dontlognull
    option forwardfor
    timeout connect 5s
    timeout client 30s
    timeout server 30s

frontend www
    bind :80
    default_backend app

backend app
    balance leastconn
    option httpchk
    http-check send meth GET uri /health
    http-check expect status 200
    default-server check inter 2s fall 2 rise 2
    server web1 127.0.0.1:9101
    server web2 127.0.0.1:9102
    server web3 127.0.0.1:9103
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
Bash
sudo systemctl reload haproxy

Check it worked

Start two slow requests in the background, so two backends are busy for five seconds, then send four quick ones:

Bash
curl -s http://127.0.0.1/slow > ~/haproxy-demo/slow-a.txt &
slow_a=$!
curl -s http://127.0.0.1/slow > ~/haproxy-demo/slow-b.txt &
slow_b=$!
sleep 1
for i in 1 2 3 4; do curl -s http://127.0.0.1/; done > ~/haproxy-demo/fast.txt
wait "$slow_a" "$slow_b"
sort ~/haproxy-demo/fast.txt | uniq -c
cat ~/haproxy-demo/slow-a.txt ~/haproxy-demo/slow-b.txt

$! holds the process ID of the last background command, so wait waits only for the two slow requests. A bare wait would also wait for the three backends you started in the background in the first step, and never return.

All four quick requests went to the one backend that had no slow request open, so sort | uniq -c prints a single line with a count of 4. The two slow answers name the other two backends. With roundrobin, two of the quick requests would have gone to the busy backends. Here each request gets its own thread, so they would still be answered at once, but on an app with a fixed number of workers they would wait behind the slow work.

HAProxy's own documentation recommends leastconn for long sessions and says it suits short HTTP requests less well, so pick it when your request times vary a lot, and keep roundrobin otherwise. The next step goes back to roundrobin, because the effect of weights is easiest to see with it.

Step 5 · Weight the servers and add a backup

If one backend has more CPU than the others, give it a larger weight. The default is 1 and the maximum 256; a server with weight 3 gets three requests for every one a weight-1 server gets. HAProxy's documentation suggests values such as 10 to 100 in production, so you have room to adjust later; this step uses 3 and 1 so the counts are easy to read.

A server marked backup gets no traffic while any normal server is up. It is the spare you keep for when everything else has failed, such as a small instance that serves a maintenance page.

Bash
sudo tee /etc/haproxy/haproxy.cfg > /dev/null <<'CFG'
global
    log /dev/log local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy

defaults
    mode http
    log global
    option httplog
    option dontlognull
    option forwardfor
    timeout connect 5s
    timeout client 30s
    timeout server 30s

frontend www
    bind :80
    default_backend app

backend app
    balance roundrobin
    option httpchk
    http-check send meth GET uri /health
    http-check expect status 200
    default-server check inter 2s fall 2 rise 2
    server web1 127.0.0.1:9101 weight 3
    server web2 127.0.0.1:9102 weight 1
    server web3 127.0.0.1:9103 backup
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
Bash
sudo systemctl reload haproxy

Check it worked

Bash
for i in $(seq 1 8); do curl -s http://127.0.0.1/; done | sort | uniq -c

Out of eight requests, backend 9101 answers six and backend 9102 answers two, or very close to that. backend 9103 does not appear, because it is the backup.

Now fail both normal servers and watch the backup take over:

Bash
touch ~/haproxy-demo/down-9101 ~/haproxy-demo/down-9102
sleep 6
for i in 1 2 3; do curl -s http://127.0.0.1/; done

All three requests print backend 9103.

Bring the normal servers back:

Bash
rm ~/haproxy-demo/down-9101 ~/haproxy-demo/down-9102
sleep 6
for i in 1 2 3 4; do curl -s http://127.0.0.1/; done | sort | uniq -c

After two passed checks, traffic goes back to 9101 and 9102, and backend 9103 drops out of the counts.

Step 6 · Add a stats page behind a password

HAProxy has a built-in web page that shows every frontend, backend and server with its state, check results and traffic counters. Bind it to 127.0.0.1 so it is never reachable from the internet, and put a password on it as well, because anyone with a shell on the server could otherwise read it.

Create a SHA-512 hash of a password of your choice. openssl passwd prompts for it twice, so it never appears in your shell history:

Bash
HASH=$(openssl passwd -6)

Append a user list and a stats section to the configuration. The heredoc delimiter is not quoted here, so the shell fills in $HASH:

Bash
sudo tee -a /etc/haproxy/haproxy.cfg > /dev/null <<CFG

userlist stats_users
    user admin password '$HASH'

listen stats
    bind 127.0.0.1:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats http-request auth realm stats unless { http_auth(stats_users) }
CFG
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
Bash
sudo systemctl reload haproxy

A userlist holds users for HTTP basic authentication. With password, HAProxy compares a hash, so the configuration never holds the password itself. Each request to the stats page runs the hash function, which is deliberately slow; that is fine for one admin page, but do not use hashed passwords this way on high-traffic routes. The stats http-request rule only works in a listen or backend section, which is why this is a listen section and not a frontend.

Check it worked

Without a password the page refuses you:

Bash
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8404/stats

It prints 401. With the user admin, curl prompts for the password and prints 200:

Bash
curl -s -u admin -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8404/stats

To see the page in a browser, open an SSH tunnel. Run this on your laptop, replacing you@your-server with your login and server address:

Bash
ssh -N -L 8404:127.0.0.1:8404 you@your-server

Leave it running and open http://localhost:8404/stats on your laptop. After you sign in as admin, you see a table for the app backend with web1 and web2 in green and web3 marked as a backup. Press Ctrl+C in the terminal to close the tunnel.

Step 7 · Drain a server through the runtime API

Before you patch or restart a backend, take it out of rotation so it finishes its current requests and gets no new ones. The runtime API on /run/haproxy/admin.sock does this without a reload.

Bash
echo "set server app/web1 state drain" | sudo socat stdio /run/haproxy/admin.sock
echo "show stat app 4 -1" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f2,18

web1 now shows DRAIN. A drained server keeps being health-checked, so you still see whether it is healthy, but the load balancer gives it no new requests. The other states are maint, which also stops the health checks, and ready, which puts the server back.

Check it worked

Bash
for i in 1 2 3 4; do curl -s http://127.0.0.1/; done | sort | uniq -c

All four requests print backend 9102. The backup stays idle, because web2 is still up. On the stats page, the web1 row changes colour to show it is draining.

When the work on web1 is done, put it back:

Bash
echo "set server app/web1 state ready" | sudo socat stdio /run/haproxy/admin.sock
echo "show stat app 4 -1" | sudo socat stdio /run/haproxy/admin.sock | cut -d, -f2,18

web1 shows UP again. Changes made through the runtime API live only in the running process: the next reload or restart reads the configuration file afresh. To keep a server out for longer, add disabled to its server line, check the file with haproxy -c and reload.

Step 8 · Clean up

Stop the three backends, delete the demo folder and put the stock configuration back. Skip the configuration restore if you are going on to the TLS tutorial below, which starts from this setup.

Bash
pkill -f 'haproxy-demo/[b]ackend.py'
rm -rf ~/haproxy-demo
sudo cp -p /etc/haproxy/haproxy.cfg.orig /etc/haproxy/haproxy.cfg

The stock file has only global and defaults sections and no frontend or bind line. It is valid, so the check passes:

Bash
sudo haproxy -c -f /etc/haproxy/haproxy.cfg

A reload with this file would leave HAProxy running but serving nothing on port 80, so stop it instead:

Bash
sudo systemctl stop haproxy

If you no longer need HAProxy at all, remove it, its saved configuration and the PPA:

Bash
sudo apt purge -y haproxy
sudo rm -f /etc/haproxy/haproxy.cfg.orig
sudo add-apt-repository -y --remove ppa:vbernat/haproxy-3.4

Check it worked

Bash
pgrep -f 'haproxy-demo/[b]ackend.py' || echo "no backends running"
apt-cache policy haproxy | sed -n '1,3p'

The first command prints no backends running. If you removed HAProxy, apt-cache policy shows Installed: (none).

Next steps

  • Serve HTTPS at the balancer and send each hostname to its own backend with /tutorials/terminate-tls-and-route-by-hostname-with-haproxy.
  • Compare the same job in Nginx, which checks backends passively, with /tutorials/load-balance-with-nginx-upstream.
  • Try a lighter setup with automatic HTTPS in /tutorials/reverse-proxy-and-load-balance-with-caddy.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.