1. 环境说明
操作系统 | IP地址 | 角色说明 |
---|---|---|
CentOS7 | 172.16.120.101 vip:172.16.1.100 | master |
CentOS7 | 172.16.120.102 vip:172.16.1.100 | backup |
2. Master部署
nginx安装见:https://blog.51cto.com/7965676/2629308
yum install -y keepalived
vim /etc/keepalived/keepalived.conf
global_defs {
router_id NGINX_DEVEL
}
#定义脚本的名称为check_nginx
vrrp_script check_nginx {
#script后面可以直接接shell命令或一个可执行脚本
script "/etc/keepalived/nginx_pid.sh"
#定义执行间隔为2秒
interval 2
#失败次数为2次
fall 2
#检测1次成功就算成功
rise 1
}
vrrp_instance nginx {
state MASTER
interface ens33
#定义发送vrrp广播的源地址
mcast_src_ip 172.16.120.101
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
#执行监控的服务
track_script {
#引用VRRP脚本
check_nginx
}
virtual_ipaddress {
172.16.1.100/24
}
}
3. Backup部署
nginx安装见:https://blog.51cto.com/7965676/2629308
yum install -y keepalived
vim /etc/keepalived/keepalived.conf
global_defs {
router_id NGINX_DEVEL
}
vrrp_script check_nginx {
script "/etc/keepalived/nginx_pid.sh"
interval 2
fall 2
rise 1
}
vrrp_instance nginx {
state BACKUP
interface ens33
mcast_src_ip 172.16.120.102
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_nginx
}
virtual_ipaddress {
172.16.1.100/24
}
}
4. 编写脚本
vim /etc/keepalived/nginx_pid.sh
#!/bin/bash
nginx_check () {
nginxpid=`ps -C nginx --no-header |wc -l`
if [ $nginxpid -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 1
nginxpid=`ps -C nginx --no-header |wc -l`
if [ $nginxpid -eq 0 ];then
systemctl stop keepalived
fi
fi
}
nginx_check
5. 启动服务
systemctl start keepalived
systemctl enable keepalived