Keepalived is a Linux-based routing software that offers load balancing and high availability through the Virtual Router Redundancy Protocol (VRRP) and health checks. It enables servers to share a virtual IP address to provide failover capabilities and ensures that network services remain available even if individual servers fail.
VRRP ensures that one of the participating servers takes over a virtual IP address if the current holder of the IP fails. Keepalived automates this process, providing a seamless transition between servers, which is crucial for maintaining service availability.
Keepalived can monitor the health of services on servers, using simple scripts or checking the availability of HTTP or TCP services. If a service fails its health check, Keepalived can trigger a failover to another server that is still operational.
To install Keepalived, use the package manager of your Linux distribution.
sudo apt-get update && sudo apt-get install keepalived
sudo yum install keepalived
Before diving into Keepalived configuration, it's essential to ensure that the firewall is configured to allow VRRP traffic. This step is crucial for Keepalived's VRRP communication:
sudo firewall-cmd --add-rich-rule='rule protocol value="vrrp" accept' --permanent
sudo firewall-cmd --reload
This configuration allows VRRP protocol traffic through the firewall, essential for the communication between MASTER and BACKUP servers.
The primary configuration file for Keepalived is located at /etc/keepalived/keepalived.conf
. It includes global settings, VRRP instance definitions, and health check configurations.
For a host designated as MASTER, replace YOUR_MASTER_IP
with the internal IP of this machine, and YOUR_BACKUP_IP
with the internal IP of the backup machine:
global_defs {
enable_script_security
}
vrrp_track_process chk_service {
process nginx
weight 2
}
vrrp_instance VI_1 {
interface ens192
virtual_router_id 27
state MASTER
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass secret12
}
virtual_ipaddress {
192.0.2.100/32
}
unicast_src_ip YOUR_MASTER_IP
unicast_peer {
YOUR_BACKUP_IP
}
track_process {
chk_service
}
}
For a host designated as BACKUP, reverse the YOUR_MASTER_IP
and YOUR_BACKUP_IP
from the MASTER configuration:
global_defs {
enable_script_security
}
vrrp_track_process chk_service {
process nginx
weight 2
}
vrrp_instance VI_2 {
interface ens192
virtual_router_id 27
state BACKUP
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass secret12
}
virtual_ipaddress {
192.0.2.100/32
}
unicast_src_ip YOUR_BACKUP_IP
unicast_peer {
YOUR_MASTER_IP
}
track_process {
chk_service
}
}
Health checks monitor the availability of services, such as nginx, adjusting VRRP priorities based on service availability to facilitate automatic failover.
After configuring Keepalived and firewall rules, restart Keepalived and monitor logs for any errors or status changes:
sudo systemctl restart keepalived
tail -f /var/log/syslog | grep Keepalived