Linux keepalived+nginx实现主从模式

双机高可用方法目前分为两种:
  主从模式:一台主服务器和一台从服务器,当配置了虚拟vip的主服务器发送故障时,从服务器将自动接管虚拟ip,服务将不会中断。但主服务器不出现故障的时候,从服务器永远处于浪费状态,对于服务器不多的网站,该方案不经济实惠。
  主主模式:开启两个虚拟服务,一台服务器这个虚拟组A中设置为主节点,另一台服务器在虚拟组B中设置为主节点,这样就有两个虚拟IP,两个机器都是主节点,也都是从节点,当一台机器故障了,非故障机器就会拥有两个虚拟ip,也会负担所有的请求。

主从环境

  VIP:172.30.100.8

  keepalived+nginx1(主):172.30.100.126

  keepalived+nginx1(备):172.30.100.127

服务检测策略

  对于nginx服务状态检测的方式是脚本检测,当nginx进程为0时,会尝试着启动nginx服务;如果启动失败,则停止keepalived服务,这样虚拟VIP会漂移到从节点。

  脚本中sleep的时间一定要小于keepalived的配置文件中脚本执行间隔时间。

#!/bin/bash  
NGX_STATUS=`ps -C nginx –no-header |wc -l`  
if [ $NGX_STATUS -eq 0 ];then  
    /app/nginx/sbin/nginx  
    sleep 1
    if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then  
        systemctl stop keepalived
    fi  
fi

主节点配置

! Configuration File for keepalived

# 全局配置
global_defs {
   notification_email {
     root@localhost.localdomain
   }
   notification_email_from root@localhost.localdomain
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id LVS1
   vrrp_skip_check_adv_addr
   #vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
   vrrp_mcast_group4 224.18.18.18
}

# 检测脚本配置参数
vrrp_script chk_ngx {
   script "/etc/keepalived/nginx_check.sh"
   interval 2
   weight -20
}

# 设置虚拟服务
vrrp_instance VI1 {
    state MASTER
    interface eth0
    virtual_router_id 111
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
        chk_ngx
    }
    virtual_ipaddress {
        172.30.100.8
    }
}

从节点配置

! Configuration File for keepalived

global_defs {
   notification_email {
     root@localhost.localdomain
   }
   notification_email_from root@localhost.localdomain
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id LVS2
   vrrp_skip_check_adv_addr
   #vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
   vrrp_mcast_group4 224.18.18.18
}

vrrp_script chk_ngx {
   script "/etc/keepalived/nginx_check.sh"
   interval 2
   weight -20
}

vrrp_instance VI1 {
    state SLAVE
    interface eth0
    virtual_router_id 111
    priority 70
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
        chk_ngx
    }
    virtual_ipaddress {
        172.30.100.8
    }
}
原文地址:https://www.cnblogs.com/houyongchong/p/10552868.html