配置keepalived支持nginx高可用

实验环境

序号 主机名 IP地址
1 nginx1 192.168.204.11
2 nginx2 192.168.204.12

安装nginx

安装nginx

yum install -y epel-*
yum install -y nginx

编写HTML文件
nginx1上

echo -e "nginx1" > /usr/share/nginx/html/index.html

nginx2上

echo -e "nginx2" > /usr/share/nginx/html/index.html

启动nginx

systemctl start nginx
systemctl enable nginx
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload

访问浏览器

安装配置keepalived

1.安装keepalived

yum install keepalived -y

2.在nginx1上配置keepalived
修改配置文件

vim /etc/keepalived/keepalived.conf

启动

systemctl start keepalived
systemctl enable keepalived

3.在nginx2上配置keepalived
修改配置文件

vim /etc/keepalived/keepalived.conf

启动

systemctl start keepalived
systemctl enable keepalived

4.在宿主机ping 192.168.204.10,使用arp -a查看缓存

5.浏览器访问虚拟地址

6.在nginx1上宕掉ens33网卡

在宿主机使用arp -a查看缓存

在主机使用浏览器访问虚拟地址

可以看到,对192.168.204.10的请求已从nginx1节点转移到了nginx2节点

配置keepalived支持nginx高可用

1.编写NGINX状态监测脚本

编写脚本/etc/keepalived/nginx_check.sh

#!/bin/bash
# file:/etc/keepalived/nginx_check.sh
N=`ps -C nginx --no-header | wc -l`
if [ $N -eq 0 ]; then
    systemctl restart nginx
    sleep 2
    if [ `ps -C nginx --no-header | wc -l` -eq 0 ]; then
        killall keepalived
    fi
fi

赋予可执行权限

chmod +x /etc/keepalived/nginx_check.sh

测试脚本

2.配置keepalived支持NGINX高可用

在nginx1节点上编辑/etc/keepalived/keepalived.conf

vim /etc/keepalived/keepalived.conf

重新启动keepalived

systemctl restart keepalived

3.测试高可用

浏览器访问虚拟地址

在nginx1节点运行stop.sh脚本,然后使用浏览器访问虚拟地址

#!/bin/bash
# file:stop.sh
for ((i=0; i<=100; i++))
do
    systemctl stop nginx
    echo 'stoped. sleep 1s...'
    sleep 1
done

本文链接: https://www.cnblogs.com/connect/p/nginx-keepalived-high-availability.html

原文地址:https://www.cnblogs.com/connect/p/nginx-keepalived-high-availability.html