首先准备两台虚拟机
构架方式为
其中没有后端使用两台虚拟机安装nginx和keepalived
master {nginx + keepalived 192.168.110.171} - [vrrp192.168.1.138] - backup{{nginx + keepalived 192.168.110.172}
需要关闭防火墙selinux
两台服务器安装
yum install -y nginx
yum install -y keepalived
keeplves_master服务器上的keepalived.conf配置
global_defs {
router_id keeplves_master #hostname
}
vrrp_script chk_nginx {
script "/etc/keepalived/check.sh" #检测nginx的脚本
interval 5 #每2秒检测一次
weight -20 #如果某一个nginx宕机 则权重减20
}
vrrp_instance VI_1 {
state MASTER #状态 MASTER BACKUP
interface ens33 #绑定的网卡
virtual_router_id 51 #虚拟路由的ID号,两个节点设置必须一样
mcast_src_ip 192.168.110.171 #本机的IP
priority 90
advert_int 1
# 设置验证信息,两个节点必须一致
authentication {
auth_type PASS
auth_pass 1111
}
# 虚拟IP,两个节点设置必须一样。
virtual_ipaddress {
192.168.1.138
}
# nginx存活状态检测脚本
track_script {
chk_nginx
}
}
keeplves_backup服务器上的keepalived.conf配置
global_defs {
router_id keeplves_backup #hostname
}
vrrp_script chk_nginx {
script "/etc/keepalived/check.sh" #检测nginx的脚本
interval 2 #每2秒检测一次
weight -20 #如果某一个nginx宕机 则权重减20
}
vrrp_instance VI_1 {
state BACKUP #状态 MASTER BACKUP
interface ens33 #绑定的网卡
virtual_router_id 51
mcast_src_ip 192.168.1.172
priority 40
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.138
}
track_script {
chk_nginx
}
}
nginx状态检测脚本简单写法
#!/bin/bash
A=`ps -C nginx --no-header | wc -l`
if [ $A -eq 0 ];then
systemctl stop nginx #尝试重新启动nginx
sleep 2 #睡眠2秒
if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
systemctl stop keepalived
#killall keepalived #启动失败,将keepalived服务杀死。将vip漂移到其它备份节点
fi
fi
遇到的问题
报错信息
May 22 14:43:49 keeplves_master Keepalived_vrrp[42456]: Sending gratuitous ARP on ens33 for 192.168.1.138
May 22 14:43:49 keeplves_master Keepalived_vrrp[42456]: Sending gratuitous ARP on ens33 for 192.168.1.138
May 22 14:43:49 keeplves_master Keepalived_vrrp[42456]: Sending gratuitous ARP on ens33 for 192.168.1.138
interval4 : 每4s检测一次,这里要大于监控脚本执行的时间,监控脚本会执行超时,keepalived会发送SIGTERM信号结束监控脚本的执行。
启动nginx keepalived
查看虚拟IP是否绑定192.168.1.138如果有这个IP则绑定成功
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:cc:7a:77 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.171/24 brd 192.168.1.255 scope global noprefixroute dynamic ens33
valid_lft 84406sec preferred_lft 84406sec
inet 192.168.1.138/32 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::279c:6292:4838:c6f6/64 scope link noprefixroute
valid_lft forever preferred_lft forever
停掉nginx测试
看是否会把虚拟IP主动切换到backup上
如果切换到了证明成功
实验结束
更多内容欢迎到博客讨论www.g6k.cn
不适用于生产环境