主题
第 10 章 Keepalived VIP 配置
10.1 Keepalived 安装
Ubuntu 22.04
bash
apt install -y keepalivedRocky Linux 9
bash
dnf install -y keepalived验证安装
bash
keepalived --version10.2 单 VIP 配置
本书使用单一 VIP 作为客户端统一入口。VIP 会在健康节点之间漂移。
节点规划
| 节点 | VRRP 角色 | Priority |
|---|---|---|
| node1 | MASTER | 100 |
| node2 | BACKUP | 90 |
| node3 | BACKUP | 80 |
10.3 健康检查脚本(检测 Ganesha)
创建检查脚本 /etc/keepalived/check_ganesha.sh:
bash
#!/bin/bash
if systemctl is-active --quiet nfs-ganesha; then
exit 0
else
exit 1
fi赋予执行权限:
bash
chmod +x /etc/keepalived/check_ganesha.shnode1 配置
创建 /etc/keepalived/keepalived.conf:
conf
vrrp_script check_ganesha {
script "/etc/keepalived/check_ganesha.sh"
interval 2
weight -50
fall 2
rise 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1234
}
virtual_ipaddress {
10.0.0.100/24
}
track_script {
check_ganesha
}
}node2 配置
conf
vrrp_script check_ganesha {
script "/etc/keepalived/check_ganesha.sh"
interval 2
weight -50
fall 2
rise 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1234
}
virtual_ipaddress {
10.0.0.100/24
}
track_script {
check_ganesha
}
}node3 配置
conf
vrrp_script check_ganesha {
script "/etc/keepalived/check_ganesha.sh"
interval 2
weight -50
fall 2
rise 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 80
advert_int 1
authentication {
auth_type PASS
auth_pass 1234
}
virtual_ipaddress {
10.0.0.100/24
}
track_script {
check_ganesha
}
}10.4 Master/Backup 优先级设计
优先级设置原则
- 优先级差异建议 10-20,避免频繁切换
- 最高优先级节点作为默认 Master
- 健康检查失败时 priority 降低,触发重新选举
健康检查 weight 计算
| 节点 | 基础 Priority | 检查失败 weight | 失败后 Priority |
|---|---|---|---|
| node1 | 100 | -50 | 50 |
| node2 | 90 | -50 | 40 |
| node3 | 80 | -50 | 30 |
当 node1 的 Ganesha 故障时,priority 降为 50,node2(90)将成为 Master。
10.5 VIP 漂移验证
启动 Keepalived
在所有节点执行:
bash
systemctl enable --now keepalived查看 VIP 所在节点
bash
ip addr show eth0应该看到 10.0.0.100 在 node1 上。
模拟故障
在 node1 停止 Ganesha:
bash
systemctl stop nfs-ganesha等待 4-6 秒后,在 node2 或 node3 查看:
bash
ip addr show eth0VIP 应该漂移到健康节点。
恢复验证
bash
systemctl start nfs-ganesha由于 preempt 默认开启,VIP 会回到 node1。
10.6 多 VIP 与负载均衡进阶
如果需要分散负载,可以配置多个 VRRP 实例,每个实例使用不同 VIP 和不同 Master:
conf
vrrp_instance VI_1 {
state MASTER
virtual_router_id 51
priority 100
virtual_ipaddress { 10.0.0.100/24 }
}
vrrp_instance VI_2 {
state BACKUP
virtual_router_id 52
priority 90
virtual_ipaddress { 10.0.0.101/24 }
}客户端可以将不同业务挂载到不同 VIP,实现负载分担。
10.7 本章小结
- Keepalived 通过 VRRP 提供虚拟 IP
- 健康检查脚本检测 Ganesha 状态,失败时降低 priority
- VIP 会自动漂移到健康的最高优先级节点
- 单 VIP 简单,多 VIP 可实现负载分担
- 修改
interface为实际网卡名
练习题
- Keepalived 的
virtual_router_id有什么作用?同一网络中可以重复吗? weight -50表示什么意思?- 如何验证 VIP 是否成功漂移?
- 多 VIP 配置相比单 VIP 有什么优势?