Docs / Networking / How to Set Up HAProxy for TCP and HTTP Load Balancing

How to Set Up HAProxy for TCP and HTTP Load Balancing

By Admin · Mar 15, 2026 · Updated Apr 23, 2026 · 255 views · 2 min read

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 haproxy

HTTP 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 backup

TCP 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 backup

Load 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 header

Health 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 successes

Session 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 web2

Stats Dashboard

# Enable HAProxy statistics page
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats auth admin:YourPassword
    stats hide-version

Testing and Reloading

# Validate configuration
sudo haproxy -c -f /etc/haproxy/haproxy.cfg

# Reload without dropping connections
sudo systemctl reload haproxy

Was this article helpful?