How to Configure Keepalived on Linux: Setting Up a Virtual IP (VIP) and High Availability (HA) Failover for Servers

Linux tutorial - IT technology blog
Linux tutorial - IT technology blog

A coffee shop with only one cashier grinds to a halt the moment that person calls in sick. Customers stand waiting, orders pile up, and the day’s revenue is practically wiped out.

Server infrastructure operates by the exact same rule. When a website runs on a single server, a power outage, network drop, or service crash immediately leaves every user staring at an error page. High Availability (HA) eliminates this weakness by keeping a standby server ready. As soon as the primary machine goes down, the backup automatically takes over traffic within seconds.

Comparing Server Failover Solutions

To let two or more servers automatically take over from one another during an outage, sysadmins typically consider four common approaches:

  • DNS Failover: You point your domain (such as example.com) to the primary server’s IP. When the primary goes offline, the DNS system automatically updates the record to the backup server’s IP.
  • Cloud Load Balancer: You rent a load-balancing service from a cloud provider like AWS ALB or Cloudflare Load Balancing. All traffic passes through this intermediary layer before being distributed to the underlying servers.
  • Pacemaker with Corosync: A comprehensive Linux clustering solution for resource management. This model is typically used for shared storage systems or complex databases.
  • Keepalived with a Virtual IP (VIP): Two servers share a single “virtual” IP address. Normally, the primary server (Master) holds the VIP; when the Master fails, the secondary server (Backup) automatically claims this IP using the VRRP (Virtual Router Redundancy Protocol).

Pros and Cons of Each Approach

No single solution fits every use case. Depending on your budget and existing infrastructure, each approach comes with its own trade-offs:

1. DNS Failover

  • Pros: Quick to set up with no extra software required on Linux. It works well even if the two servers are located in different countries.
  • Cons: Slow failover. Even with a low TTL (such as 60 or 300 seconds), many ISPs and browsers cache old DNS records for anywhere from several minutes to an hour.

2. Cloud Load Balancer

  • Pros: Virtually zero maintenance overhead, with an intuitive management dashboard out of the box. It both distributes traffic and automatically removes unhealthy nodes in real time.
  • Cons: Incurs a fixed monthly cost (typically starting around $15–$25 or more depending on traffic). Additionally, it isn’t an option if you’re running on-premises physical servers or budget VPS plans that don’t support this feature.

3. Pacemaker + Corosync

  • Pros: Fine-grained control over individual services and shared storage. Its STONITH (Shoot The Other Node In The Head) mechanism reliably prevents two servers from fighting for control (split-brain).
  • Cons: Steep learning curve. Configuration and debugging are complex, making it overkill if you only need failover for a web server or reverse proxy.

4. Keepalived and Virtual IP (VIP)

  • Pros: Lightweight, free, and the entire configuration lives in a single file. Failover is very fast, taking only about 1 to 4 seconds.
  • Cons: All servers must reside on the same local network segment (same Layer 2 Subnet/LAN) to share a VIP address.

When Should You Choose Keepalived?

Do you have two or more Linux servers on the same LAN or in the same datacenter? Are you running Nginx, HAProxy, or internal APIs and looking to save on Load Balancer costs? If so, Keepalived is the ideal fit.

Keepalived works much like staffing a hotline. Both servers share a single hotline number—the Virtual IP. The Master server holds the line and sends a heartbeat signal every second to let the Backup know it is still healthy. If more than 3 seconds pass without a response, the Backup assumes the Master has failed and immediately picks up the line.

How to Deploy Keepalived and Configure a Virtual IP on Linux

Consider a practical setup with 2 Linux servers on the same 192.168.1.0/24 local network using the eth0 network interface:

  • Master Server: 192.168.1.10
  • Backup Server: 192.168.1.11
  • Virtual IP (VIP): 192.168.1.100 (the address clients or other services will connect to)

Quick tip: On newer Linux distributions, network interfaces are often named something like ens33, ens18, or enp0s3. Run ip addr to verify the exact interface name before editing the configuration file.

Step 1: Install Keepalived on Both Servers

On Ubuntu or Debian, install it directly via apt:

sudo apt update
sudo apt install -y keepalived

On AlmaLinux, Rocky Linux, or RHEL, use dnf:

sudo dnf install -y keepalived

Step 2: Allow Services to Listen on the Virtual IP

By default, the Linux kernel does not allow applications (like Nginx) to bind to an IP address that doesn’t currently exist on a network interface—because at any given moment, the VIP only resides on the Master. To lift this restriction, enable the ip_nonlocal_bind parameter on both servers:

echo "net.ipv4.ip_nonlocal_bind = 1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Step 3: Configure Keepalived for Master and Backup

Open or create /etc/keepalived/keepalived.conf on the Master Server (192.168.1.10). The configuration below includes a vrrp_script to monitor the nginx process. That way, even if the server itself hasn’t crashed but the web server hangs, the VIP automatically fails over to the backup node:

vrrp_script chk_service {
    script "/usr/bin/pgrep -x nginx"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 101
    advert_int 1

    unicast_src_ip 192.168.1.10
    unicast_peer {
        192.168.1.11
    }

    authentication {
        auth_type PASS
        auth_pass Vrrp2026
    }

    virtual_ipaddress {
        192.168.1.100/24
    }

    track_script {
        chk_service
    }
}

A quick note on passwords: auth_pass in VRRP only accepts up to 8 characters. If you set a longer one, Keepalived will automatically truncate the extra characters and log a warning.

On the Backup Server (192.168.1.11), create /etc/keepalived/keepalived.conf with nearly identical contents. Simply change state to BACKUP, lower priority to 100, and swap the two IP addresses in the unicast section:

vrrp_script chk_service {
    script "/usr/bin/pgrep -x nginx"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1

    unicast_src_ip 192.168.1.11
    unicast_peer {
        192.168.1.10
    }

    authentication {
        auth_type PASS
        auth_pass Vrrp2026
    }

    virtual_ipaddress {
        192.168.1.100/24
    }

    track_script {
        chk_service
    }
}

There is a common pitfall if you copy-paste default configs from the internet. Early in my sysadmin career, I once spent an entire afternoon debugging why both the Master and Backup claimed to be Master and held the VIP simultaneously. When I checked the logs with journalctl -u keepalived -f, I discovered the VPS provider’s network blocked default multicast packets. Explicitly defining unicast_src_ip and unicast_peer as shown above helps you avoid this headache.

Don’t forget to check your firewall if UFW or firewalld is enabled. Both servers need to communicate over the VRRP protocol (protocol 112). For example, with UFW, allow it using:

sudo ufw allow proto vrrp from 192.168.1.0/24

Step 4: Start the Service and Test Failover

Enable and start Keepalived on both servers, then check its status:

sudo systemctl enable --now keepalived
sudo systemctl status keepalived

Next, check which server currently holds the Virtual IP 192.168.1.100:

ip addr show eth0

When working properly, the eth0 interface on the Master will display both 192.168.1.10/24 and 192.168.1.100/24, while the Backup will only show its real IP 192.168.1.11/24.

Now simulate an outage on the Master by stopping the Keepalived service (or stopping Nginx):

sudo systemctl stop keepalived

Immediately run ip addr show eth0 again on the Backup server. When stopped gracefully, the Master sends a notification packet, allowing the Backup to take over the VIP 192.168.1.100/24 in about 1 second. If the Master loses power or network connectivity abruptly, failover takes around 3–4 seconds. Once you restart Keepalived on the Master, the VIP automatically fails back because it has a higher priority (101 vs. 100).

With just around 30 lines of configuration, your server cluster is no longer tied to a Single Point of Failure. You can confidently perform maintenance on individual nodes or handle unexpected outages without investing in expensive additional hardware.

Share: