1、安装keepalived
yum install -y keepalived
设置开机自启动
systemctl enable keepalived.service
2、修改配置文件
(1)主配置文件
vim /etc/keepalived/keepalived.conf
global_defs { router_id keep_01 } vrrp_script chk_nginx { script "/etc/keepalived/check_nginx.sh" interval 5 weight -20 } vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 150 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.1.144/24 dev eth0 label eth0:1 } track_script { chk_nginx } }
(2)备配置文件
global_defs { router_id keep_02 } vrrp_script chk_nginx { script "killall -0 nginx" script "/etc/keepalived/check_nginx.sh" interval 5 weight -20 } vrrp_instance VI_1 { state BACKUP interface eth0 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.1.144/24 dev eth0 label eth0:1 } track_script { chk_nginx } }
(3)主、备 添加Nginx状态监测脚本
#!/bin/bash A=`ps -C nginx --no-header | wc -l` if [ $A -eq 0 ];then /usr/local/nginx/sbin/nginx sleep 2 if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then pkill keepalived fi fi
(4)启动或者重启keepalived服务
systemctl restart keepalived
3、验证
(1)通过虚拟IP访问
(2)停掉nginx,脚本会在两秒后自动执行监测nginx,然后启动,如果只停掉主的keepalived服务,就会出现脑裂情况,所以这里为了不出现这些情况,我停掉主服务器来验证
(3)如果还不不相信自己做成功,用抓包工具wireshark来验证