You build a two-node HAProxy cluster behind a floating VIP. The first failover test passes — pull the cable, keepalived migrates the VIP, traffic continues. Six months later a routine kernel upgrade reboots the primary, the VIP goes to the secondary, and stays there forever because nobody noticed unicast_peer was never configured, the cluster ran on multicast that the cloud network silently dropped after the maintenance window, and priority on both nodes was set to 100. The “HA pair” had been a single node for months.
What’s happening
A production HAProxy + keepalived deployment needs more than the package install. VRRP must use unicast_peer (or a real multicast-capable network — most cloud VPCs are not), priority must differ on the two nodes, and vrrp_script chk_haproxy must demote the primary when HAProxy itself is down (not just when the node is). HAProxy needs its admin stats socket on a Unix socket — never on a TCP port open to the world — with level admin only for the local management user. Backend health checks must use a real option httpchk GET /healthz HTTP/1.1 rather than a TCP probe that succeeds against any listener. timeout connect, timeout client, timeout server, and timeout queue must be set explicitly (HAProxy defaults to one-second connect and no queue ceiling). And every config change must go through haproxy -c -f before systemctl reload haproxy — there is no “validate on apply” path; a syntax error takes down the listener.
How to verify
After install, on each node:
ss -lntp | grep -E ':(80|443|8404)\b'
# node-a: 10.0.0.10:80, 10.0.0.10:443, 127.0.0.1:8404
# node-b: 10.0.0.11:80, 10.0.0.11:443, 127.0.0.1:8404
# VIP 10.0.0.50 should appear on the master only:
ip -4 addr show | grep '10.0.0.50'
Confirm keepalived sees its peer and the right priority is master:
journalctl -u keepalived -n 50 --no-pager | grep -iE 'state|entering|backup|master'
Validate HAProxy syntax before any reload:
haproxy -c -f /etc/haproxy/haproxy.cfg
Hit the stats socket from the local node to confirm it’s a Unix socket and not a TCP listener:
echo "show info" | sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock | head -20
ss -lntp | grep 9000 || echo "no TCP stats — good"
If the VIP is on both nodes, both keepalived processes report MASTER, or haproxy -c -f returns errors, the cluster is not safe to reboot.
The fix
Save the script below as /root/setup-haproxy-keepalived-ubuntu22.sh on each node, then run it. It performs the full installer flow on a fresh Ubuntu 22.04 VM: base update, installs HAProxy 2.8 and keepalived from the HAProxy PPA, hardens SSH while keeping the root key, configures ufw to allow 22/80/443 plus VRRP multicast on the LAN, applies sysctl tuning relevant to a high-concurrency L4/L7 load balancer, writes an haproxy.cfg skeleton (one HTTP frontend with HSTS, one TCP frontend, two backends with HTTP health checks, stats socket on /run/haproxy/admin.sock), writes a keepalived.conf with unicast_peer, a chk_haproxy vrrp_script, and the right priority/state per node, raises LimitNOFILE to 200000 in a systemd override, validates HAProxy syntax, and waits for both listeners on the local node before continuing.
#!/usr/bin/env bash
set -euo pipefail
### Ubuntu 22.04 HAProxy 2.8 + keepalived HA installer
### Run on each node; export NODE_ROLE=master|backup and peer/VIP details first
### Stats socket on /run/haproxy/admin.sock (no TCP stats listener)
### No local backups; assumes VM-level backup
### Reboot remains manual
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
: "${NODE_ROLE:?Set NODE_ROLE=master or NODE_ROLE=backup}"
: "${NODE_IFACE:?Set NODE_IFACE=eth0 (the LAN interface)}"
: "${NODE_IP:?Set NODE_IP=10.0.0.10 (this node)}"
: "${PEER_IP:?Set PEER_IP=10.0.0.11 (the other node)}"
: "${VIP_CIDR:?Set VIP_CIDR=10.0.0.50/24 (floating VIP)}"
: "${VRRP_AUTH_PASS:?Set VRRP_AUTH_PASS=... (8-char shared secret)}"
if [[ "${NODE_ROLE}" == "master" ]]; then
STATE="MASTER"
PRIORITY=120
else
STATE="BACKUP"
PRIORITY=100
fi
echo
echo "========================================"
echo "HAProxy 2.8 + keepalived Setup (${NODE_ROLE})"
echo "========================================"
echo
echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade
echo "==> Installing base packages"
apt-get -y install \
curl \
ca-certificates \
gnupg \
software-properties-common \
ufw \
fail2ban \
unattended-upgrades \
chrony \
lsof \
socat \
net-tools \
jq
echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true
echo "==> Applying sysctl tuning for L4/L7 LB"
cat > /etc/sysctl.d/99-haproxy.conf <<'SYSCTL'
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 500000
net.ipv4.tcp_max_syn_backlog = 32768
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_max_tw_buckets = 1440000
net.ipv4.tcp_mem = 786432 1697152 1945728
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
fs.file-max = 4194304
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system
echo "==> Setting file limits"
cat > /etc/security/limits.d/99-haproxy.conf <<'LIMITS'
* soft nofile 200000
* hard nofile 200000
root soft nofile 200000
root hard nofile 200000
haproxy soft nofile 200000
haproxy hard nofile 200000
LIMITS
echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
local key="$1"
local value="$2"
if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
else
echo "${key} ${value}" >> /etc/ssh/sshd_config
fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4
sshd -t
systemctl restart ssh
echo "==> Configuring UFW (22/80/443 public, VRRP to peer only)"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow from "${PEER_IP}" to any port 112 proto any
ufw allow from "${PEER_IP}"
ufw --force enable
echo "==> Adding HAProxy 2.8 PPA"
add-apt-repository -y ppa:vbernat/haproxy-2.8
apt-get update
apt-get -y install haproxy=2.8.* keepalived
echo "==> Writing /etc/haproxy/haproxy.cfg"
mkdir -p /etc/haproxy /run/haproxy /var/log/haproxy
chown haproxy:haproxy /run/haproxy
cat > /etc/haproxy/haproxy.cfg <<'HAPROXY_CFG'
global
log /dev/log local0 info
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
stats timeout 30s
user haproxy
group haproxy
daemon
maxconn 200000
nbthread 4
cpu-map auto:1/1-4 0-3
# Strong TLS defaults
ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
log global
mode http
option httplog
option dontlognull
option http-server-close
option forwardfor
option redispatch
retries 3
timeout connect 5s
timeout client 60s
timeout server 60s
timeout queue 10s
timeout http-request 15s
timeout http-keep-alive 10s
# CommonLog-friendly capture for fail2ban
log-format "%ci:%cp [%t] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs %{+Q}r"
frontend http_in
bind *:80
http-request redirect scheme https code 301 unless { ssl_fc }
frontend https_in
bind *:443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1
http-request set-header X-Real-IP %[src]
http-request set-header X-Forwarded-Proto https
http-request set-var(txn.req_id) uuid()
http-request set-header X-Request-Id %[var(txn.req_id)]
http-response set-header X-Request-Id %[var(txn.req_id)]
http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains"
http-response set-header X-Content-Type-Options nosniff
http-response del-header Server
acl is_api path_beg /api/
use_backend be_api if is_api
default_backend be_web
backend be_web
balance roundrobin
option httpchk GET /healthz HTTP/1.1\r\nHost:\ healthcheck
http-check expect status 200
default-server inter 5s fall 3 rise 2 maxconn 1024
server web1 10.0.1.11:8080 check
server web2 10.0.1.12:8080 check
backend be_api
balance leastconn
option httpchk GET /api/healthz HTTP/1.1\r\nHost:\ healthcheck
http-check expect status 200
default-server inter 5s fall 3 rise 2 maxconn 512
server api1 10.0.1.21:9000 check
server api2 10.0.1.22:9000 check
HAPROXY_CFG
# Cert directory (one PEM per site; production fills these in)
mkdir -p /etc/haproxy/certs
chmod 750 /etc/haproxy/certs
chown haproxy:haproxy /etc/haproxy/certs
echo "==> Validating HAProxy config syntax"
haproxy -c -f /etc/haproxy/haproxy.cfg
echo "==> Writing /etc/keepalived/keepalived.conf"
VIP_ADDR_ONLY="${VIP_CIDR%/*}"
cat > /etc/keepalived/keepalived.conf <<KA_CONF
global_defs {
router_id ${NODE_ROLE^^}
enable_script_security
script_user root
}
vrrp_script chk_haproxy {
script "/usr/bin/pgrep -x haproxy"
interval 2
weight -30
fall 2
rise 2
}
vrrp_instance VI_EDGE {
state ${STATE}
interface ${NODE_IFACE}
virtual_router_id 51
priority ${PRIORITY}
advert_int 1
preempt_delay 30
unicast_src_ip ${NODE_IP}
unicast_peer {
${PEER_IP}
}
authentication {
auth_type PASS
auth_pass ${VRRP_AUTH_PASS}
}
virtual_ipaddress {
${VIP_CIDR} dev ${NODE_IFACE}
}
track_script {
chk_haproxy
}
notify_master "/usr/bin/logger keepalived: now MASTER (VIP ${VIP_ADDR_ONLY})"
notify_backup "/usr/bin/logger keepalived: now BACKUP (VIP ${VIP_ADDR_ONLY})"
notify_fault "/usr/bin/logger keepalived: FAULT"
}
KA_CONF
chmod 600 /etc/keepalived/keepalived.conf
echo "==> Setting systemd limits for HAProxy"
mkdir -p /etc/systemd/system/haproxy.service.d
cat > /etc/systemd/system/haproxy.service.d/override.conf <<'HA_OVERRIDE'
[Service]
LimitNOFILE=200000
LimitNPROC=16384
HA_OVERRIDE
systemctl daemon-reload
echo "==> Configuring fail2ban for HAProxy log"
mkdir -p /etc/fail2ban/filter.d /etc/fail2ban/jail.d
cat > /etc/fail2ban/filter.d/haproxy-status.conf <<'F2B_FILTER'
[Definition]
failregex = ^.*<HOST>:[0-9]+ .* (401|403|404|429) .*$
ignoreregex =
F2B_FILTER
cat > /etc/fail2ban/jail.d/haproxy.local <<'F2B_JAIL'
[haproxy-status]
enabled = true
filter = haproxy-status
logpath = /var/log/haproxy.log
maxretry = 50
findtime = 5m
bantime = 1h
F2B_JAIL
systemctl enable --now fail2ban
echo "==> Configuring unattended security upgrades"
dpkg-reconfigure -f noninteractive unattended-upgrades
echo "==> Enabling HAProxy and keepalived"
systemctl enable --now haproxy
systemctl restart haproxy
systemctl enable --now keepalived
systemctl restart keepalived
echo "==> Waiting for HAProxy listeners on :80 and :443"
for i in {1..30}; do
if ss -lntp | grep -q ':443' && ss -lntp | grep -q ':80'; then
break
fi
sleep 1
done
if ! ss -lntp | grep -q ':443'; then
echo "HAProxy did not bind :443"
systemctl status haproxy --no-pager -l || true
journalctl -u haproxy -n 120 --no-pager || true
exit 1
fi
echo
echo "========================================"
echo "DONE (${NODE_ROLE})"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443)\b' || true
echo
echo "Stats socket (Unix):"
echo "show info" | socat - UNIX-CONNECT:/run/haproxy/admin.sock | head -10 || true
echo
echo "Services:"
systemctl is-active haproxy keepalived fail2ban chrony ufw || true
echo
echo "VIP state on this node:"
ip -4 addr show "${NODE_IFACE}" | grep "${VIP_ADDR_ONLY}" || echo "VIP not on this node (BACKUP is correct on backup node)"
echo
echo "Keepalived state:"
journalctl -u keepalived -n 20 --no-pager || true
echo
echo "Next steps:"
echo " 1) Place per-site PEM files into /etc/haproxy/certs/ (combined cert+key, mode 600)"
echo " 2) systemctl reload haproxy"
echo " 3) Failover test: stop haproxy on master, watch journalctl -u keepalived on backup"
Make it executable and run it on each node (with the per-node env vars):
chmod 700 /root/setup-haproxy-keepalived-ubuntu22.sh
# On node-a (master):
export NODE_ROLE=master NODE_IFACE=eth0 NODE_IP=10.0.0.10 PEER_IP=10.0.0.11 \
VIP_CIDR=10.0.0.50/24 VRRP_AUTH_PASS=Sh4r3dV1p
/root/setup-haproxy-keepalived-ubuntu22.sh
# On node-b (backup):
export NODE_ROLE=backup NODE_IFACE=eth0 NODE_IP=10.0.0.11 PEER_IP=10.0.0.10 \
VIP_CIDR=10.0.0.50/24 VRRP_AUTH_PASS=Sh4r3dV1p
/root/setup-haproxy-keepalived-ubuntu22.sh
After both nodes are up, run a real failover test: systemctl stop haproxy on the master, watch journalctl -u keepalived -f on the backup, confirm the VIP migrates within a couple of seconds, then restart HAProxy and confirm preemption. Drop site PEM files into /etc/haproxy/certs/ (each file is the full chain plus the private key, mode 600), then systemctl reload haproxy. The script does not configure host-level backups — the assumption is the VM has snapshot/backup at the cloud layer.
When the HA pair fronts a regulated workload and you need on-call coverage with documented failover runbooks, that is exactly what Managed Cloud Ops ships — book a review.