HAProxy is a high-performance, open-source load balancer and proxy server. It handles millions of connections per second and is used by some of the largest websites in the world. This guide covers configuring HAProxy for both HTTP and TCP load balancing.
Installation
sudo apt install haproxy
sudo systemctl enable haproxyHTTP Load Balancing
# /etc/haproxy/haproxy.cfg
global
log /dev/log local0
maxconn 50000
daemon
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5s
timeout client 30s
timeout server 30s
retries 3
frontend http_front
bind *:80
bind *:443 ssl crt /etc/haproxy/certs/combined.pem
redirect scheme https code 301 if !{ ssl_fc }
default_backend web_servers
backend web_servers
balance roundrobin
option httpchk GET /health
server web1 10.0.0.1:8080 check
server web2 10.0.0.2:8080 check
server web3 10.0.0.3:8080 check backupTCP Load Balancing
# For non-HTTP protocols (MySQL, Redis, etc.)
frontend mysql_front
bind *:3306
mode tcp
default_backend mysql_servers
backend mysql_servers
mode tcp
balance leastconn
option mysql-check user haproxy
server db1 10.0.0.10:3306 check
server db2 10.0.0.11:3306 check backupLoad Balancing Algorithms
# roundrobin — Equal distribution (default)
# leastconn — Send to server with fewest connections
# source — Hash client IP for session persistence
# uri — Hash URI for cache-friendly distribution
# hdr(Host) — Hash by Host headerHealth Checks
# HTTP health check
option httpchk GET /health
http-check expect status 200
# TCP health check (default: TCP connect)
option tcp-check
# Custom check interval
server web1 10.0.0.1:8080 check inter 5s fall 3 rise 2
# inter 5s: check every 5 seconds
# fall 3: mark down after 3 consecutive failures
# rise 2: mark up after 2 consecutive successesSession Persistence (Sticky Sessions)
backend web_servers
balance roundrobin
cookie SERVERID insert indirect nocache
server web1 10.0.0.1:8080 check cookie web1
server web2 10.0.0.2:8080 check cookie web2Stats Dashboard
# Enable HAProxy statistics page
listen stats
bind *:8404
stats enable
stats uri /stats
stats refresh 10s
stats auth admin:YourPassword
stats hide-versionTesting and Reloading
# Validate configuration
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
# Reload without dropping connections
sudo systemctl reload haproxy