Nginx之Keepalived高可用

时间:2022-12-19 10:56:04

原文地址:http://blog.csdn.net/uq_jin/article/details/51907837

规划

主机名 ip 安装的软件
master 192.168.2.110 Nginx、Keepalived
slave1 192.168.2.111 Nginx、Keepalived
虚拟IP 192.168.2.112

安装keepalived

yum install -y keepalived

Nginx之Keepalived高可用

修改配置文件(192.168.2.110)

备份配置文件

cd /etc/keepalived
cp keepalived.conf keepalived.conf.bak

修改配置文件

vi 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
router_id nginx_server_1
}

vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -5
}

vrrp_instance VI_1 {
state MASTER
interface eno16777736
virtual_router_id 51
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.2.112
}
track_script {
chk_nginx
}
}

要修改的参数:

router_id 、interface 、priority 、track_script

参数说明参考:https://segmentfault.com/a/1190000002881132

其中interface的设置可以使用 ip addr 查看

Nginx之Keepalived高可用

创建脚本文件

vi check_nginx.sh
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
exit 1
else
exit 0
fi

给脚本文件添加执行权限

chmod +x check_nginx.sh

拷贝配置文件(192.168.2.111)

拷贝配置文件

先在192.168.2.111安装Keepalived,

scp keepalived.conf root@192.168.2.111:/etc/keepalived/
scp check_nginx.sh root@192.168.2.111:/etc/keepalived/

修改配置文件

vi keepalived.conf
router_id nginx_server_1  --> router_id nginx_server_2
state MASTER --> state BACKUP
priority 101 --> priority 100

测试

防火墙设置

一、直接关闭防火墙:

关闭防火墙
systemctl stop firewalld.service
关闭开机启动
systemctl disable firewalld.service

二、开发IP

firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 0 --in-interface eno16777736 --destination 224.0.0.18 --protocol vrrp -j ACCEPT
firewall-cmd --reload

启动Nginx

在两台机器上启动,并测试

 /opt/soft/nginx-1.10.0/sbin/nginx 

分别启动Keepalived

systemctl restart keepalived.service

通过ip addr 查看

主机192.168.2.110

Nginx之Keepalived高可用

主机192.168.2.111

Nginx之Keepalived高可用

这时停止110主机的Nginx再次查看:

主机192.168.2.110

Nginx之Keepalived高可用

主机192.168.2.111

Nginx之Keepalived高可用

可以看的 虚拟IP 自动切换到主机111 上了。

这样就算挂掉一台主机,我们的另一台主机都会切换过来实现 Nginx的高可用,

在重新启用110的Nginx后会自动切换过来,在MASTER节点的 vrrp_instance 中 配置 nopreempt ,当它异常恢复后,即使它 prio 更高也不会抢占,这样可以避免正常情况下做无谓的切换