HAProxy load balancer server infrastructure

HAProxy Load Balancer Setup on VPS

November 2026 · 10 min read

HAProxy (High Availability Proxy) is the world's most widely deployed production load balancer. It supports TCP and HTTP/HTTPS protocols, provides automatic health checks, sticky sessions, SSL termination, and a built-in stats dashboard. It's ideal for VPS setups that need to distribute traffic across multiple backend servers.


Install HAProxy

apt update
apt install haproxy -y
haproxy -v

Ubuntu 22.04/24.04 provides HAProxy 2.4+ directly. For a newer version, use the official PPA:

add-apt-repository ppa:vbernat/haproxy-2.9
apt update
apt install haproxy=2.9.*

Configuration File Structure

The main config file is at /etc/haproxy/haproxy.cfg, divided into 4 sections:

SectionPurpose
globalProcess-level settings: log, user, maxconn
defaultsDefault values applied to all frontends/backends
frontendAccepts incoming connections and applies routing rules
backendServer pool that receives traffic from frontend

Basic Config: HTTP Load Balancing

# /etc/haproxy/haproxy.cfg

global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    maxconn 50000

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    option  forwardfor
    option  http-server-close
    timeout connect 5s
    timeout client  30s
    timeout server  30s

# Accept HTTP on port 80
frontend http_front
    bind *:80
    default_backend web_servers

# Backend server pool
backend web_servers
    balance roundrobin
    option httpchk GET /health
    server web1 192.168.1.10:8080 check
    server web2 192.168.1.11:8080 check
    server web3 192.168.1.12:8080 check
Tip: option forwardfor passes the X-Forwarded-For header to the backend so your app can see the real client IP.

Load Balancing Algorithms

Round Robin (Default)

balance roundrobin
server web1 192.168.1.10:8080 check weight 1
server web2 192.168.1.11:8080 check weight 2
# web2 receives twice the traffic of web1

Least Connections

balance leastconn
# Routes to the server with fewest active connections
# Best for long-lived connections: WebSocket, database

Source IP Hash (Sticky Sessions)

balance source
hash-type consistent
# Same client IP always routes to the same server

Health Checks

backend web_servers
    balance roundrobin
    option httpchk GET /healthz HTTP/1.1\r\nHost:\ localhost
    http-check expect status 200
    default-server inter 3s fall 3 rise 2
    server web1 192.168.1.10:8080 check
    server web2 192.168.1.11:8080 check

Health check parameters:

SSL Termination

# Combine cert + private key into single PEM file
cat /etc/ssl/certs/example.crt /etc/ssl/private/example.key > /etc/haproxy/certs/example.pem
chmod 600 /etc/haproxy/certs/example.pem

# HTTPS frontend config
frontend https_front
    bind *:443 ssl crt /etc/haproxy/certs/example.pem
    # Redirect HTTP → HTTPS
    bind *:80
    redirect scheme https code 301 if !{ ssl_fc }
    default_backend web_servers
Tip: Works with Let's Encrypt — add a post-renew script that merges the new cert automatically.

Stats Dashboard

frontend stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats auth admin:StrongPasswordHere
    stats show-legends
    stats show-node

Browse to http://your-vps-ip:8404/stats for a real-time dashboard showing connection counts, request rates, and server status.

Cookie-Based Sticky Sessions

backend web_servers
    balance roundrobin
    cookie SERVERID insert indirect nocache
    server web1 192.168.1.10:8080 check cookie s1
    server web2 192.168.1.11:8080 check cookie s2
    server web3 192.168.1.12:8080 check cookie s3

HAProxy injects a SERVERID cookie so the client always returns to the same server. Use this for apps storing sessions in memory.

Rate Limiting

frontend http_front
    bind *:80
    # Create stick table counting requests per IP
    stick-table type ip size 100k expire 30s store http_req_rate(10s)
    http-request track-sc0 src
    # Block if > 100 requests in 10 seconds
    http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }
    default_backend web_servers

Graceful Config Reload (Zero Downtime)

# Validate config before reload
haproxy -c -f /etc/haproxy/haproxy.cfg

# Graceful reload — no dropped connections
systemctl reload haproxy

Verify HAProxy Is Working Correctly

# Check service status
systemctl status haproxy

# View active connection count
echo "show info" | socat stdio /run/haproxy/admin.sock | grep CurrConns

# View all backend server states
echo "show servers state" | socat stdio /run/haproxy/admin.sock

# Test load balancing with curl
for i in {1..6}; do curl -s http://localhost/ | grep "Server:"; done

# Monitor logs in real time
tail -f /var/log/haproxy.log
Tip: Install socat with apt install socat to use admin socket commands conveniently.

Troubleshooting Common Issues

Error: "cannot bind to source address"

This occurs when the port HAProxy needs is still held from a previous restart. Check and clear it:

ss -tlnp | grep :80
# If another process is using the port
kill $(lsof -t -i:80)
systemctl start haproxy

Error: "backend has no server available"

All backend servers are down or health checks are failing. Diagnose with:

# Check backend status
echo "show stat" | socat stdio /run/haproxy/admin.sock | cut -d',' -f1,2,18,19

# Test health check endpoint from HAProxy server
curl -v http://192.168.1.10:8080/healthz

# Check recent error logs
journalctl -u haproxy --since "5 minutes ago" | grep -i error

Error: "SSL handshake failure"

Usually caused by an invalid PEM file or expired certificate:

# Check PEM certificate dates
openssl x509 -in /etc/haproxy/certs/example.pem -noout -dates
# Verify cert and key match
openssl x509 -noout -modulus -in cert.crt | md5sum
openssl rsa -noout -modulus -in private.key | md5sum

Error: "timeout during connect"

Backend server not responding within the configured timeout. Increase it in defaults:

defaults
    timeout connect 10s   # increased from 5s
    timeout server  60s   # for slow backends

Error: "haproxy: configuration file has errors"

Syntax error in config — always validate before reloading:

haproxy -c -f /etc/haproxy/haproxy.cfg
# Output shows the line number and description of any error

Frequently Asked Questions

How is HAProxy different from Nginx or Traefik?

HAProxy is purpose-built for load balancing and high availability, offering superior performance and more comprehensive health check, ACL, and stats features. Nginx excels as a web server and reverse proxy, while Traefik focuses on auto-discovery in container environments. HAProxy is the best choice for production clusters that prioritize stability and throughput.

Does HAProxy support WebSockets?

Yes. Use mode http with option http-server-close — WebSocket connections are automatically upgraded to a TCP tunnel. Use balance leastconn since WebSocket connections are long-lived.

How do I achieve zero-downtime deploys with HAProxy?

Drain each server before deploying to it: run echo "disable server web_servers/web1" | socat stdio /run/haproxy/admin.sock, deploy to web1, then re-enable it. Repeat for each server in the pool.