Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 25 min read

Keepalived + HAProxy/Nginx HA Setup: VIP Failover, Split-Brain Prevention & Drills

This article details building a high-availability load balancer using Keepalived VRRP with HAProxy/Nginx, covering VIP failover mechanics, split-brain causes and prevention via unicast peers and dual-network heartbeats, health check scripting, failover drill procedures with acceptance criteria, and a production checklist for reliable deployment.

1. Production Pain Points and Business Scenario

Two HAProxy/Nginx load balancer nodes experienced two critical failures: (1) VIP did not drift to the backup when the master failed, causing nearly two minutes of service interruption; (2) both nodes simultaneously believed they were Master, each holding the same VIP, leading to ARP conflicts, random client request routing, and data consistency corruption — a classic split-brain scenario.

This article addresses three concrete problems:

Use Keepalived (VRRP) to provide VIP high availability for HAProxy/Nginx, enabling automatic failover.

Identify and prevent common split-brain triggers: network partition, missing vrrp_strict configuration, single heartbeat path.

Provide a standard failover drill process with acceptance criteria, not just "configured and assumed working."

Assumption: Both nodes reside in the same LAN/broadcast domain (VRRP relies on multicast/broadcast). Cross-AZ or cross-data-center VIP drift requires additional network-layer support (e.g., cloud provider elastic IPs/load balancers) and is outside this article's scope.

2. Core Principles and Architecture Breakdown

2.1 VRRP and VIP Drift Mechanism

[Master Node]                          [Backup Node]
  Holds VIP                              Does not hold VIP
     |                                        |
     +----- Periodic VRRP Advertisements --->+
     |          (advert_int interval)        |
     |                                        |
     |  If Backup receives no advertisement  |
     |  within (master_down_interval) ------->|  Deems Master failed
     |                                        |  Transitions to Master
     |                                        |  Sends Gratuitous ARP
     |                                        |  Broadcasts VIP-MAC binding
     |                                        |  Switches/other devices update ARP cache
     |                                        |  Subsequent traffic forwards to new Master

Keepalived uses VRRP: nodes form a VRRP instance, elect a Master by priority. Master holds the VIP and sends periodic multicast/broadcast advertisements. Backup nodes listen; upon timeout, they trigger election and take over the VIP. The VIP "drift" is essentially the new Master sending a Gratuitous ARP to update ARP caches across the LAN, changing the MAC associated with the VIP — not moving the IP between systems.

2.2 Split-Brain Triggers and Prevention Principles

Split-brain typically arises from these combined conditions:

Network partition (heartbeat link down, but both nodes reachable externally): Both nodes think the other is dead, each promotes to Master, both hold VIP.

vrrp_strict not enabled and config has gaps: Keepalived validates config less strictly, allowing inconsistent states in edge cases.

Relying on a single NIC / single heartbeat path: NIC failure cuts inter-node communication while business network may stay up, creating "healthy islands."

No unicast_peer configured, relying on multicast; network devices mishandle multicast: Some cloud environments / network gear have limited multicast support or filter it, causing advertisement loss.

Core prevention strategy: Decouple "VRRP heartbeat health" from "business network health" as much as possible, and use arbitration mechanisms or dual heartbeat paths to reduce misjudgment from single-link failures. Common practices: dual-NIC heartbeats (one business, one dedicated heartbeat), configure unicast_peer to avoid multicast limitations, add external arbitration (e.g., check if node can reach a third-party gateway).

3. Experimental Baseline and Prerequisites

OS: CentOS 7.9 / Ubuntu 22.04 LTS — Kernel must support VRRP multicast/raw sockets.

Keepalived: 2.2.x / 2.3.x series — Official: https://www.keepalived.org/download.html; syntax differs across major versions.

HAProxy: 2.8.x LTS series — Official: http://www.haproxy.org/#down

Nginx: 1.24.x / 1.26.x series — If using Nginx as LB, choose one; config approach same. Article uses HAProxy as primary example.

Hardware/Network: Two nodes same broadcast domain, NICs ≥ 2 (business + heartbeat separation, production recommended) — Cross-broadcast-domain VRRP needs extra network support; verify actual topology.

Kernel Parameter: net.ipv4.ip_nonlocal_bind=1 — Allows HAProxy/Nginx to bind VIP before it exists locally, avoiding startup failure on backup nodes.

Prerequisite check commands:

# Verify inter-node connectivity (heartbeat link)
ping -c 3 <PEER_IP>

# Verify kernel parameter
sysctl net.ipv4.ip_nonlocal_bind

# Verify VIP not currently in use
ip addr show | grep <VIP>

4. Standardized Deployment and Core Implementation

4.1 Installation and Base Configuration (Both Nodes, Only priority and state Differ)

yum install -y keepalived   # or apt install -y keepalived
sysctl -w net.ipv4.ip_nonlocal_bind=1
echo "net.ipv4.ip_nonlocal_bind=1" >> /etc/sysctl.conf

Master Node /etc/keepalived/keepalived.conf:

vrrp_script chk_haproxy {
    script "/etc/keepalived/check_haproxy.sh"
    interval 2
    weight -20
    fall 2
    rise 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 150
    advert_int 1
    unicast_src_ip <MASTER_IP>
    unicast_peer {
        <BACKUP_IP>
    }
    authentication {
        auth_type PASS
        auth_pass <STRONG_RANDOM_PASSWORD>
    }
    virtual_ipaddress {
        <VIP>/24 dev eth0
    }
    track_script {
        chk_haproxy
    }
}

Backup Node : Same except state BACKUP, priority 100, unicast_src_ip <BACKUP_IP>, unicast_peer { <MASTER_IP> }. virtual_router_id, auth_pass, virtual_ipaddress must match exactly; otherwise nodes won't recognize each other as same VRRP instance.

Health check script /etc/keepalived/check_haproxy.sh:

#!/bin/bash
# Check HAProxy process and listening port; any failure returns non-zero, triggering demotion
if ! systemctl is-active --quiet haproxy; then
    exit 1
fi
if ! ss -lnt | grep -q ':80\b'; then
    exit 1
fi
exit 0
chmod +x /etc/keepalived/check_haproxy.sh

Four-Dimensional Configuration Breakdown (Keepalived Core Parameters)

virtual_router_id : No default; both nodes in same VRRP instance must match, and must not conflict with other VRRP instances in same segment (range 0-255). Mechanism: Distinguishes different VRRP groups in same network, participates in election. Misconfiguration consequence: Conflict with other VRRP instances causes unrelated clusters to interfere with each other's elections.

unicast_peer : Default unset (uses multicast); production recommends explicit unicast. Mechanism: Specifies target peer IP for heartbeat advertisements, switches to unicast transport. Misconfiguration consequence: Without it, relies on multicast; some cloud networks / security groups filter multicast, nodes never sense each other, both may become Master.

priority : Default 100; Master should be higher (e.g., 150 vs 100). Mechanism: Determines initial election result and role preference after failure recovery. Misconfiguration consequence: Equal priorities on both nodes lead to undefined initial behavior and unpredictable failback order.

track_script / weight : Default: no business process tracking. Mechanism: Periodically runs health check script; on failure, adjusts priority by weight, triggering failover. Misconfiguration consequence: Without it, Keepalived only senses VRRP protocol heartbeats; if HAProxy/Nginx crashes but host stays up, VIP won't drift, causing "false healthy" state.

About vrrp_strict : Recommended enabled in production (place in global global_defs section). It enforces stricter VRRP compliance checks (e.g., requires virtual_ipaddress to start). Different Keepalived versions behave differently when checks fail; consult the specific version's official docs — this article does not assume exact error messages. systemctl enable --now keepalived Expected Output (Sample, Not Real Benchmark):

journalctl -u keepalived -n 20 --no-pager
Keepalived_vrrp[xxxx]: VRRP_Instance(VI_1) Transition to MASTER STATE
# <- Key field: Transition to MASTER STATE, indicates node elected Master
Keepalived_vrrp[xxxx]: VRRP_Instance(VI_1) Entering MASTER STATE
# <- After entering Master state, VIP should be bound
ip addr show eth0 | grep <VIP>
# inet <VIP>/24 ...   # <- VIP appears on Master NIC, binding successful

4.2 HAProxy Base Configuration (Identical on Both Nodes, No VIP-Specific Content)

# /etc/haproxy/haproxy.cfg snippet
frontend fe_http
    bind <VIP>:80
    default_backend be_app

backend be_app
    balance roundrobin
    option httpchk GET /healthz
    server app1 <APP1_IP>:8080 check
    server app2 <APP2_IP>:8080 check

Key Point: bind <VIP>:80 requires the process to start listening even when VIP is not present on the local NIC. This is exactly why net.ipv4.ip_nonlocal_bind=1 is needed — otherwise the Backup node's HAProxy would fail to start during the period it doesn't hold the VIP, meaning HAProxy wouldn't be running when a real failover occurs.

5. Functional Verification and Acceptance

Static Validation (No Production Traffic Impact):

# Config syntax check; only catches syntax errors, not logic correctness
haproxy -c -f /etc/haproxy/haproxy.cfg

Failover Drill (Run in Staging First; Impact: VIP Briefly Unreachable, Business Connections May See Seconds of Reconnect):

# Step 1: Record current Master and VIP location
ip addr show | grep <VIP>

# Step 2: Simulate process failure on current Master (verify in non-prod first)
systemctl stop haproxy

# Step 3: Observe Backup detecting anomaly and taking over within (fall * interval) seconds
# With track_script fall=2, interval=2, expect ~4 seconds to trigger demotion
journalctl -u keepalived -f   # On Backup node

# Step 4: Confirm VIP drifted to Backup
ip addr show | grep <VIP>

# Step 5: Restore original Master's haproxy, observe role failback behavior
# Under priority config, original Master will preempt Master role again (VRRP default).
# If preemption undesired, evaluate nopreempt (requires preempt_delay and understanding impact on recovery semantics).
systemctl start haproxy

Acceptance Metrics:

VIP Switch Time: Compare Step 2 execution time with Step 4 VIP arrival confirmation. Measured RTO basis; must derive from advert_int / fall / rise config, not guesswork.

Request Success Rate During Switch: Continuous probe/load test against VIP, count failures in switch window. Must provide actual probe script and real measurements; no fabricated numbers.

ARP Convergence: On another host in same segment: arp -n | grep <VIP>. Confirm Gratuitous ARP received, MAC updated to new Master.

Lightweight Continuous Probe Script (for observing availability during switch window; run only in test or after production impact assessment):

while true; do
  code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 1 http://<VIP>/healthz)
  echo "$(date +%H:%M:%S) ${code}"
  sleep 0.5
done

6. Production Pitfalls and Troubleshooting Handbook

[Symptom / Typical Log] Both nodes in MASTER state, ip addr shows VIP on both.

[Root Cause Commands]

# On each node, verify VRRP heartbeat link connectivity
ping -c 3 <PEER_IP>
tcpdump -i eth0 vrrp -c 5

[Standard Fix] Typical split-brain: confirm heartbeat network link broken; after network repair, nodes re-elect via priority. Long-term prevention: configure dedicated heartbeat NIC or unicast_peer to avoid single-point dependency on shared network.

[Symptom / Typical Log] Backup node journalctl shows no VRRP logs; nodes unaware of each other.

[Root Cause Commands]

systemctl status keepalived
cat /etc/keepalived/keepalived.conf | grep -E "unicast_peer|interface"
firewall-cmd --list-all   # Or check security group/iptables for VRRP (IP protocol 112) / multicast allowance

[Standard Fix] Verify interface matches correct heartbeat NIC; ensure firewall/security group allows VRRP (IP protocol 112) or multicast; in cloud, switch to unicast_peer uniformly.

[Symptom / Typical Log] VIP drifted to Backup but business still fails.

[Root Cause Commands]

ss -lnt | grep :80
curl -v http://127.0.0.1/healthz   # On Backup node locally

[Standard Fix] Confirm HAProxy/Nginx process alive on Backup; check if net.ipv4.ip_nonlocal_bind missing caused startup failure; verify track_script correctly linked to process health.

[Symptom / Typical Log] Original Master recovers and preempts Master role, causing brief double-flap.

[Root Cause Commands] Compare timestamps of both switches with priority config.

[Standard Fix] This is VRRP default preemptive behavior. If business tolerates switch count less than switch speed, evaluate nopreempt (requires preempt_delay and understanding impact on recovery semantics). Decide based on SLA; do not enable without assessment.

[Symptom / Typical Log] track_script health check script exits abnormally (e.g., script bug), causing node misjudged unhealthy, triggering meaningless frequent switches.

[Root Cause Commands]

bash -x /etc/keepalived/check_haproxy.sh; echo "exit code: $?"

[Standard Fix] Verify script logic and exit codes (non-zero = failure). Ensure internal commands ( systemctl, ss) paths and permissions are executable under Keepalived's runtime user to avoid false positives from permission issues.

7. Production Go-Live Checklist

[ ] Both nodes: virtual_router_id, auth_pass, virtual_ipaddress identical; only state / priority / unicast_src_ip differ by role.

[ ] Switched to unicast_peer instead of multicast, or confirmed network supports multicast/VRRP (IP protocol 112) with proper allow policies.

[ ] net.ipv4.ip_nonlocal_bind=1 persisted on both nodes (written to sysctl.conf, not just temporary).

[ ] track_script configured to monitor HAProxy/Nginx process health, not just VRRP protocol heartbeats.

[ ] Completed at least one real failover drill, recorded switch time and request failures; not just "config looks correct."

[ ] Evaluated preemptive failback ( nopreempt) impact on business, documented decision.

[ ] Heartbeat path considers single-point failure (recommend dedicated NIC or at least separate from business traffic path) to avoid business congestion misjudged as node failure.

[ ] VIP switch events integrated into monitoring/alerting (via Keepalived logs or track_script state changes) for later audit of abnormal switch frequency.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

high availabilityfailoverVRRPVIPhealth checksHAProxyKeepalivedsplit-brain

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion