You have a small fleet of application servers that share files over NFS — a media library, a code build cache, a shared upload directory for a multi-tenant app. The NFS server is a single VM on a managed hypervisor; when that VM gets rebooted for kernel patches, every NFS client hangs for the duration of the maintenance window. The application either blocks on the mount and produces a thundering herd of timeouts, or it gives up and starts throwing 5xx. Moving to S3 isn’t an option this quarter — the application doesn’t speak it, and the code change is bigger than the storage problem. What you can do, in two days, is put DRBD underneath the NFS server, run two of them in active/passive, give them a virtual IP managed by keepalived, and let the NFSv4 kernel client handle the actual failover transparently. Clients see a brief pause; nothing un-mounts; the application doesn’t notice.
What’s happening
The stack has three layers. DRBD 9 mirrors a block device (/dev/sdb here) from the active node to the standby — synchronous protocol C, so a write only ACKs after it’s durable on both. The filesystem lives on /dev/drbd0, mounted at /srv/nfs on whichever node is currently primary. keepalived runs VRRP between the two nodes, carries a virtual IP that the NFS clients always connect to, and runs a notify script that flips DRBD primary/secondary and mounts/unmounts the filesystem when the VIP moves. NFSv4 exports /srv/nfs as a single pseudo-root. The NFSv4 client, unlike NFSv3, was designed for server failover — when the TCP connection to the server breaks, the client transparently retransmits to whatever is now answering on the same IP, and the application sees a pause rather than an error.
Two pieces of that story have sharp edges. First, NFS state (open file handles, locks, leases) lives on the active server. When the VIP moves, the new server starts with no state. NFSv4 has a 90-second grace period (lease_time) during which clients reclaim their locks; if the failover takes longer than that, locks are lost. You configure both servers to point their /var/lib/nfs state directory at a path on the DRBD volume so the state survives failover — that’s the trick that makes “transparent” actually transparent. Second, NFSv3 was an option for fifteen years and is still default on a lot of distros, but its locking is brittle on failover (rpc.statd, rpc.lockd, port mapper). NFSv4-only is the correct choice for any new HA NFS deployment, and the kernel client speaks v4 by default since RHEL 8 / Ubuntu 20.04.
Common failure modes: DRBD enters split-brain because keepalived flapped during a brief network glitch and both nodes briefly thought they were primary (fix: STONITH, or at minimum a notify script that doesn’t promote without checking peer state); /var/lib/nfs not on the DRBD volume, so file handles change after failover and clients see “stale file handle” errors that persist until reboot; nfs-server not stopped before the VIP moves, leaving the old primary still answering on the same export.
How to verify
DRBD says both sides are UpToDate:
drbdadm status nfs-store
# nfs-store role:Primary
# disk:UpToDate
# peer role:Secondary
# replication:Established peer-disk:UpToDate
keepalived has elected one MASTER and the VIP is up on that node only:
# On the primary
ip -br addr show | grep '10.50.0.10'
# ens4 UP 10.50.0.11/24 10.50.0.10/32
# On the secondary
ip -br addr show | grep '10.50.0.10'
# (empty)
NFS is exported and the client can mount:
showmount -e 10.50.0.10
# Export list for 10.50.0.10:
# /srv/nfs *
mount -t nfs4 10.50.0.10:/ /mnt/nfs
df -hT /mnt/nfs
# Filesystem Type Size Used Avail Use% Mounted on
# 10.50.0.10:/ nfs4 100G 64K 100G 1% /mnt/nfs
End-to-end failover drill — what you run before this serves production traffic:
# On a client, start a continuous write while you fail over
while true; do
date +"%H:%M:%S.%N" >> /mnt/nfs/heartbeat
sleep 0.5
done
# On the primary node, force a controlled failover
systemctl stop keepalived # VIP moves to peer
# Watch the heartbeat file: there should be a 1-15s gap, then writes resume
# Bring it back
systemctl start keepalived
If the client errors with Stale file handle or the write loop dies with an IO error, /var/lib/nfs is not on the DRBD volume — fix that before going live.
The fix
Save the script as /root/setup-nfs-ha.sh and run it on each of the two nodes after editing the variables at the top. Run on nfs-01 first, complete the post-install steps printed at the end (force initial DRBD sync, format the filesystem, move /var/lib/nfs onto the DRBD volume), then run on nfs-02.
#!/usr/bin/env bash
set -euo pipefail
### AlmaLinux 9 HA NFSv4 installer: DRBD 9 + keepalived
### Run on BOTH nodes after editing the variables below; run on nfs-01 first
### /dev/sdb must be a dedicated, unpartitioned block device of the same size on both nodes
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
# === EDIT PER DEPLOYMENT ===
NODE_NAME="nfs-01" # nfs-01 or nfs-02
NODE_IP="10.50.0.11"
PEER_NAME="nfs-02"
PEER_IP="10.50.0.12"
VIP="10.50.0.10"
VIP_CIDR="24"
REPLICATION_NIC="ens4"
RESOURCE_NAME="nfs-store"
BACKING_DEVICE="/dev/sdb"
MOUNT_POINT="/srv/nfs"
NFS_STATE_DIR_ON_DRBD="${MOUNT_POINT}/.nfs-state"
EXPORT_SUBNET="10.50.0.0/16"
KEEPALIVED_AUTH="CHANGE_ME_KEEPALIVED"
DRBD_SHARED_SECRET="CHANGE_ME_DRBD"
# ===========================
if [[ "${NODE_NAME}" == "nfs-01" ]]; then
VRRP_PRIORITY=200
VRRP_STATE="MASTER"
else
VRRP_PRIORITY=150
VRRP_STATE="BACKUP"
fi
echo
echo "========================================"
echo "HA NFS node ${NODE_NAME} (${NODE_IP})"
echo "VIP ${VIP} | DRBD ${RESOURCE_NAME} on ${BACKING_DEVICE}"
echo "========================================"
echo
echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release elrepo-release
dnf -y install vim curl wget chrony fail2ban dnf-automatic \
policycoreutils-python-utils lsof tcpdump bind-utils tar gzip jq socat \
iproute net-tools parted util-linux \
nfs-utils rpcbind
systemctl enable --now chronyd
echo "==> SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true
echo "==> /etc/hosts (no DNS dependency in the failover path)"
if ! grep -q "${PEER_IP}\s*${PEER_NAME}" /etc/hosts; then
echo "${PEER_IP} ${PEER_NAME}" >> /etc/hosts
fi
hostnamectl set-hostname "${NODE_NAME}"
echo "==> Firewalld — narrow rules between the two nodes; NFSv4 only"
systemctl enable --now firewalld
firewall-cmd --permanent --zone=public --add-service=ssh
firewall-cmd --permanent --new-zone=cluster 2>/dev/null || true
firewall-cmd --permanent --zone=cluster --add-source="${PEER_IP}/32"
firewall-cmd --permanent --zone=cluster --add-port=7788-7799/tcp # DRBD
firewall-cmd --permanent --zone=cluster --add-protocol=vrrp # VRRP
firewall-cmd --permanent --zone=public --add-service=nfs # NFSv4 (2049/tcp)
firewall-cmd --permanent --zone=public --add-port=2049/tcp
firewall-cmd --reload
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
echo "==> Sysctl — NFS server + DRBD throughput"
cat > /etc/sysctl.d/99-nfs-ha.conf <<'SYSCTL'
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.rmem_default = 524288
net.core.wmem_default = 524288
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.core.netdev_max_backlog = 30000
# NFSv4 grace period: 90s default; clients reclaim locks within this window
fs.nfs.nfs_callback_tcpport = 0
vm.swappiness = 5
vm.dirty_background_ratio = 5
vm.dirty_ratio = 15
SYSCTL
sysctl --system
echo "==> Installing DRBD 9 from ELRepo"
dnf -y install kmod-drbd9x drbd9x-utils
modprobe drbd
lsmod | grep -q drbd || { echo "DRBD module did not load"; exit 1; }
echo "==> Wiping backing device ${BACKING_DEVICE}"
if [[ ! -b "${BACKING_DEVICE}" ]]; then
echo "ERROR: ${BACKING_DEVICE} is not present"
exit 1
fi
wipefs -a "${BACKING_DEVICE}" || true
echo "==> DRBD global config"
cat > /etc/drbd.d/global_common.conf <<'GLOBAL'
global {
usage-count no;
udev-always-use-vnr;
}
common {
handlers {
split-brain "/usr/lib/drbd/notify-split-brain.sh root";
}
startup {
wfc-timeout 30;
degr-wfc-timeout 30;
}
options {
on-no-data-accessible io-error;
auto-promote no;
}
disk {
on-io-error detach;
disk-flushes yes;
md-flushes yes;
resync-rate 100M;
c-plan-ahead 20;
c-max-rate 200M;
}
net {
protocol C;
max-buffers 36864;
sndbuf-size 1024k;
rcvbuf-size 2048k;
verify-alg sha256;
ping-int 5;
ping-timeout 30;
connect-int 10;
timeout 60;
after-sb-0pri discard-zero-changes;
after-sb-1pri discard-secondary;
after-sb-2pri disconnect;
rr-conflict disconnect;
cram-hmac-alg sha256;
}
}
GLOBAL
echo "==> DRBD resource ${RESOURCE_NAME}"
cat > "/etc/drbd.d/${RESOURCE_NAME}.res" <<EOF
resource ${RESOURCE_NAME} {
device /dev/drbd0;
disk ${BACKING_DEVICE};
meta-disk internal;
net {
shared-secret "${DRBD_SHARED_SECRET}";
}
on ${NODE_NAME} {
node-id 0;
address ${NODE_IP}:7788;
}
on ${PEER_NAME} {
node-id 1;
address ${PEER_IP}:7788;
}
connection-mesh {
hosts ${NODE_NAME} ${PEER_NAME};
}
}
EOF
chmod 600 /etc/drbd.d/*.conf "/etc/drbd.d/${RESOURCE_NAME}.res"
echo "==> Creating DRBD metadata"
yes | drbdadm create-md "${RESOURCE_NAME}"
echo "==> Bring DRBD up (will be Inconsistent until peer joins + initial sync)"
systemctl enable drbd
systemctl restart drbd
drbdadm up "${RESOURCE_NAME}"
mkdir -p "${MOUNT_POINT}"
echo "==> Configure NFS server: NFSv4 only, no UDP"
cat > /etc/nfs.conf.d/ha.conf <<'NFSCONF'
[nfsd]
vers2 = n
vers3 = n
vers4 = y
vers4.0 = y
vers4.1 = y
vers4.2 = y
udp = n
tcp = y
threads = 32
NFSCONF
# Don't bind state to /var/lib/nfs locally; it will be redirected to DRBD post-install
mkdir -p /etc/nfs.conf.d
# Disable rpcbind for NFSv4-only mode
systemctl mask rpcbind 2>/dev/null || true
systemctl mask rpcbind.socket 2>/dev/null || true
echo "==> Writing /etc/exports (single NFSv4 pseudo-root)"
cat > /etc/exports <<EOF
${MOUNT_POINT} ${EXPORT_SUBNET}(rw,sync,no_subtree_check,fsid=0,sec=sys,no_root_squash)
EOF
# Don't start nfs-server here — keepalived will start/stop it on failover
systemctl disable nfs-server || true
systemctl stop nfs-server || true
echo "==> Installing keepalived"
dnf -y install keepalived
mkdir -p /etc/keepalived
mkdir -p /usr/local/bin/keepalived
echo "==> keepalived failover scripts"
cat > /usr/local/bin/keepalived/nfs_takeover.sh <<EOF
#!/usr/bin/env bash
set -euo pipefail
exec >>/var/log/keepalived-nfs.log 2>&1
echo "[$(date -Iseconds)] nfs_takeover invoked"
# Verify peer is not also primary (best-effort split-brain guard)
PEER_ROLE=\$(drbdadm status ${RESOURCE_NAME} | awk '/peer role:/{print \$3}' | head -1)
echo " peer role currently: \${PEER_ROLE}"
# Promote DRBD
drbdadm primary ${RESOURCE_NAME}
echo " promoted to Primary"
# Mount the filesystem
if ! mountpoint -q ${MOUNT_POINT}; then
mount -t ext4 -o noatime,nodiratime /dev/drbd0 ${MOUNT_POINT}
echo " mounted /dev/drbd0 on ${MOUNT_POINT}"
fi
# Move NFS state directory onto DRBD if not already
if [[ -L /var/lib/nfs ]] || [[ "\$(readlink /var/lib/nfs)" == "${NFS_STATE_DIR_ON_DRBD}" ]]; then
: # already symlinked
else
if [[ ! -d "${NFS_STATE_DIR_ON_DRBD}" ]]; then
cp -a /var/lib/nfs "${NFS_STATE_DIR_ON_DRBD}"
fi
fi
# Start NFS server (state will be reclaimed during the NFSv4 grace period)
systemctl start nfs-server
echo " nfs-server started"
EOF
cat > /usr/local/bin/keepalived/nfs_release.sh <<EOF
#!/usr/bin/env bash
set -euo pipefail
exec >>/var/log/keepalived-nfs.log 2>&1
echo "[$(date -Iseconds)] nfs_release invoked"
systemctl stop nfs-server || true
echo " nfs-server stopped"
if mountpoint -q ${MOUNT_POINT}; then
umount ${MOUNT_POINT} || umount -l ${MOUNT_POINT}
echo " unmounted ${MOUNT_POINT}"
fi
drbdadm secondary ${RESOURCE_NAME} || true
echo " demoted to Secondary"
EOF
cat > /usr/local/bin/keepalived/check_drbd.sh <<EOF
#!/usr/bin/env bash
# Returns 0 if DRBD is healthy and we are eligible to be MASTER; non-zero otherwise.
set -u
ROLE=\$(drbdadm role ${RESOURCE_NAME} 2>/dev/null || echo "Unknown")
DISK=\$(drbdadm dstate ${RESOURCE_NAME} 2>/dev/null || echo "Unknown")
case "\${DISK}" in
UpToDate|Consistent)
exit 0
;;
*)
echo "DRBD disk state \${DISK}; not eligible for MASTER"
exit 1
;;
esac
EOF
chmod 700 /usr/local/bin/keepalived/*.sh
echo "==> keepalived config"
cat > /etc/keepalived/keepalived.conf <<EOF
global_defs {
router_id ${NODE_NAME}
enable_script_security
script_user root
}
vrrp_script chk_drbd {
script "/usr/local/bin/keepalived/check_drbd.sh"
interval 5
timeout 4
fall 2
rise 2
weight -30
}
vrrp_instance NFS_HA {
state ${VRRP_STATE}
interface ${REPLICATION_NIC}
virtual_router_id 51
priority ${VRRP_PRIORITY}
advert_int 1
nopreempt
unicast_src_ip ${NODE_IP}
unicast_peer {
${PEER_IP}
}
authentication {
auth_type PASS
auth_pass ${KEEPALIVED_AUTH}
}
virtual_ipaddress {
${VIP}/${VIP_CIDR} dev ${REPLICATION_NIC}
}
track_script {
chk_drbd
}
notify_master "/usr/local/bin/keepalived/nfs_takeover.sh"
notify_backup "/usr/local/bin/keepalived/nfs_release.sh"
notify_fault "/usr/local/bin/keepalived/nfs_release.sh"
}
EOF
chmod 600 /etc/keepalived/keepalived.conf
systemctl enable keepalived
echo
echo "========================================"
echo "BASE INSTALL DONE on ${NODE_NAME}"
echo "========================================"
echo
echo "POST-INSTALL (run ONCE, on nfs-01 only, after BOTH nodes finish base install):"
echo
echo " # 1. Force the initial DRBD sync from nfs-01"
echo " drbdadm primary --force ${RESOURCE_NAME}"
echo " watch -n 2 'drbdadm status ${RESOURCE_NAME}' # wait for UpToDate/UpToDate"
echo
echo " # 2. Create the filesystem on /dev/drbd0 (once)"
echo " mkfs.ext4 -L ${RESOURCE_NAME} /dev/drbd0"
echo " mount -o noatime,nodiratime /dev/drbd0 ${MOUNT_POINT}"
echo
echo " # 3. Migrate /var/lib/nfs to live on DRBD so failover preserves NFSv4 state"
echo " systemctl stop nfs-server || true"
echo " mkdir -p ${NFS_STATE_DIR_ON_DRBD}"
echo " cp -a /var/lib/nfs/* ${NFS_STATE_DIR_ON_DRBD}/ 2>/dev/null || true"
echo " rm -rf /var/lib/nfs"
echo " ln -s ${NFS_STATE_DIR_ON_DRBD} /var/lib/nfs"
echo
echo " # 4. On nfs-02, mirror the symlink (the directory follows DRBD)"
echo " ssh root@${PEER_IP} 'rm -rf /var/lib/nfs && ln -s ${NFS_STATE_DIR_ON_DRBD} /var/lib/nfs'"
echo
echo " # 5. Demote and start keepalived on both nodes"
echo " umount ${MOUNT_POINT}"
echo " drbdadm secondary ${RESOURCE_NAME}"
echo " systemctl start keepalived # on nfs-01"
echo " ssh root@${PEER_IP} 'systemctl start keepalived' # on nfs-02"
echo
echo " # 6. Failover drill"
echo " systemctl stop keepalived # VIP moves to nfs-02"
echo " # On a client: writes should pause ~5-15s then resume; no stale handle"
echo " systemctl start keepalived"
Make it executable and run on both nodes:
chmod 700 /root/setup-nfs-ha.sh
/root/setup-nfs-ha.sh # nfs-01 first, then nfs-02
Then run the post-install block on nfs-01 exactly once — the sequence matters. Bring DRBD up to UpToDate/UpToDate, format /dev/drbd0, move /var/lib/nfs onto the DRBD volume, and only then start keepalived on both sides. If you skip step 3, the new primary will hand clients different file handles after failover, and Stale file handle errors will persist until the clients are remounted.
Client-side considerations:
-
Mount with NFSv4 and
hard,intrsemantics. Asoftmount turns transient failover into permanent IO errors; ahardmount is what lets the kernel client wait out the VIP move.# On every NFS client cat > /etc/systemd/system/srv-shared.mount <<'UNIT' [Unit] Description=Shared NFS mount from HA NFS cluster After=network-online.target Wants=network-online.target [Mount] What=10.50.0.10:/ Where=/srv/shared Type=nfs4 Options=rw,hard,timeo=600,retrans=2,sec=sys,vers=4.2,_netdev [Install] WantedBy=multi-user.target UNIT systemctl daemon-reload systemctl enable --now srv-shared.mount -
NFSv4 grace period is 90 seconds. If your failover takes longer than that, lock state is lost. Tune
lease_timeif you have to, but the better fix is to make failover faster: VRRPadvert_int 1,notify_masterscript that does its work in under 5 seconds, no DNS in the hot path. -
fsid=0makes the export the NFSv4 pseudo-root. That’s why clients mount10.50.0.10:/and not10.50.0.10:/srv/nfs. If you also need sub-exports, declare them under the pseudo-root and the client mounts them as:/sub-name.
Two production guardrails:
-
No real fencing in this stack. keepalived has a
check_drbdscript that refuses MASTER if the local DRBD disk is bad, andnotify_masterchecks peer role before promotion. That is a soft safeguard, not STONITH. For a deployment that can tolerate brief split-brain windows (read-mostly content servers, build caches), this is acceptable. For deployments where two concurrent writers would corrupt data, add Pacemaker with proper fencing on top — but at that point you are no longer running this stack, you are running the DRBD + Pacemaker stack and keepalived is removed. -
Don’t share the DRBD replication NIC with VRRP and NFS traffic. A burst of NFS traffic that saturates the replication NIC can flap VRRP, and the cluster fails over for the wrong reason. Two NICs: one for replication + VRRP, one for client-facing NFS. Cheap insurance.
Stack Harbor runs HA NFS clusters under Managed Cloud Ops on managed cloud compute — separate replication network, NFSv4-only exports, quarterly client-side failover drills, and /var/lib/nfs correctly carried by DRBD — start a scoping call if you want shared storage that survives a node reboot without your application noticing.