俄罗斯“黑科技”——Nginx高可用的配置keepalived

俄罗斯“黑科技”——Nginx高可用的配置keepalived

Scroll Down

Nginx高可用的配置keepalived

1.什么是keepalived?

keepalived是集群管理中保证集群高可用的一个服务软件,其功能类似于heartbeat,用来防止单点故障。

2.安装

解压
yum -y install libnl libnl-devel
keepalived根目录
	./configure --prefix=/usr/local/keepalived --sysconf=/etc
make &&make install
查看keepalived
	whereis keepalived

3.配置解析

位置:/etc/keepalived/keepalived.conf

! Configuration File for keepalived
# 邮箱通知
global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   #当前安装keepalived节点主机的标识符,全局唯一的ID
   router_id LVS_DEVEL
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_instance VI_1 {
    #表示的Nginx的主节点
    state MASTER
    #网卡名称
    interface eth0
    #保证主备节点一致
    virtual_router_id 51
    #权重 优先级 如果有多个BACKUP 谁的优先级搞就选举谁为主节点
    priority 100
    #主备之间同步建成的时间间隔 默认1s
    advert_int 1
    #认证授权的密码,防止非法节点的进入
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    #虚拟IP
    virtual_ipaddress {
        192.168.200.16
        192.168.200.17
        192.168.200.18
    }
}

个人的配置:

! Configuration File for keepalived

global_defs {


   router_id KEEP130

}
vrrp_script check_nginx_is_alive{
	script "/etc/keepalived/check_nginx_is_alive.sh"
	interval 2#每隔2秒运行上一行的脚本
	weight 10 #运行成功 则审计权重+10

}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 80
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
	 track_script {
        check_nginx_is_alive
        }
    virtual_ipaddress {
      192.168.10.222
    }
}
vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 52
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
	#追踪脚本
	 track_script {
        check_nginx_is_alive
        }
    virtual_ipaddress {
      192.168.10.333
    }
}


4.注册服务到liunx

/usr/local/keepalived/keepalived-2.0.18/keepalived/etc
找到解压中的init.d/keepalived
cp init.d/keepalived /etc/init.d/
找到解压中的sysconfig/keepalived
cp sysconfig/keepalived /etc/sysconfig/
刷新服务 systemctl daemon-reload
启动 systemctl start keepalived.service

5.配置脚本检测Nginx

check_nginx_is_alive.sh

#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
#判断Nginx是否宕机,宕机尝试重启
if [ $A -eq 0 ];then
	/usr/local/nginx/sbin/nginx
	#等待一会儿再次检查Nginx,如果没有启动成功 则停止keepalived 备用机启动
	sleep 3
	if [`ps -C nginx --no-header |wc -l` -eq 0];then
		killall keepalived
	fi
fi