学习自:https://www.nhooo.com/note/qa3jz9.html
最终效果
主从两个节点都安装nginx与keepalived,安装到相同路径
安装Nginx
点此:https://www.jianshu.com/p/1a51f2384c11
安装keepalived
下载安装包:https://www.keepalived.org/download.html
# tar命令解压
# 进入解压后目录
./configure --prefix=/usr/local/keepalived
make && make install
将配置文件拷贝到系统对应的目录下
mkdir /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/keepalived
核心keepalived配置文件
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id ngkp1 # 主从节点不一致即可
script_user root
}
vrrp_script nginx_check {
script "/etc/keepalived/nginx_check.sh" ## 检测 nginx 状态的脚本路径
interval 5 ## 检测时间间隔
#weight -20 ## 如果条件成立,权重-20
}
vrrp_instance VI_1 {
state MASTER ## 必填,MASTER或BACKUP,可以不一致,也可以一致
interface ens16 ## 网卡名称
virtual_router_id 51 # 主从节点中保持一致
unicast_src_ip xx.xx.6.1 #本机IP
unicast_peer {
xx.xx.6.2 # 对方机器IP
}
priority 100 # 主从不要一致,主比从大
advert_int 1
authentication {
auth_type PASS # 主从节点中保持一致
auth_pass 111111 # 主从节点中保持一致
}
track_script {
nginx_check ## 执行 Nginx 监控的服务
}
virtual_ipaddress {
xx.xx.6.20/24 dev ens16 # 虚拟IP
}
}
Nginx监控脚本
vim /etc/keepalived/nginx_check.sh
#!/usr/bin/bash
counter=$(ps -C nginx --no-heading|wc -l) # 检查nginx进程数
if [ $counter -eq 0 ]; then
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf # 如果进程数等于0,则尝试对nginx进行重启操作
sleep 1 # 等待一秒时间
cnt=$(ps -C nginx --no-heading|wc -l) #再次检查nginx进程数
if [ $cnt -eq 0 ]; then
systemctl stop keepalived # 如果还等于0,则停止掉keepalived进程,实现虚拟IP漂移到从节点,由从节点的nginx继续提供服务
fi
fi
标签:etc,##,Keepalived,keepalived,Nginx,usr,nginx,主从
From: https://www.cnblogs.com/tshuai/p/17781306.html