
在生产环境中,单点故障(SPOF) 是架构稳定性的最大敌人。 无论是 Nginx 还是 HAProxy,一旦入口节点宕机,整个业务就会中断。 Keepalived 的作用就是——让入口节点“永不宕机”。
┌──────────────┐
│ Client │
└──────┬───────┘
│
VIP: 192.168.1.100
│
┌──────────┴──────────┐
│ │
┌───▼───┐ ┌─────▼────┐
│ Nginx │ │ HAProxy │
│ Master│ │ Backup │
└───┬───┘ └─────┬────┘
│ │
└──────────┬──────────┘
│
┌─────▼─────┐
│ Backend │
└───────────┘
节点角色 | 主机名 | IP 地址 | 说明 |
|---|---|---|---|
Master | lb01 | 192.168.1.11 | 主入口 |
Backup | lb02 | 192.168.1.12 | 备用入口 |
VIP | - | 192.168.1.100 | 漂移 IP |
CentOS / RHEL 系列
yum install -y keepalivedDebian / Ubuntu 系列
apt-get update && apt-get install -y keepalived/etc/keepalived/keepalived.confvrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 123456
}
virtual_ipaddress {
192.168.1.100/24
}
track_script {
chk_nginx
}
}
vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -20
}vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 123456
}
virtual_ipaddress {
192.168.1.100/24
}
track_script {
chk_nginx
}
}
vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -20
}vi /etc/keepalived/check_nginx.sh
把以下内容填入#!/bin/bash
if ! pgrep nginx > /dev/null; then
systemctl start nginx
sleep 2
if ! pgrep nginx > /dev/null; then
exit 1
fi
fi
exit 0给到执行权限
chmod +x /etc/keepalived/check_nginx.shsystemctl enable keepalived --nowip addr show eth0应看到 VIP 192.168.1.100 已绑定
systemctl stop nginx几秒后,VIP 会自动漂移到 Backup 节点
如果入口层是 HAProxy,只需将健康检查脚本改为:
bash
#!/bin/bash
if ! pgrep haproxy > /dev/null; then
systemctl start haproxy
sleep 2
if ! pgrep haproxy > /dev/null; then
exit 1
fi
fi
exit 0unicast_peer 或 notify 脚本,避免双主通过 Keepalived + Nginx/HAProxy,我们可以在入口层实现秒级故障切换,让业务在节点宕机时依然平稳运行。 这套方案部署简单、成本低,非常适合中小型企业和高可用入门实践。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。