Setting Up HAProxy as a Load Balancer
HAProxy distributes incoming traffic across multiple backend servers to improve availability and performance.
Install HAProxy
apt update
apt install haproxy -y
Basic Configuration
nano /etc/haproxy/haproxy.cfg
global
log /dev/log local0
maxconn 4096
defaults
log global
mode http
timeout connect 5s
timeout client 30s
timeout server 30s
frontend http_in
bind *:80
default_backend webservers
backend webservers
balance roundrobin
option httpchk GET /health
server web1 192.168.1.101:80 check
server web2 192.168.1.102:80 check
server web3 192.168.1.103:80 check
Balance Algorithms
roundrobin— distribute requests evenly in rotationleastconn— send to the server with fewest active connections (best for long-lived connections)source— sticky sessions by client IP
Enable the Stats UI
listen stats
bind *:8404
stats enable
stats uri /stats
stats auth admin:password
Access at http://YOUR_SERVER_IP:8404/stats.
Start and Enable HAProxy
systemctl enable haproxy
systemctl start haproxy
SSL Termination at HAProxy
frontend https_in
bind *:443 ssl crt /etc/ssl/certs/yourdomain.pem
default_backend webservers
Combine your certificate and key into one PEM file: cat fullchain.pem privkey.pem > yourdomain.pem