如何使用keepalived实现nginx双机热备

时间:2022-12-19 09:42:28

1、linux安装方法:yum -y install keepalived

配置开机启动:sudo chkconfig  keepalived on

查看keepalivede运行日志:/var/log/messages

sudo /etc/init.d/keepalived start/restart

Usage: /etc/init.d/keepalived {start|stop|status|restart|condrestart|try-restart|reload|force-reload}

2、配置文件位置:/etc/keepalived

3、配置文件keepalived.conf分为三部分功能:

  a)global_defs:全局配置

  b)vrrp_instance:高可用配置

  c)virtual_server:负责分担配置

  d)vrrp_script:监控其他应用

本部分内容使用功能b)和功能d);使用d)监控nginx是否可用,从而决定nginx同台设备的keepalived是否可用;使用b)使两台设备通信,决定master设备

4、两台设备的keepalive的版本配置要一致(两个节点的配置基本完全一样,除了优先级主节点是100,备节点是99)

5、环境:机器A、机器B;两台机器都安装nginx(sudo yum -y install nginx)和keepalived

机器A的keepalived配置:

! Configuration File for keepalived
#下面是监控脚本 vrrp_script chk_nginx { script "/etc/keepalived/script/check_alive.sh" interval 2 #每2秒执行一次脚本 weight -2 #当脚本执行返回非0时,priority-2 } vrrp_instance appserver { state MASTER #master节点 interface eth0 virtual_router_id 150 priority 100 #优先级,如果两个设备state都为master,则根据优先级进行确定哪个为master advert_int 1 authentication { auth_type PASS auth_pass 666666 #两台设备进行通信的密码 } track_script { chk_nginx #检查脚本 } virtual_ipaddress { x.x.17.158 dev eth0 label eth0:1 #key:value VIP } }

机器B的keepalived配置:

! Configuration File for keepalived
vrrp_script chk_nginx {
        script "/etc/keepalived/script/check_alive.sh"
        interval 2
        weight -2
}
vrrp_instance appserver {
    state MASTER
    interface eth0
    virtual_router_id 150
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 666666
    }
    track_script {
    	chk_haproxy
	}
    virtual_ipaddress {
        x.x.17.158 dev eth0 label eth0:1
    }

}

脚本内容:

#!/bin/bash
if [ "$(ps -ef | grep nginx | grep -v grep | wc -l)" -eq 0 ]
then
exit 1
else
exit 0
fi

 通过查看,可以知道其中为master的设备具有VIP

如何使用keepalived实现nginx双机热备

ps:最近又发现一个坑点,使用上面的配置,需要上面的两台设备的物理IP和虚拟IP要在同一个网段。当然不在一个网段,修改配置应该可以解决。具体配置办法,遇到了再说吧