安装 keepalived + nginx

192.209.233.104 nginx01

192.209.233.105 nginx02

192.168.200.18 vip

1、安装软件
yum -y install keepalived ipvsadm
2、配置nginx01
cat > /etc/keepalived/keepalived.conf <<EOF
global_defs {
   router_id LB01
}

vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight -20
    fall 2
    rise 1
}

vrrp_instance nginx {
    state BACKUP
    interface enp3s0
    virtual_router_id 51
    priority 200
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    nopreempt
    track_script {
        chk_nginx
    }
    virtual_ipaddress {
        192.168.200.18
    }
}
EOF

check_nginx.sh

cat > /etc/keepalived/nginx_check.sh <<EOF
#!/bin/bash
nginxpid=\`ps -C nginx --no-header | wc -l\`
if [ \$nginxpid -eq 0 ];then
    systemctl restart nginx
    sleep 2
    nginxpid=\`ps -C nginx --no-header | wc -l\`
    if [ \$nginxpid -eq 0 ];then
        systemctl stop keepalived
    fi
fi
EOF
chmod +x /etc/keepalived/nginx_check.sh
systemctl  restart  keepalived
3、配置nginx02

重复2、步骤即可,keepalived配置文件需要修改几个地方

router_id LB02
4、查看vip
ip a |grep vip

高可用测试,分别关闭keepalived服务,再看vip是否漂移

5、主nginx配置文件变化时自动同步到从nginx

主备nginx之间提前做好免密认证

主nginx上

rpm -ivh inotify-tools-3.14-19.el8.aarch64.rpm
yum -y install rsync
cat >/etc/keepalived/nginx_conf_sync.sh <<EOF
#!/bin/bash

watchdir="/usr/local/nginx/conf/"
inotifywait -mr -e MODIFY,DELETE,CREATE,ATTRIB,MOVE \$watchdir |  
while  read -r dir event file; do  
    echo  \`date +'%F %T'\` "The file \$file in directory \$dir was \$event"  
    rsync -avz -e 'ssh -p 22' --delete \$watchdir 10.209.233.105:\${watchdir}
done
EOF
cd /etc/keepalive
nohup sh nginx_conf_sync.sh >> nginx_conf_sync.log &
6、从nginx配置文件变化时自动reload

从nginx上

rpm -ivh inotify-tools-3.14-19.el8.aarch64.rpm
yum -y install rsync
cat >/etc/keepalived/monitor_nginx_conf_autoreload.sh <<EOF
#!/bin/bash

watchdir="/usr/local/nginx/conf/"
inotifywait -mr -e MODIFY,DELETE,CREATE,ATTRIB,MOVE \$watchdir |  
while  read -r dir event file; do  
    echo  \`date +'%F %T'\` "The file \$file in directory \$dir was \$event"  
    /usr/local/nginx/sbin/nginx -s reload
done
EOF
cd /etc/keepalive
nohup sh monitor_nginx_conf_autoreload.sh >> monitor_nginx_conf_autoreload.log &