keepalived+nginx+应用
达到的效果就是,每个keepalived中都有一个weight,这个数最大的作为主节点。意外挂掉就另一个升为leader,比如开始一个6,一个5,挂一次这个数减2。6挂一次再启动就是5,4了,两台机器以同一个VIP(虚IP)访问。
要写一个循环检测的脚本check_nginx.sh
,看keepalived的状态,如下:
sudo cat >/etc/keepalived/check_nginx.sh<<‐'EOF' #!/bin/bash counter=$(ps ‐C nginx ‐‐no‐heading|wc ‐l) if [ "${counter}" = "0" ]; then systemctl start nginx sleep 2 counter=$(ps ‐C nginx ‐‐no‐heading|wc ‐l) if [ "${counter}" = "0" ]; then systemctl stop keepalived fi fi EOF
然后给check_nginx.sh 增加权限
chmod 755 /etc/keepalived/check_nginx.sh
然后是keepalived master 配置:
# 全局配置,路由ID,固定不变 global_defs { router_id LVS_DEVEL } # 定义Nginx状态脚本 vrrp_script chk_nginx { script "/etc/keepalived/check_nginx.sh" # 间隔时间,单位为秒,默认1秒 interval 2 # 权重,当脚本成功或失败对当前节点的优先级是增加还是减少 weight ‐5 } #VRRP实例 vrrp_instance VI_1 { # 主节点 state MASTER # 绑定的网卡,使用ifconfig命令查看获取 interface ens33 # 虚拟路由id,保证相同 virtual_router_id 51 # 优先级,抢占模式下优先级高的称为主 priority 84 # 指定发送VRRP通告的间隔。单位是秒。 advert_int 2 # 安全认证用的密码,自定义即可 authentication { auth_type PASS auth_pass 1111 } # 对外暴露的VIP地址 virtual_ipaddress { *.*.*.* } # 指定Nginx执行状态脚本 track_script { chk_nginx } }
然后是keepalived slave配置:
global_defs { router_id LVS_DEVEL } vrrp_script chk_nginx { script "/etc/keepalived/check_nginx.sh" interval 2 weight ‐5 } vrrp_instance VI_1 { # 初始角色Backup state BACKUP interface *.*.*.* virtual_router_id 51 # 优先级比master低 priority 100 advert_int 2 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { *.*.*.* } track_script { chk_nginx } }
然后可以停掉master,VIP不影响访问,参考文章地址:https://www.jianshu.com/p/6658257abb65