Skip to content

nginx active-active pair with ucarp floating VIP and conntrack sync on AlmaLinux 9

Stand up a two-node nginx active-active edge with ucarp for VIP failover and conntrackd for connection state sync — sub-second failover, no upstream LB.

You have a pair of nginx nodes fronting an internal service and the only thing in front of them is DNS round-robin. A reboot for kernel patching means one of the records is dead for forty seconds while clients retry; long-lived connections get reset; some clients cache the dead IP for an extra five minutes because their resolver doesn’t honour your TTL. The fix is not “shorten the TTL.” It’s to put a single virtual IP in front of both nodes — a floating address that one node owns at a time, hands over in under a second on failure, and keeps active connections alive across the handover because conntrack state is replicated on both sides.

What’s happening

CARP (Common Address Redundancy Protocol) is the open implementation of the protocol VRRP cloned. ucarp is a userspace daemon that speaks CARP on a network interface: each node advertises a virtual address with a priority, the highest-priority advertiser owns the VIP, and if its advertisements stop the next-highest priority takes over. Failover is a couple of CARP intervals — typically under a second.

The CARP layer handles “which node has the address.” It does not handle “what about the connections that were in flight when the address moved.” That’s where conntrackd comes in: it replicates the kernel’s connection-tracking table from the active node to the standby over a dedicated link (or a UDP multicast group on the LAN), so when the VIP moves the new owner has every existing flow’s state and can keep serving without RST-ing the client. For nginx this matters most for long-lived connections — WebSockets, SSE, gRPC streams, HTTP/2 multiplexed traffic — where a fresh TCP handshake means the application notices.

Active-active is the second axis. The simplest model is master-backup: one node owns the VIP, the other is warm. That works, but wastes a node. Active-active uses two VIPs and assigns one to each node by priority — under normal operation each node owns one VIP and DNS round-robins between them, but when a node dies the surviving node grabs both VIPs and serves all traffic until its peer recovers. It needs more discipline (the surviving node must be sized to handle both pools at once and conntrackd must be running with the right group) but the steady-state capacity is doubled.

The third piece is the upstream story. Both nginx nodes must have an identical view of the upstream pool and the same TLS cert bundle. If the upstreams are themselves a pool of application servers, nginx talks to them by short DNS name (which both nodes resolve), or by static IP list kept in sync via your config-management tool of choice. The TLS bundle goes on disk on both nodes — same path, same contents — refreshed by certbot or your cert-management pipeline running on a schedule.

How to verify

After running the installer on both nodes, the VIPs should each be advertised by one node:

# On node-01 (priority master for VIP1, backup for VIP2)
ip -4 addr show dev eth0 | grep -E '10\.50\.0\.(100|101)'
# expect: 10.50.0.100  (VIP1)

# On node-02
ip -4 addr show dev eth0 | grep -E '10\.50\.0\.(100|101)'
# expect: 10.50.0.101  (VIP2)

conntrackd should report a sync peer:

conntrackd -s | grep -E 'External|Internal'
# External cache: peer sync OK, X entries
# Internal cache: kernel sync OK, Y entries

Simulate failure of node-01 and watch node-02 grab the second VIP:

# On node-01:
systemctl stop ucarp@vip1.service

# On node-02 within ~1s:
ip -4 addr show dev eth0 | grep '10.50.0.100'
# should now also show VIP1

Connections in flight should survive — open a long curl with --http2 to the VIP, fail the active node, and confirm no reset:

curl -v --http2 -o /dev/null https://10.50.0.100/long-stream &
PID=$!
ssh node-01 systemctl stop nginx ucarp@vip1
wait $PID
echo "exit=$?"   # 0 means the connection survived

The fix

Run the installer on both nodes. The variables at the top differ between them — NODE_ROLE, the priorities, and the peer IP. Two VIPs are configured: VIP1 is owned by node-01 in steady state, VIP2 by node-02; either node will grab both if the other drops out.

Save as /root/setup-nginx-active-active.sh:

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

### AlmaLinux 9 nginx + ucarp + conntrackd active-active pair installer
### Run on each of the two nodes after editing the variables below.

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

# === EDIT PER NODE ===
NODE_NAME="nginx-01"                # nginx-01 / nginx-02
NODE_IP="10.50.0.11"                # this node's real IP on the LAN
PEER_IP="10.50.0.12"                # the other node's real IP
IFACE="eth0"                        # LAN interface (carrier of VIPs)
VIP1="10.50.0.100"                  # nginx-01 owns this in steady state
VIP2="10.50.0.101"                  # nginx-02 owns this in steady state
VIP_NETMASK="24"
CARP_PASS_1="CHANGE_ME_CARP1"
CARP_PASS_2="CHANGE_ME_CARP2"
# Priorities: master=10 (lower wins ucarp election), backup=20.
# On nginx-01:  VIP1_ADVBASE=1, VIP1_ADVSKEW=10 / VIP2_ADVBASE=1, VIP2_ADVSKEW=20
# On nginx-02:  VIP1_ADVBASE=1, VIP1_ADVSKEW=20 / VIP2_ADVBASE=1, VIP2_ADVSKEW=10
if [[ "$NODE_NAME" == "nginx-01" ]]; then
  VIP1_ADVSKEW=10; VIP2_ADVSKEW=20
else
  VIP1_ADVSKEW=20; VIP2_ADVSKEW=10
fi
VIP1_ID=1; VIP2_ID=2
CONNTRACK_GROUP=3780                # arbitrary; same on both nodes
UPSTREAM_BACKENDS="10.50.1.10:8080 10.50.1.11:8080 10.50.1.12:8080"
# =====================

echo
echo "========================================"
echo "${NODE_NAME} (${NODE_IP}) on ${IFACE}"
echo "========================================"
echo

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y install curl wget jq lsof tcpdump net-tools bind-utils tar gzip \
  policycoreutils-python-utils fail2ban dnf-automatic chrony socat \
  iproute conntrack-tools ipset firewalld

systemctl enable --now chronyd

echo "==> SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart sshd

cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
DNFAUTO
systemctl enable --now dnf-automatic.timer

echo "==> Kernel tuning"
cat > /etc/sysctl.d/99-nginx-vip.conf <<'SYSCTL'
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.all.arp_ignore = 1
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 32768
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_keepalive_time = 60
net.ipv4.tcp_slow_start_after_idle = 0
net.netfilter.nf_conntrack_max = 1048576
net.netfilter.nf_conntrack_tcp_timeout_established = 86400
fs.file-max = 2097152
fs.nr_open = 2097152
vm.swappiness = 10
SYSCTL
modprobe nf_conntrack
sysctl --system

cat > /etc/security/limits.d/99-nginx.conf <<'LIMITS'
nginx soft nofile 1048576
nginx hard nofile 1048576
LIMITS

echo "==> Installing nginx + ucarp"
dnf -y install nginx ucarp

echo "==> nginx configuration"
mkdir -p /etc/nginx/conf.d /etc/nginx/upstreams /var/log/nginx /etc/nginx/tls
chown -R nginx:nginx /var/log/nginx

cat > /etc/nginx/nginx.conf <<'NGINX'
user nginx;
worker_processes auto;
worker_rlimit_nofile 1048576;
pid /run/nginx.pid;

events {
  worker_connections 65536;
  use epoll;
  multi_accept on;
}

http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  log_format json escape=json '{'
    '"ts":"$time_iso8601",'
    '"remote":"$remote_addr",'
    '"vip":"$server_addr",'
    '"req":"$request",'
    '"status":$status,'
    '"bytes":$body_bytes_sent,'
    '"rt":$request_time,'
    '"ut":"$upstream_response_time",'
    '"ua":"$http_user_agent"}';

  access_log /var/log/nginx/access.log json buffer=64k flush=2s;
  error_log /var/log/nginx/error.log warn;

  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  keepalive_requests 10000;
  reset_timedout_connection on;
  client_body_timeout 30s;
  client_header_timeout 30s;
  send_timeout 30s;

  proxy_http_version 1.1;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection $connection_upgrade;
  proxy_read_timeout 60s;
  proxy_send_timeout 60s;
  proxy_connect_timeout 5s;
  proxy_next_upstream error timeout http_502 http_503 http_504;
  proxy_next_upstream_tries 3;

  map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
  }

  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
  ssl_prefer_server_ciphers off;
  ssl_session_cache shared:SSL:50m;
  ssl_session_timeout 1d;
  ssl_session_tickets off;

  include /etc/nginx/upstreams/*.conf;
  include /etc/nginx/conf.d/*.conf;

  server {
    listen 127.0.0.1:9080;
    location = /nginx_status {
      stub_status;
      allow 127.0.0.1;
      deny all;
    }
  }
}
NGINX

UPSTREAM_LINES=""
for ep in ${UPSTREAM_BACKENDS}; do
  UPSTREAM_LINES+="  server ${ep} max_fails=3 fail_timeout=10s;"$'\n'
done

cat > /etc/nginx/upstreams/app.conf <<UPS
upstream app_pool {
  zone app_pool 64k;
  least_conn;
${UPSTREAM_LINES}
  keepalive 256;
}
UPS

cat > /etc/nginx/conf.d/app.conf <<'APP'
server {
  listen 80 default_server reuseport;
  listen 443 ssl default_server reuseport;
  http2 on;

  ssl_certificate     /etc/nginx/tls/fullchain.pem;
  ssl_certificate_key /etc/nginx/tls/privkey.pem;

  location / {
    proxy_pass http://app_pool;
  }
}
APP

# Placeholder self-signed cert (replace before exposing)
if [[ ! -s /etc/nginx/tls/fullchain.pem ]]; then
  openssl req -x509 -nodes -newkey rsa:2048 -days 30 \
    -keyout /etc/nginx/tls/privkey.pem -out /etc/nginx/tls/fullchain.pem \
    -subj "/CN=app.example.com" >/dev/null 2>&1
  chown -R nginx:nginx /etc/nginx/tls
  chmod 600 /etc/nginx/tls/privkey.pem
  echo "WARNING: placeholder self-signed cert installed."
fi

nginx -t
systemctl enable --now nginx

echo "==> ucarp up/down scripts"
mkdir -p /etc/ucarp/scripts
cat > /etc/ucarp/scripts/vip-up.sh <<'UP'
#!/usr/bin/env bash
set -e
IFACE="$1"
VIP="$2"
MASK="$3"
ip addr add "${VIP}/${MASK}" dev "${IFACE}" 2>/dev/null || true
# Gratuitous ARP so the LAN sees the new owner immediately.
arping -U -c 3 -I "${IFACE}" "${VIP}" >/dev/null 2>&1 || true
logger -t ucarp "VIP ${VIP} UP on ${IFACE}"
UP

cat > /etc/ucarp/scripts/vip-down.sh <<'DOWN'
#!/usr/bin/env bash
set -e
IFACE="$1"
VIP="$2"
MASK="$3"
ip addr del "${VIP}/${MASK}" dev "${IFACE}" 2>/dev/null || true
logger -t ucarp "VIP ${VIP} DOWN on ${IFACE}"
DOWN

chmod +x /etc/ucarp/scripts/vip-up.sh /etc/ucarp/scripts/vip-down.sh

echo "==> Templated systemd units for VIP1 and VIP2"
cat > /etc/systemd/system/ucarp@.service <<'UCARP'
[Unit]
Description=ucarp for VIP %i
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
EnvironmentFile=/etc/ucarp/%i.env
ExecStart=/usr/sbin/ucarp \
  --interface=${IFACE} \
  --srcip=${NODE_IP} \
  --vhid=${VHID} \
  --pass=${PASS} \
  --addr=${VIP} \
  --advbase=1 \
  --advskew=${ADVSKEW} \
  --upscript=/etc/ucarp/scripts/vip-up.sh \
  --downscript=/etc/ucarp/scripts/vip-down.sh \
  --neutral \
  --shutdown \
  --xparam=${VIP_NETMASK}
Restart=on-failure
RestartSec=2s

[Install]
WantedBy=multi-user.target
UCARP

mkdir -p /etc/ucarp

cat > /etc/ucarp/vip1.env <<EOF
IFACE=${IFACE}
NODE_IP=${NODE_IP}
VHID=${VIP1_ID}
PASS=${CARP_PASS_1}
VIP=${VIP1}
VIP_NETMASK=${VIP_NETMASK}
ADVSKEW=${VIP1_ADVSKEW}
EOF

cat > /etc/ucarp/vip2.env <<EOF
IFACE=${IFACE}
NODE_IP=${NODE_IP}
VHID=${VIP2_ID}
PASS=${CARP_PASS_2}
VIP=${VIP2}
VIP_NETMASK=${VIP_NETMASK}
ADVSKEW=${VIP2_ADVSKEW}
EOF

chmod 600 /etc/ucarp/vip*.env

systemctl daemon-reload
systemctl enable --now ucarp@vip1.service ucarp@vip2.service

echo "==> conntrackd"
cat > /etc/conntrackd/conntrackd.conf <<CTD
Sync {
  Mode FTFW {
    DisableExternalCache off
    CommitTimeout 1800
    PurgeTimeout 5
  }
  UDP {
    IPv4_address ${NODE_IP}
    IPv4_Destination_Address ${PEER_IP}
    Port 3780
    Interface ${IFACE}
    SndSocketBuffer 1249280
    RcvSocketBuffer 1249280
    Checksum on
  }
}

General {
  Nice -20
  HashSize 32768
  HashLimit 262144
  LogFile on
  Syslog on
  LockFile /var/lock/conntrack.lock
  UNIX {
    Path /var/run/conntrackd.ctl
    Backlog 20
  }
  NetlinkBufferSize 2097152
  NetlinkBufferSizeMaxGrowth 8388608
  Filter From Userspace {
    Protocol Accept { TCP UDP ICMP }
    Address Ignore {
      IPv4_address 127.0.0.1
    }
  }
}
CTD

systemctl enable --now conntrackd

echo "==> firewalld baseline"
systemctl enable --now firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-service=ssh
# CARP advertisements are sent as IP protocol 112 to the CARP multicast group.
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="'"${PEER_IP}"'" protocol value="112" accept'
# conntrackd UDP sync between the two nodes.
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="'"${PEER_IP}"'" port port="3780" protocol="udp" accept'
firewall-cmd --reload

echo "==> nginx reload helper for cert rotation"
cat > /etc/cron.d/nginx-reload <<'CRON'
# Reload nginx daily after cert renewal hooks.
17 4 * * * root /usr/sbin/nginx -t && systemctl reload nginx
CRON

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Interfaces:"
ip -4 addr show dev ${IFACE}
echo
echo "ucarp status:"
systemctl status ucarp@vip1.service ucarp@vip2.service --no-pager | head -30 || true
echo
echo "conntrackd peer:"
conntrackd -s 2>/dev/null | head -20 || true
echo
echo "nginx:"
ss -lntp | grep -E ':(80|443)\b'
echo
echo "Run the same script on the peer node with its NODE_NAME / NODE_IP / PEER_IP swapped."

Make it executable and run on each node (edit the variable block first):

chmod 700 /root/setup-nginx-active-active.sh
/root/setup-nginx-active-active.sh

Once both nodes are up, point DNS round-robin (or a cloud DNS round-robin record set) at VIP1 and VIP2. Each VIP lives on its preferred node in steady state. Run a failover drill: systemctl stop nginx ucarp@vip1 on node-01 and confirm node-02 grabs both VIPs within a second and existing connections survive. Bring node-01 back with systemctl start ucarp@vip1 nginx and the VIPs split again — assuming you used the lower advskew on the preferred owner, ucarp will preempt back.

A few warnings. conntrackd’s FTFW mode is reliable but burns CPU on heavy connection rates; on a busy edge tune HashSize upward and watch conntrackd -s for cache misses. The placeholder self-signed cert above is for first-boot — replace it with your real bundle (same path on both nodes) before serving real traffic, and make sure your renewal hook runs on both nodes so the cert never drifts. If you run on a cloud VPC where promiscuous mode isn’t allowed, ucarp on the L2 LAN doesn’t work — you need a cloud LB or a floating-IP API call as the failover mechanism instead.

For an edge tier where you don’t want to operate ucarp + conntrackd + cert rotation yourself, our environment management team runs the proxy plane with Sev-1 monitoring and failover drills on a cadence. Plan it with us.