Mastering HAProxy: Installation, L7/L4 Load Balancing, and High‑Availability Setup
This comprehensive guide explains what HAProxy is, its core capabilities and performance characteristics, walks through installing and configuring it on CentOS 7 for both L7 and L4 load‑balancing scenarios, and shows how to achieve high availability using Keepalived, complete with practical code snippets and sysctl tuning.
Overview
HAProxy is an open‑source, high‑performance load‑balancer that runs on most Linux distributions. It supports Layer 4 (TCP) and Layer 7 (HTTP) balancing, health checking, SSL termination, session persistence, request rewriting, and a built‑in web statistics page.
Core capabilities
Balancing algorithms: round‑robin, static‑rr, least‑connections, source‑IP hash, URI hash, header hash, etc.
Health checks in TCP and HTTP modes.
Session persistence via insert/rewriter/prefix cookies or hash‑based stickiness.
SSL termination and HTTP request/response rewriting.
Real‑time statistics page (optional authentication).
Performance
Single‑process, event‑driven, non‑blocking architecture (O(1) event lookup, zero‑copy forwarding).
Typical CPU usage < 15 % even under heavy load; can handle >100 k requests/s and 10 Gbps line rate on modern hardware.
Stability
HAProxy runs as a single process; stability largely depends on the underlying kernel. Recommended kernel: 2.6 or newer with tuned sysctl parameters:
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65023
net.ipv4.tcp_max_syn_backlog = 10240
net.ipv4.tcp_max_tw_buckets = 400000
net.ipv4.tcp_max_orphans = 60000
net.ipv4.tcp_synack_retries = 3
net.core.somaxconn = 10000Installing HAProxy on CentOS 7
Create a dedicated system user (e.g., ha).
Download and extract the source package:
wget http://www.haproxy.org/download/1.7/src/haproxy-1.7.2.tar.gz
tar -xzf haproxy-1.7.2.tar.gzCompile and install (kernel 3.10 → TARGET=linux2628):
make PREFIX=/home/ha/haproxy TARGET=linux2628
make install PREFIX=/home/ha/haproxyCreate /home/ha/haproxy/conf/haproxy.cfg (example shown below).
Install an init script in /etc/init.d/haproxy (or a systemd unit) and enable the service.
Control the daemon with service haproxy start|stop|restart (or systemctl).
Minimal configuration
global
daemon
maxconn 256
pidfile /home/ha/haproxy/conf/haproxy.pid
defaults
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend http-in
bind *:8080
default_backend servers
backend servers
server server1 127.0.0.1:8000 maxconn 32 checkFor production use increase maxconn and raise the file descriptor limit: ulimit -n >= maxconn*2+18.
Logging with rsyslog
Add log directives to the global and defaults sections, e.g.:
log 127.0.0.1 local0 info
log 127.0.0.1 local1 warningCreate /etc/rsyslog.d/haproxy.conf to route the logs:
local0.* /var/log/haproxy.log
local1.* /var/log/haproxy_warn.logRestart rsyslog and HAProxy after changes.
Layer 7 (HTTP) load‑balancing example
The configuration below demonstrates URI‑based routing, cookie persistence, health checks, and a statistics page.
global
daemon
maxconn 30000
user ha
pidfile /home/ha/haproxy/conf/haproxy.pid
log 127.0.0.1 local0 info
log 127.0.0.1 local1 warning
defaults
mode http
log global
option http-keep-alive
option forwardfor
option httplog
timeout connect 5000ms
timeout client 10000ms
timeout server 50000ms
timeout http-request 20000ms
option httpchk GET /healthCheck.html
frontend http-in
bind *:9001
maxconn 30000
acl url_ms1 path_beg -i /ms1/
acl url_ms2 path_beg -i /ms2/
use_backend ms1 if url_ms1
use_backend ms2 if url_ms2
default_backend default_servers
backend ms1
balance roundrobin
cookie HA_STICKY_ms1 insert indirect nocache
server ms1.srv1 192.168.8.111:8080 cookie ms1.srv1 maxconn 300 check
server ms1.srv2 192.168.8.112:8080 cookie ms1.srv2 maxconn 300 check
backend ms2
balance roundrobin
cookie HA_STICKY_ms2 insert indirect nocache
server ms2.srv1 192.168.8.111:8081 cookie ms2.srv1 maxconn 300 check
server ms2.srv2 192.168.8.112:8081 cookie ms2.srv2 maxconn 300 check
backend default_servers
balance roundrobin
cookie HA_STICKY_def insert indirect nocache
server def.srv1 192.168.8.111:8082 cookie def.srv1 maxconn 300 check
server def.srv2 192.168.8.112:8082 cookie def.srv2 maxconn 300 check
listen stats
bind *:1080
stats refresh 30s
stats uri /stats
stats realm "HAProxy Stats"
stats auth admin:adminAfter reloading HAProxy, the statistics page is reachable at http://<em>host</em>:1080/stats (basic authentication required).
Layer 4 (TCP) load‑balancing example
TCP mode disables HTTP‑specific features but provides higher throughput for raw‑socket services.
global
daemon
maxconn 30000
user ha
pidfile /home/ha/haproxy/conf/haproxy.pid
log 127.0.0.1 local0 info
log 127.0.0.1 local1 warning
defaults
mode tcp
log global
option tcplog
timeout connect 5000ms
timeout client 10000ms
timeout server 10000ms
option httpchk GET /healthCheck.html
frontend tcp-in
bind *:9002
maxconn 30000
default_backend tcp_backends
backend tcp_backends
balance roundrobin # replace with "source" for IP‑based stickiness
server def.srv1 192.168.8.111:8082 maxconn 300 check
server def.srv2 192.168.8.112:8082 maxconn 300 checkHigh availability with Keepalived
Running two HAProxy instances behind Keepalived provides automatic failover. The instance with the higher VRRP priority becomes MASTER; the virtual IP moves to the surviving node when MASTER stops.
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_haproxy {
script "killall -0 haproxy"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER # set BACKUP on the secondary host
interface enp0s25
virtual_router_id 51
priority 101 # secondary host uses a lower value, e.g., 100
advert_int 1
virtual_ipaddress {
192.168.8.201
}
track_script {
chk_haproxy
}
}Install Keepalived, register it as a service, and start it on both nodes. The virtual IP 192.168.8.201 will always be bound to the active HAProxy instance.
Configuration sections reference
global : daemon mode, user/group, log destinations, pidfile, maxconn.
defaults : common settings for all frontends/backends (mode, timeouts, logging, options).
frontend : bind address/port, ACL definitions, use_backend routing, stats settings.
backend : load‑balancing algorithm, cookie persistence, server definitions (address, port, maxconn, health‑check parameters).
listen : combined frontend+backend for simple setups.
For a complete list of directives, consult the official HAProxy configuration documentation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Architects Alliance
Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
