Comprehensive Guide to Installing, Configuring, and Using HAProxy for L7/L4 Load Balancing and High Availability
This tutorial explains what HAProxy is, its core capabilities and key features, provides step‑by‑step instructions for installing and running it on CentOS 7, demonstrates how to build both L7 and L4 load balancers, details essential configuration options, and shows how to achieve high availability with Keepalived, all illustrated with practical code examples and screenshots.
What is HAProxy
HAProxy is a free, open‑source load‑balancing software that runs on most mainstream Linux distributions, offering both L4 (TCP) and L7 (HTTP) balancing with a rich set of features and performance comparable to commercial solutions.
Core Capabilities and Key Features
Load‑balancing algorithms: round‑robin, static‑RR, least‑connection, IP/URI/HEADER hash, etc.
Health checks: TCP and HTTP modes.
Session persistence via cookies.
SSL termination and HTTP request rewriting.
Web‑based statistics page for monitoring.
Performance highlights include a single‑threaded, event‑driven, non‑blocking architecture that can handle hundreds of requests per millisecond with only a few kilobytes of memory per session, and reported throughput of over 100 k requests/second.
Installation and Operation on CentOS 7
Create a dedicated user/group (e.g., ha ), download the source, extract, compile, and install:
wget http://www.haproxy.org/download/1.7/src/haproxy-1.7.2.tar.gz
tar -xzf haproxy-1.7.2.tar.gz
make PREFIX=/home/ha/haproxy TARGET=linux2628
make install PREFIX=/home/ha/haproxyAdjust sysctl parameters for optimal performance, for example:
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65023
net.ipv4.tcp_max_syn_backlog = 10240
net.core.somaxconn = 10000Register HAProxy as a system service using an init script placed in /etc/init.d/haproxy and control it with service haproxy start|stop|restart .
Adding Logging via rsyslog
Configure HAProxy to send logs to rsyslog (local0 for info, local1 for warnings) and create /etc/rsyslog.d/haproxy.conf :
$ModLoad imudp
$UDPServerRun 514
local0.* /var/log/haproxy.log
local1.* /var/log/haproxy_warn.logRestart both services to apply the changes.
Building an L7 Load Balancer
Define a simple configuration that balances traffic based on URI prefixes, enables session persistence with cookies, and provides 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
option httpchk GET /healthCheck.html
frontend http-in
bind *:9001
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 uri /stats
stats refresh 30s
stats realm HAProxy\ Stats
stats auth admin:adminAfter reloading HAProxy, you can test the setup by accessing http:// host :9001/ms1/demo.html , /ms2/ , and /def/ and observing the cookies that enforce persistence.
Building an L4 Load Balancer
Switch the mode to tcp and use a simple round‑robin or source‑based balancing. Cookie‑based persistence is unavailable, but IP‑based persistence can be achieved by changing balance roundrobin to balance source .
Key Configuration Details
The HAProxy configuration file is divided into five sections: global , defaults , frontend , backend , and listen . Each section controls specific aspects such as process limits, logging, ACLs, binding ports, health checks, timeouts, and load‑balancing algorithms.
Using Keepalived for High Availability
Deploy two HAProxy instances on separate hosts and run Keepalived on each. Keepalived manages a virtual IP (e.g., 192.168.8.201 ) and uses a VRRP script to monitor HAProxy health. The instance with the highest priority holds the virtual IP and acts as MASTER; if it fails, the BACKUP automatically takes over.
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_haproxy {
script "killall -0 haproxy"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface enp0s25
virtual_router_id 51
priority 101
advert_int 1
virtual_ipaddress {
192.168.8.201
}
track_script {
chk_haproxy
}
}Start both Keepalived services, verify which node holds the virtual IP, and test failover by stopping HAProxy on the MASTER; the BACKUP will acquire the IP and continue serving traffic.
Overall, the guide provides a complete workflow—from understanding HAProxy’s capabilities, through installation, configuration for both L7 and L4 scenarios, logging, monitoring, to building a resilient HA setup with Keepalived.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.