1.准备工作
master 192.168.3.7
slave 192.168.3.8
vip 192.168.3.6
2.Nginx和keepalive安装,两台node机器上操作一样
yum install nginx
yum install keepalived
加入开机启动
echo "/usr/sbin/nginx" >> /etc/rc.local
echo "/usr/sbin/keepalived start" >> /etc/rc.local
chmod +x /etc/rc.d/rc.local
3.keepalived的配置
master节点
vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id master_node
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight 20 #权重
!weight为正数
!如果脚本执行结果为0,,Master:weight+priority>Backup:weight+priority(不切换)
!如果脚本执行结果不为0,Master:priority<Backup:priority+weight(切换)
!weight为负数
!如果脚本执行结果为0,,Master:priority>Backup:priority(不切换)
!如果脚本执行结果不为0,Master:priority+weight<Backup:priority(切换)
!一般来说,weight的绝对值要大于Master和Backup的priority之差
}
vrrp_instance VI_1 {
state MASTER #Master
interface enp0s3 #绑定的网卡
virtual_router_id 51
mcast_src_ip 192.168.3.7 #本地ip
priority 100 #优先级
nopreempt
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx #nginx检测脚本
}
virtual_ipaddress {
192.168.3.6/24 #虚ip
}
}
/etc/keepalived/nginx_check.sh内容
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then
/usr/sbin/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
slave节点
state 和主不一样,是BACKUP
route_id 和主不一样
priority 小于主机
! Configuration File for keepalived
global_defs {
router_id slave_node
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight 20
!weight为正数
!如果脚本执行结果为0,,Master:weight+priority>Backup:weight+priority(不切换)
!如果脚本执行结果不为0,Master:priority<Backup:priority+weight(切换)
!weight为负数
!如果脚本执行结果为0,,Master:priority>Backup:priority(不切换)
!如果脚本执行结果不为0,Master:priority+weight<Backup:priority(切换)
!一般来说,weight的绝对值要大于Master和Backup的priority之差
}
vrrp_instance VI_1 {
state BACKUP
interface enp0s3
virtual_router_id 51
mcast_src_ip 192.168.3.8
priority 90
nopreempt
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.3.6/24
}
}
nginx_check.sh脚本内容和之前一样
4.重启keepalived测试
默认可以在 cat /var/log/messages看到keepalived日志
目前在3.7机器上,停掉keepalived服务以后,可以看到vip已经漂移到另一台机器上
通过vip访问
停止3.7服务后
基本nginx主从搭建完毕。