两台机器都执行yum install -y keepalived
两台机器都安装nginx,其中133上已经编译安装过nginx,134上需要yum安装nginx:
yum install -y epel-release
yum install -y nginx
> /etc/keepalived/keepalived.conf
vim /etc/keepalived/keepalived.conf
global_defs {
notification_email {
chinantfy@qq.com //接收通知邮件的邮箱
}
notification_email_from root@chinantfy.com //发送通知邮件的邮箱
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/usr/local/sbin/check_ng.sh" //检查nginx的sh路径
interval 3
}
vrrp_instance VI_1 {
state MASTER //主上为MASTER,备用上为BACKUP
interface ens33 //用哪个网卡通信
virtual_router_id 51 //主和备用一样
priority 100 //备用要比主的低
advert_int 1
authentication {
auth_type PASS
auth_pass chinantfy>com
}
virtual_ipaddress {
192.168.127.100 //设置一个公用ip
}
track_script {
chk_nginx
}
}
vim /usr/local/sbin/check_ng.sh
#!/bin/bash
#时间变量,用于记录日志
d=`date --date today +%Y%m%d_%H:%M:%S`
#计算nginx进程数量
n=`ps -C nginx --no-heading|wc -l`
#如果进程为0,则启动nginx,并且再次检测nginx进程数量,
#如果还为0,说明nginx无法启动,此时需要关闭keepalived
if [ $n -eq "0" ]; then
/etc/init.d/nginx start
n2=`ps -C nginx --no-heading|wc -l`
if [ $n2 -eq "0" ]; then
echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log
systemctl stop keepalived
fi
fi
给脚本755权限
chmod 755 /usr/local/sbin/check_ng.sh
systemctl start keepalived //133启动服务
nginx默认配置文件在
/usr/local/nginx/conf/vhost/default.conf 文件可以找到
> /etc/keepalived/keepalived.conf
vim /etc/keepalived/keepalived.conf
global_defs {
notification_email {
chinantfy@qq.com //接收通知邮件的邮箱
}
notification_email_from root@chinantfy.com //发送通知邮件的邮箱
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/usr/local/sbin/check_ng.sh" //检查nginx的sh路径
interval 3
}
vrrp_instance VI_1 {
state BACKUP //主上为MASTER,备用上为BACKUP
interface ens33 //用哪个网卡通信
virtual_router_id 51 //主和备用一样
priority 90 //备用要比主的低
advert_int 1
authentication {
auth_type PASS
auth_pass chinantfy>com
}
virtual_ipaddress {
192.168.127.100 //设置一个公用ip
}
track_script {
chk_nginx
}
}
134上编辑监控脚本
vim /usr/local/sbin/check_ng.sh
#!/bin/bash
#时间变量,用于记录日志
d=`date --date today +%Y%m%d_%H:%M:%S`
#计算nginx进程数量
n=`ps -C nginx --no-heading|wc -l`
#如果进程为0,则启动nginx,并且再次检测nginx进程数量,
#如果还为0,说明nginx无法启动,此时需要关闭keepalived
if [ $n -eq "0" ]; then
systemctl start nginx
n2=`ps -C nginx --no-heading|wc -l`
if [ $n2 -eq "0" ]; then
echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log
systemctl stop keepalived
fi
fi
chmod 755 /usr/local/sbin/check_ng.sh
> /usr/share/nginx/html/index.html //由于nginx是yum安装,所以默认配置文件路径与133不同
vim /usr/share/nginx/html/index.html
BACKUP BACKUP
systemctl start keepalived //134启动服务
master开启时,在133用ip addr 命令可以看到vip ,backup开启时在134可以查到vip,
如果切换服务失败,就检查防火墙,iptables或者selinux
原文地址:http://blog.51cto.com/13569831/2118921