Mastering HAProxy & Keepalived: Build a High‑Availability Load Balancer with VRRP
This guide explains HAProxy’s role as a high‑performance load balancer, compares its features with alternatives, details common algorithms, introduces Keepalived’s VRRP‑based high‑availability clustering, and provides step‑by‑step configuration commands for setting up a master‑backup HAProxy environment with monitoring and failover scripts.
HAProxy and Keepalived VRRP Introduction
HAProxy is a high‑performance load‑balancing software that operates at layer 7 (HTTP) and can also handle layer 4 (TCP) traffic. Compared with Apache, HAProxy is more specialized for load balancing and is widely used in production environments.
HAProxy Overview
Because HAProxy focuses solely on load balancing, it often outperforms general‑purpose web servers like Nginx in this specific task.
HAProxy Features
Key advantages of HAProxy over alternatives such as LVS and Nginx include support for both TCP and HTTP load balancing, around eight balancing algorithms (especially rich in HTTP mode), excellent single‑process performance, a powerful real‑time monitoring UI, and flexible ACL capabilities.
HAProxy Algorithms
1. roundrobin : weight‑based round‑robin, dynamic weight adjustment at runtime, ideal when server processing times are evenly distributed. 2. static‑rr : similar to roundrobin but static; weight changes do not take effect until restart. 3. leastconn : directs new connections to the server with the fewest active connections.
What is Keepalived
Keepalived provides high‑availability clustering by preventing single‑point failures using the VRRP (Virtual Router Redundancy Protocol) protocol.
Keepalived Working Principle
VRRP creates a virtual router group with one master and multiple backup nodes. The master holds a virtual IP (VIP) that clients use as the default gateway. It periodically sends multicast advertisements; if a backup does not receive these, it assumes the master has failed and promotes itself based on priority, ensuring continuous availability.
Project Preparation
Set up four virtual machines: two HAProxy proxy servers (one master, one backup) and two real web servers (running Nginx) for testing. Install Keepalived on the proxy servers to manage a shared VIP, then configure Nginx load balancing across the real servers.
# Example /etc/hosts entries
127.0.0.1 localhost
192.168.13.128 master
192.168.13.129 backup
192.168.13.133 real-server1
192.168.13.137 real-server2nginx Installation
On both real servers, disable firewalld and SELinux, add the official Nginx repository, and install Nginx.
# Disable firewall and SELinux
systemctl stop firewalld && setenforce 0
# Add Nginx repo
cat > /etc/yum.repos.d/nginx.repo <<EOF
[name]
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
EOF
# Install Nginx
yum -y install yum-utils
yum -y install nginx
systemctl start nginx
# Create a simple index page
echo "this is first real-server" > /usr/share/nginx/html/index.htmlHAProxy Scheduler Configuration (Master/Backup)
# Install HAProxy
yum -y install haproxy
# Backup original config
cp -rf /etc/haproxy/haproxy.cfg{,.bak}
# Minimal haproxy.cfg
global
log 127.0.0.1 local2 info
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
nbproc 1
defaults
mode http
log global
retries 3
option redispatch
maxconn 4000
contimeout 5000
clitimeout 50000
srvtimeout 50000
listen stats
bind *:81
stats enable
stats uri /haproxy
stats auth yjssjm:123
frontend web
mode http
bind *:80
option httplog
acl html url_reg -i \.html$
use_backend httpservers if html
default_backend httpservers
backend httpservers
balance roundrobin
server http1 192.168.13.133:80 maxconn 2000 weight 1 check inter 1s rise 2 fall 2
server http2 192.168.13.137:80 maxconn 2000 weight 1 check inter 1s rise 2 fall 2Keepalived HA Scheduler (Both Nodes)
Master node configuration (router_id directory1).
global_defs {
router_id directory1
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 80
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.13.144/24
}
}Backup node configuration (router_id directory2).
global_defs {
router_id directory2
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
nopreempt
virtual_router_id 80
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.13.144/24
}
}Testing and Monitoring
Start Keepalived on both nodes ( systemctl start keepalived) and enable it at boot. Access http://192.168.13.144:81/haproxy to view HAProxy statistics, which display queue lengths, request/connection errors, and server status (UP/DOWN, weight, last check).
High Availability with Scripts
To ensure VIP failover when HAProxy itself fails, add a health‑check script that stops Keepalived if the local HAProxy service is unreachable.
# /etc/keepalived/check_haproxy_status.sh
#!/bin/bash
/usr/bin/curl -I http://localhost &>/dev/null
if [ $? -ne 0 ]; then
systemctl stop keepalived
fiMake the script executable ( chmod +x /etc/keepalived/check_haproxy_status.sh) and reference it in keepalived.conf:
vrrp_script check_haproxy {
script "/etc/keepalived/check_haproxy_status.sh"
interval 5
}
vrrp_instance VI_1 {
...
track_script { check_haproxy }
}Logging Configuration
Enable UDP syslog reception for HAProxy logs by editing /etc/rsyslog.conf:
$ModLoad imudp
$UDPServerRun 514
local2.* /var/log/haproxy.logRestart rsyslog and HAProxy, then monitor logs with tail -f /var/log/haproxy.log.
Original article: https://www.jianshu.com/p/1fab38472c04 Author: 明_96af
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
