Keepalived结合Nginx可以实现高可用的Web服务架构,确保在主服务器故障时自动切换到备用服务器。以下是详细实现方案:
架构组成:
工作原理:
在两台服务器上执行:
# CentOS/RHEL
yum install -y nginx keepalived
# Ubuntu/Debian
apt-get install -y nginx keepalived
在两台服务器上配置相同的Nginx服务(内容根据实际需求调整):
# /etc/nginx/nginx.conf
http {
server {
listen 80;
server_name your_domain.com;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
}
global_defs {
router_id LVS_MASTER # 唯一标识,备机改为LVS_BACKUP
}
vrrp_script chk_nginx {
script "/usr/bin/killall -0 nginx" # 检测nginx进程是否存在
interval 2 # 每2秒检测一次
weight -20 # 检测失败则优先级减20
}
vrrp_instance VI_1 {
state MASTER # 主服务器设置为MASTER,备机设置为BACKUP
interface eth0 # 修改为实际网卡名称
virtual_router_id 51 # 虚拟路由ID,主备必须相同
priority 100 # 主服务器优先级高于备机(如备机设为90)
advert_int 1 # 主备同步检查间隔
authentication {
auth_type PASS
auth_pass 1111 # 主备密码必须一致
}
virtual_ipaddress {
192.168.1.100 # 虚拟IP(VIP),根据实际网络配置
}
track_script {
chk_nginx # 关联nginx检测脚本
}
}
只需修改以下参数:
router_id LVS_BACKUP
state BACKUP
priority 90 # 低于主服务器
在两台服务器上执行:
systemctl start nginx
systemctl enable nginx
systemctl start keepalived
systemctl enable keepalived
故障转移测试:
systemctl stop nginx
服务器宕机测试:
global_defs {
notification_email {
admin@example.com
}
notification_email_from keepalived@example.com
smtp_server smtp.example.com
smtp_connect_timeout 30
}
vrrp_instance VI_2 {
state BACKUP
interface eth0
virtual_router_id 52
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 2222
}
virtual_ipaddress {
192.168.1.101
}
}
/etc/keepalived/check_nginx.sh
:#!/bin/bash
if [ "$(curl -s -o /dev/null -w '%{http_code}' http://localhost)" != "200" ]; then
systemctl restart nginx
sleep 2
if [ "$(curl -s -o /dev/null -w '%{http_code}' http://localhost)" != "200" ]; then
exit 1
fi
fi
exit 0
然后更新vrrp_script部分:
vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -20
}
VRRP协议问题:
iptables -A INPUT -p vrrp -j ACCEPT
VIP无法切换:
virtual_router_id
是否一致auth_pass
是否一致脑裂问题:
通过以上配置,您已经建立了一个高可用的Nginx服务架构,能够自动处理单点故障,确保服务持续可用。