Nginx高可用

高可用原理

客户端通过虚拟IP访问服务器,默认通过主Nginx代理服务器访问真实服务器,当主nginx代理服务器宕机自动切换到备nginx代理服务器上去。

参考资料: keepalive详解

主从模式集群案例

两台Nginx服务器,分别为10.154.0.111和10.154.0.112

1、安装Nginx,可参考: 编译安装Nginx

2、在两台nginx代理服务器上安装keepalive软件

$ yum -y install keepalived

#查看是否安装
$ rpm -q -a keepalived

配置文件路径在/etc/keepalived/keepalived.conf

3、编辑keepalived.conf配置文件

在主代理服务器10.154.0.111配置文件如下

$ cat /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 127.0.0.1
   smtp_connect_timeout 30
   router_id client1

}
#注意大括号要换行且顶行写
vrrp_script chk_http_port
{
    script "/usr/local/src/nginx_check.sh"
    interval 1
    weight -2
}

vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
       #注意查看网卡名称
        10.154.0.110/24 brd 10.154.0.110 dev ens33 label ens33:0
    }
track_script {
 chk_http_port
}
}


在备代理服务器10.154.0.112配置文件如下

$ cat /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 127.0.0.1
   smtp_connect_timeout 30
   router_id client2

}

vrrp_script chk_http_port
{
   script "/usr/local/src/nginx_check.sh"
   interval 1  
   weight 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens34
    virtual_router_id 51
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
       #client2的网卡名称为ens34,使用ifconfig查看
        10.154.0.110/24 brd 10.154.0.110 dev ens34 label ens34:0
    }
}

参考资料:脚本不能执行

4、nginx_check.sh脚本文件内容如下
需要在两台nginx代理服务器上部署

$ cat /usr/local/src/nginx_check.sh
#!/bin/sh
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then
	if [ $A -eq 0 ];then
		killall keepalived
	fi
fi

参考:脚本为何不能执行1
脚本为何不能执行2

5、其他配置

#启动nginx
$ nginx

#关闭selinux
$ setenforce 0

#启动keepalived
$ systemctl start keepalived

6、效果
在主nginx代理服务器上使用ifconfig可查看虚拟网卡已启用

停用主nginx代理服务的nginx服务,页面能正常访问

此时已切换到备nginx服务器,查看此时备服务器的ifconfig为


学习来自:YJ.li老师博客,nginx详解高级课程P14-16

posted @ 2021-01-15 01:38  努力吧阿团  阅读(155)  评论(0)    收藏  举报