What Is HAProxy?
HAProxy is a high-performance TCP/HTTP load balancer and proxy server. It distributes incoming traffic across multiple backend servers for improved performance and reliability.
Installation
sudo apt update && sudo apt install -y haproxyBasic HTTP Load Balancing
Edit /etc/haproxy/haproxy.cfg:
frontend http_front
bind *:80
default_backend web_servers
backend web_servers
balance roundrobin
option httpchk GET /health
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
server web3 192.168.1.12:80 checkLoad Balancing Algorithms
| Algorithm | Description |
|---|---|
roundrobin | Cycle through servers sequentially |
leastconn | Send to server with fewest connections |
source | Hash client IP (sticky sessions) |
uri | Hash URI for cache-friendly distribution |
SSL Termination
frontend https_front
bind *:443 ssl crt /etc/haproxy/certs/example.com.pem
http-request redirect scheme https unless { ssl_fc }
default_backend web_serversHealth Checks
backend web_servers
option httpchk GET /health HTTP/1.1\r\nHost:\ example.com
http-check expect status 200
server web1 192.168.1.10:80 check inter 5s fall 3 rise 2Stats Dashboard
listen stats
bind *:8404
stats enable
stats uri /stats
stats refresh 10s
stats admin if LOCALHOSTAccess at http://your-ip:8404/stats for real-time metrics on all backends.
Validate and Reload
haproxy -c -f /etc/haproxy/haproxy.cfg
sudo systemctl reload haproxy