Leo_zhou

练习时长八年半的运维工程师

Nginx+keepalived搭建实现HA功能

前言
单独的nginx作为web代理服务器可以满足一定时间段的需求,但如果遇上大并发的时候就需要考虑可靠的nginx架构,keepalived可以实现ha的功能,即主备功能,避免单点故障。

架构
nginx-122.119.181.100,122.119.181.101(两台服务器需要同时搭建nginx以及keepalived,不过keepalived是要分主次)。
vip-122.119.181.120(虚拟的IP地址,提供给客户访问,然后VIP会分发到对应下的nginx)。
后端-通过nginx的upstream功能实现后端的负载均衡。

安装
nginx-可以通过编译安装或者yum安装
keepalived-同样可以使用yum或者编译安装

配置
keepalived核心点-yum安装后默认在/etc/keepalived/keepalived.conf
master配置

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
   router_id LVS_DEVEL
}
vrrp_script check_ng {
        script "/opt/app/web/nginx/checknginx.sh"
        interval 2
}

vrrp_instance VI_1 {
    state MASTER   #区分主次标签
    interface eth0   #绑定对应的网卡接口
    virtual_router_id 51   #固定路由编号,需要和BACKUP保持一致
    mcast_src_ip 122.119.181.100 #本地的IP地址
    priority 100  #分发的权限,如果只有2台意义不大
    advert_int 1
    authentication {
        auth_type PASS  #设置账号密码
        auth_pass zhouzhifei
    }
    virtual_ipaddress {
        122.119.181.120/24 dev eth0 label eth0:1 #虚拟IP地址绑定对应的网卡
    }
    track_script {
         check_ng
            }         
}

BACKUP配置

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
   router_id LVS_DEVEL
}
vrrp_script check_ng {
        script "/opt/app/web/nginx/checknginx.sh"
        interval 2
}
vrrp_instance VI_1 {
    state BACKUP
    interface eth1
    virtual_router_id 51
    mcast_src_ip 122.119.181.101
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass zhouzhifei
    }
    virtual_ipaddress {
122.119.181.120/24 dev eth1 label eth1:1
    }
    track_script {
         check_ng
                  } 
}

基础nginx检测脚本

#!/bin/bash
run=`ps -C nginx --no-header | wc -l`
if [ $run -eq 0 ];then
     /opt/app/web/nginx/sbin/nginx -s stop
     /opt/app/web/nginx/sbin/nginx
     sleep 3
     if [ `ps -C nginx --no-header | wc -l` ];then
        killall keepalived
     fi
fi

思考
当mater恢复后,如何从BACKUP自动切换到MASTER?

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注