HAProxy: Frontends & Backends
HAProxy does one job: it is a load balancer and proxy for TCP and HTTP, and nothing else (no static files, no cache beyond a small one, no application code). In exchange it is extremely fast, has the richest set of load-balancing, health-checking and traffic-control features of the four servers here, and can be changed while running through its Runtime API. It sits in front of many of the largest sites and inside many products (OpenShift's router, several cloud load balancers).
The configuration's sections
global process-wide: user, pid file, logging, the stats socket, TLS defaults, maxconn
defaults default settings for the proxies below (mode, timeouts, options); can be repeated
frontend NAME what clients connect to: bind addresses, ACLs, which backend to use
backend NAME a pool of servers: balancing algorithm, health checks, the server lines
listen NAME frontend + backend in one section (handy for simple TCP services and the stats page)A request flows frontend → (rules) → backend → server. Each section is a list of keywords, one per line; order matters for rules (http-request … lines run top to bottom), not for most settings.
| Keyword | Meaning |
|---|---|
mode http / mode tcp |
layer 7 (parses HTTP: headers, paths, cookies) or layer 4 (just bytes: databases, TLS passthrough, anything) |
timeout connect/client/server |
connecting to a server / client inactivity / server inactivity. HAProxy warns if they are missing |
option forwardfor |
add X-Forwarded-For with the client address |
option httplog |
the detailed HTTP log format (see Access Log Formats) |
maxconn |
connection limit (global, per frontend, per server: excess connections queue) |
default_backend / use_backend |
where requests go |
A first configuration
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.end_headers()
self.wfile.write(f"{sys.argv[2]} path={self.path} xff={self.headers.get('X-Forwarded-For')}\n".encode())
def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 web1 &
python3 app.py 9002 web2 &
for p in 9001 9002; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > haproxy.cfg <<'EOF'
global
pidfile haproxy.pid
maxconn 2000
defaults
mode http
timeout connect 2s
timeout client 30s
timeout server 30s
frontend fe_web
bind 127.0.0.1:8080
option forwardfor
default_backend be_app
backend be_app
balance roundrobin
server web1 127.0.0.1:9001
server web2 127.0.0.1:9002
listen raw_tcp # layer 4: no HTTP parsing, no headers added
mode tcp
bind 127.0.0.1:8081
server web1 127.0.0.1:9001
listen stats
bind 127.0.0.1:8404
stats enable
stats uri /stats
stats refresh 10s
EOF
haproxy -c -f haproxy.cfg
haproxy -D -f haproxy.cfg
for i in 1 2 3; do curl -s 127.0.0.1:8080/orders; done
echo "--- tcp mode:"; curl -s 127.0.0.1:8081/orders
echo "--- stats as CSV (proxy, server, total sessions, status):"
curl -s "127.0.0.1:8404/stats;csv" | cut -d, -f1,2,8,18 | grep -E '^(fe_web|be_app)'
kill $(cat haproxy.pid) %1 %2Configuration file is valid
web1 path=/orders xff=127.0.0.1
web2 path=/orders xff=127.0.0.1
web1 path=/orders xff=127.0.0.1
--- tcp mode:
web1 path=/orders xff=None
--- stats as CSV (proxy, server, total sessions, status):
fe_web,FRONTEND,3,OPEN
be_app,web1,2,no check
be_app,web2,1,no check
be_app,BACKEND,3,UP
haproxy -c is the check to run before every reload. In HTTP mode HAProxy added X-Forwarded-For; in TCP mode it passed the bytes untouched, so the backend saw no header at all. The stats page (/stats in a browser, ;csv for scripts) shows every frontend, backend and server with its state and counters (no check means the server has no health check, so HAProxy assumes it is up; the Health Checks lesson fixes that). Expose it only on an internal address, and protect it with stats auth user:password if anything else can reach it.
Errors HAProxy catches
cat > haproxy.cfg <<'EOF'
global
pidfile haproxy.pid
defaults
mode http
frontend fe_web
bind 127.0.0.1:8080
default_backend be_ap
backend be_app
server web1 127.0.0.1:9001 chek
EOF
check() { haproxy -c -f haproxy.cfg 2>&1 | grep -E 'ALERT|WARNING|valid' | sed -E 's/^\[([A-Z]*)\] *\([0-9]*\) : /\1: /'; }
check
echo "--- after fixing the typo:"
sed -i 's/ chek$/ check/' haproxy.cfg
checkALERT: config : [haproxy.cfg:9] : 'server be_app/web1' : unknown keyword 'chek'; did you mean 'check' maybe ?
ALERT: config : Error(s) found in configuration file : haproxy.cfg
ALERT: config : Fatal errors found in configuration.
--- after fixing the typo:
ALERT: config : Proxy 'fe_web': unable to find required default_backend: 'be_ap'.
WARNING: config : missing timeouts for frontend 'fe_web'.
| While not properly invalid, you will certainly encounter various problems
WARNING: config : missing timeouts for backend 'be_app'.
| While not properly invalid, you will certainly encounter various problems
ALERT: config : Fatal errors found in configuration.
HAProxy stops at the first parse error (a typo, with a suggestion), so problems surface one round at a time: only after the fix does it report the backend name that doesn't exist. Missing timeouts are only warnings, but take them seriously: without timeout client, a client that disappears without closing its connection holds it forever.
On a real server
# Sample session (Ubuntu 24.04, haproxy 2.8 package)
$ sudoedit /etc/haproxy/haproxy.cfg
$ sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy
Configuration file is valid
$ journalctl -u haproxy -n 3 -o cat
[NOTICE] (1201) : Reloading HAProxy
[NOTICE] (1201) : New worker (2290) forked
[NOTICE] (1201) : Loading success.The packaged service runs HAProxy in master-worker mode: systemctl reload makes the master start a new worker with the new configuration, which takes over the listening sockets, while the old worker finishes its connections (Zero-Downtime Reloads). Ubuntu's default config sends logs to syslog through /dev/log, so they appear in the journal and /var/log/haproxy.log.
HAProxy versions: even-numbered releases (2.8, 3.0, 3.2, …) are LTS with five years of fixes; odd ones are short-lived. Ubuntu 24.04 ships 2.8 LTS; the HAProxy team's PPA (ppa:vbernat/haproxy-3.2 and similar) provides newer LTS lines. Everything in this course works on 2.8.
Test yourself
Which section receives client connections and decides where requests go?
- global
- defaults
- frontend
- backend
In mode tcp, can HAProxy add an X-Forwarded-For header?
- Yes, with option forwardfor
- No: in TCP mode it doesn't parse HTTP; use the PROXY protocol (
send-proxy) to pass the client address - Only with TLS
- Only for GET
What does haproxy -c -f haproxy.cfg do?
- Starts HAProxy
- Checks the configuration and reports errors and warnings without starting
- Clears the counters
- Converts the config