Prerequisites
Before configuring HAProxy, make sure you have:
- A dedicated VPS for HAProxy (or run on same VPS)
- Two or more backend web servers
- Root or sudo privileges
Step 1: Install HAProxy
Connect to your HAProxy VPS:
ssh hxroot@YOUR_SERVER_IP -p 22
sudo apt update
sudo apt install haproxy -y
Step 2: Configure HAProxy
Backup default config:
sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak
sudo nano /etc/haproxy/haproxy.cfg
Example for HTTP load balancing:
global
log /dev/log local0
maxconn 4096
user haproxy
group haproxy
defaults
log global
mode http
option httplog
option dontlognull
retries 3
timeout connect 5000
timeout client 50000
timeout server 50000
frontend http_front
bind *:80
stats uri /haproxy?stats
default_backend http_back
backend http_back
balance roundrobin
server web1 BACKEND1_IP:80 check
server web2 BACKEND2_IP:80 check
Step 3: Enable HAProxy
sudo systemctl enable haproxy
sudo systemctl start haproxy
Step 4: Allow Firewall Port
sudo ufw allow 80/tcp
Step 5: Check HAProxy Status
sudo systemctl status haproxy
Step 6: Access Statistics Page
Visit http://YOUR_HAPROXY_IP/haproxy?stats (username: stats, password: stats by default). You can change credentials in config.
Configure HTTPS Load Balancing
Add SSL termination:
frontend https_front
bind *:443 ssl crt /etc/ssl/certs/haproxy.pem
default_backend http_back
Generate self-signed or copy your SSL certificate and key into a combined .pem file.
Load Balancing Algorithms
- roundrobin – Distributes equally (default)
- leastconn – Sends to server with fewest connections
- source – Ensures client sticks to same backend (session persistence)
Health Checks Customization
server web1 BACKEND1_IP:80 check inter 2000 rise 2 fall 3
Check every 2 seconds, require 2 successes, mark down after 3 failures.
Test HAProxy
Generate traffic to your HAProxy IP and check statistics page to see distribution.
✅ HAProxy configured. Traffic is now balanced across your backend servers.