Keepalived is a daemon that provides simple and robust high-availability (HA) for Linux systems, mainly by managing Virtual IPs (VIPs) and failover using VRRP (Virtual Router Redundancy Protocol).
1. Install Keepalived
On Ubuntu/Debian:
sudo apt update
sudo apt install keepalived -y
On CentOS/RHEL:
sudo yum install epel-release -y
sudo yum install keepalived -y
Check version:
keepalived -v
2. Basic Concept
- VRRP: Protocol to assign a Virtual IP to a master server. Backup servers monitor the master and take over the VIP if the master fails.
- VIP: Virtual IP shared among servers. Clients connect to VIP, not the real server IP.
- Priority: Determines master (higher priority wins).
- State: MASTER or BACKUP.
3. Simple Keepalived Configuration
Edit /etc/keepalived/keepalived.conf on MASTER:
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass mysecret
}
virtual_ipaddress {
192.168.1.100
}
}
On BACKUP server:
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass mysecret
}
virtual_ipaddress {
192.168.1.100
}
}
Explanation:
interface: network interface to bind VIP.virtual_router_id: unique VRRP ID (1–255) shared by the group.priority: higher = master.advert_int: advertisement interval in seconds.authentication: simple password auth.virtual_ipaddress: IP that floats between servers.
4. Advanced Configuration
4.1 Track Scripts
Run a script to check service health and adjust priority dynamically.
vrrp_script chk_nginx {
script "pidof nginx"
interval 2
weight 20
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass mysecret
}
virtual_ipaddress {
192.168.1.100
}
track_script {
chk_nginx
}
}
weight: decreases priority if the script fails, triggering failover.
4.2 Multiple VIPs
You can assign multiple VIPs:
virtual_ipaddress {
192.168.1.100
192.168.1.101
}
4.3 Notifications
Keepalived can trigger scripts on state changes:
notify /etc/keepalived/notify.sh
Example notify.sh:
#!/bin/bash
TYPE=$1
NAME=$2
STATE=$3
echo "$(date) - $TYPE $NAME changed state to $STATE" >> /var/log/keepalived.log
5. Start & Enable Keepalived
sudo systemctl start keepalived
sudo systemctl enable keepalived
sudo systemctl status keepalived
Check VIP:
ip addr show eth0
6. Troubleshooting
- Logs:
/var/log/syslog(Ubuntu/Debian) or/var/log/messages(CentOS/RHEL). - Test failover: stop keepalived on master, backup should take VIP.
- Verify priority and state:
sudo ip addr show
sudo systemctl status keepalived
7. Practical Tips
- Always test failover in a safe environment.
- Keep VRRP
virtual_router_idunique per VIP group. - Set higher
priorityfor your main server. - Use
track_scriptfor service-aware failover (Nginx, HAProxy, MySQL, etc.). - Combine with HAProxy for full HA load balancing.