Skip to content

Deploying a keepalived VRRP pair for TCP/IP failover on a non-Kubernetes service

Full installer for an active/passive VIP using keepalived on two Linux nodes — VRRP config, custom healthcheck script, and verification.

The application is one TCP-speaking process — a Postal MTA, a Mosquitto broker, a self-hosted SFTP, a Postgres primary running without orchestration — and it doesn’t speak HTTP, so no L7 load balancer helps. The product manager doesn’t care that it’s “just one process”; they care that when the VM behind that IP reboots, customers see a connection reset for the next ten minutes. The pragmatic answer is not Kubernetes. The pragmatic answer is two identical Linux boxes, a floating IP, and keepalived running VRRP between them — five minutes of configuration, no consensus store, no controller, no upgrade treadmill. The thing that distinguishes a serious keepalived deployment from a hobby one is the healthcheck: VRRP by default only proves the node is alive, not the service, and you spend a year very confidently failing over to a peer where the actual daemon is dead. The fix is a custom vrrp_script that checks the right thing on the right port.

What’s happening

VRRP (Virtual Router Redundancy Protocol, RFC 5798) lets two or more nodes share a single IP address on a LAN. One node is the master and replies to ARP for the VIP; the others are backups and stay quiet. They communicate via multicast (default 224.0.0.18) and exchange tiny “I am alive at priority X” frames every advertisement interval (default 1 second). If the master stops advertising, the highest-priority backup takes over — sends gratuitous ARP, binds the VIP — and clients reconnecting hit the new master within a few seconds. keepalived implements VRRP and adds three things you actually want in production: vrrp_script, a periodic shell command whose exit code (0 = healthy, non-zero = unhealthy) feeds into the priority; vrrp_instance with a track_script, so an unhealthy service deliberately lowers the node’s priority and forces failover; and notify scripts, executed when this node transitions to master/backup/fault, for things like firing a webhook, kicking a downstream service, or refreshing a connection pool. The crucial subtlety is that the healthcheck must verify the actual service is serving on the port the VIP exposes — not just that the daemon’s PID exists. A Postgres process that’s stuck in a checkpoint, an Nginx that has lost its upstream — those daemons are “running” but the port isn’t accepting useful connections. Always check the port and ideally do a tiny application-level probe.

How to verify

On the master, the VIP should be bound:

ip -4 addr show | grep -F "10.10.0.60/32"
#   inet 10.10.0.60/32 scope global secondary ens18

On the backup, it should NOT be bound — only its node IP:

ip -4 addr show ens18 | grep -F inet
#   inet 10.10.0.21/24 ...
# (no 10.10.0.60 here — good)

VRRP state via keepalived:

keepalived -v
# Keepalived v2.2.8 (10/15,2022)

cat /var/run/keepalived.vrrp.stats   # if dump-stats enabled
# Or send the data dump signal:
killall -USR1 keepalived
cat /tmp/keepalived.data | grep -E "State|Priority|Effective priority"
#  State = MASTER
#  Priority = 110
#  Effective priority = 110

From a client on the same LAN, watch failover live: hold an open TCP session and kill the daemon on the master.

# On a workstation, hold a connection
nc 10.10.0.60 5432

# On the master, stop the service
sudo systemctl stop postgresql
# Within ~3 seconds the backup takes over;
# the existing TCP session resets; new connections to 10.10.0.60 succeed against the new master.

arping from the LAN should resolve the VIP to the master’s MAC, then to the backup’s MAC after failover:

arping -c 5 10.10.0.60
# 60 bytes from aa:bb:cc:dd:ee:01 (10.10.0.60): index=0 time=0.412 msec
# ... after stop ...
# 60 bytes from aa:bb:cc:dd:ee:02 (10.10.0.60): index=3 time=0.387 msec

The fix

The installer below stands up a two-node keepalived pair for a generic TCP service on port 5432 (Postgres in the example — substitute whatever port your service uses). One node has priority 110 (preferred master), the other priority 100; the healthcheck script reduces priority by 20 when the service is unhealthy, which forces an orderly failover. Run the same script on both nodes after editing the per-node variables.

#!/usr/bin/env bash
set -euo pipefail

### keepalived VRRP active/passive installer for a TCP service
### Run on both nodes after editing the per-node variables.

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
NODE_NAME="lb01"                   # lb01 / lb02
NODE_PRIORITY="110"                # 110 on master, 100 on backup
NODE_INTERFACE="ens18"
NODE_PEER_IP="10.10.0.21"          # IP of the OTHER node
VRRP_VIP="10.10.0.60"              # the floating IP
VRRP_ID="51"                       # any 1-255 unique to this VIP on the L2
VRRP_AUTH_PASS="CHANGE_ME_VRRPPASS"
SERVICE_PORT="5432"
SERVICE_NAME="postgresql"          # systemd unit name (used by notify scripts)
NOTIFY_WEBHOOK=""                  # optional: a URL to POST state changes to
# =====================

echo
echo "========================================"
echo "keepalived ${NODE_NAME} priority ${NODE_PRIORITY}"
echo "VIP ${VRRP_VIP} on ${NODE_INTERFACE}"
echo "========================================"
echo

echo "==> Installing keepalived + helpers"
if command -v dnf >/dev/null 2>&1; then
  dnf -y install keepalived nmap-ncat curl jq
elif command -v apt-get >/dev/null 2>&1; then
  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get -y install keepalived ncat curl jq
else
  echo "Unsupported package manager."
  exit 1
fi

echo "==> Allowing keepalived to bind the VIP (sysctl)"
cat > /etc/sysctl.d/99-keepalived.conf <<'SYSCTL'
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 1
SYSCTL
sysctl --system

echo "==> Writing healthcheck script"
mkdir -p /etc/keepalived/scripts
cat > /etc/keepalived/scripts/check_service.sh <<EOF
#!/bin/bash
# Returns 0 if the local service is accepting connections, 1 otherwise.
# The TCP-level probe catches stuck processes; replace with a richer probe
# (e.g. psql -c 'SELECT 1', mysqladmin ping, mqtt publish) for application-level health.
set -e
timeout 2 bash -c '</dev/tcp/127.0.0.1/${SERVICE_PORT}' >/dev/null 2>&1
EOF
chmod 755 /etc/keepalived/scripts/check_service.sh

echo "==> Writing notify script"
cat > /etc/keepalived/scripts/notify.sh <<EOF
#!/bin/bash
# Called by keepalived on every state transition:
#   \$1 = instance type ("INSTANCE" or "GROUP")
#   \$2 = instance/group name
#   \$3 = new state ("MASTER" | "BACKUP" | "FAULT" | "STOP")
#   \$4 = priority
STATE="\$3"
TS=\$(date -Is)
logger -t keepalived-notify "Node ${NODE_NAME} -> \${STATE} at \${TS}"

if [[ -n "${NOTIFY_WEBHOOK}" ]]; then
  curl -fsS -m 5 -X POST -H 'Content-Type: application/json' \\
    -d "{\\"node\\":\\"${NODE_NAME}\\",\\"state\\":\\"\${STATE}\\",\\"ts\\":\\"\${TS}\\"}" \\
    "${NOTIFY_WEBHOOK}" || true
fi

# Optional: kick a downstream service on transition.
# case "\${STATE}" in
#   MASTER) systemctl start some-write-only-service ;;
#   BACKUP|FAULT) systemctl stop some-write-only-service ;;
# esac
EOF
chmod 755 /etc/keepalived/scripts/notify.sh

echo "==> Writing keepalived.conf"
cat > /etc/keepalived/keepalived.conf <<EOF
! Configuration for ${NODE_NAME}
global_defs {
  router_id ${NODE_NAME}
  enable_script_security
  script_user root
}

vrrp_script chk_service {
  script "/etc/keepalived/scripts/check_service.sh"
  interval 2
  timeout 2
  rise 2
  fall 2
  weight -20            # reduce effective priority by 20 if unhealthy
}

vrrp_instance VI_${VRRP_ID} {
  state BACKUP          # always start BACKUP; let priority decide
  interface ${NODE_INTERFACE}
  virtual_router_id ${VRRP_ID}
  priority ${NODE_PRIORITY}
  advert_int 1
  unicast_src_ip $(ip -4 addr show ${NODE_INTERFACE} | awk '/inet /{print \$2}' | cut -d/ -f1 | head -1)
  unicast_peer {
    ${NODE_PEER_IP}
  }
  authentication {
    auth_type PASS
    auth_pass ${VRRP_AUTH_PASS}
  }
  virtual_ipaddress {
    ${VRRP_VIP}/32 dev ${NODE_INTERFACE} label ${NODE_INTERFACE}:vip
  }
  track_script {
    chk_service
  }
  notify "/etc/keepalived/scripts/notify.sh"
  garp_master_delay 1
  garp_master_refresh 60
  preempt
  preempt_delay 5
}
EOF

echo "==> Validating config"
keepalived --config-test || {
  echo "keepalived config did not parse. Aborting."
  exit 1
}

echo "==> Enabling firewall rule for VRRP multicast (if firewalld)"
if systemctl is-active --quiet firewalld; then
  firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 \
    -p vrrp -j ACCEPT >/dev/null 2>&1 || true
  firewall-cmd --permanent --direct --add-rule ipv4 filter OUTPUT 0 \
    -p vrrp -j ACCEPT >/dev/null 2>&1 || true
  firewall-cmd --reload >/dev/null 2>&1 || true
fi

echo "==> Starting keepalived"
systemctl enable --now keepalived
sleep 3

echo
echo "========================================"
echo "DONE on ${NODE_NAME}"
echo "========================================"
echo
echo "Service state:"
systemctl status keepalived --no-pager | head -20 || true
echo
echo "Current VIP binding (this node):"
ip -4 addr show "${NODE_INTERFACE}" | grep -F "${VRRP_VIP}/" || echo "  VIP not bound on this node (this is correct on the backup)."
echo
echo "Dump state:"
echo "  killall -USR1 keepalived ; cat /tmp/keepalived.data"
echo
echo "After running on BOTH nodes, simulate a failure:"
echo "  systemctl stop ${SERVICE_NAME}  # on the current master"
echo "  watch -n0.5 'ip -4 addr show ${NODE_INTERFACE} | grep ${VRRP_VIP}'"
echo
echo "Recovery: restart ${SERVICE_NAME} on the failed node; with 'preempt' set,"
echo "if priorities differ the higher-priority node will retake the VIP after preempt_delay."

A few hard-earned tips. Always run keepalived --config-test before reload — an invalid config silently keeps the old config running and you’ll be debugging stale state. Don’t run keepalived on more than two nodes in a flat pair (use a third node only as an explicit state MASTER with priority 100 and an arbiter pattern); three “peer” nodes with the default config can flap. Set enable_script_security and script_user root — without those, keepalived 2.x silently disables your healthcheck because it ran as a non-root user with a non-secured path. If you have firewalld or nftables, open VRRP protocol 112 between the two unicast peers; on a default RHEL/AlmaLinux 9 box firewalld will silently drop multicast and you’ll spend an afternoon wondering why both nodes think they’re master. Finally, the preempt_delay 5 is important: it stops the master flapping when a brief network blip drops its advertisement; without preempt_delay, a 500ms network event can cost you a forced failover.

A keepalived pair is the right call when one well-understood service needs a floating IP. When the dependency graph gets longer — one VIP, three apps behind it, a database tier and a queue and a cache — you outgrow it. Our Cloud Compute team builds those bigger HA stacks under Managed Cloud Ops with proper consensus, observability, and runbooks attached — book a network-design review if you want a second opinion before you tile your topology with VIPs.