1.keepalived的安装与配置
负载均衡lb01:
yum install keepalived -y
vim /etc/keepalived/keepalived.conf
-------------/etc/keepalived/keepalived.conf---------------
global_defs {
router_id lb01
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 50
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
}
------------/etc/keepalived/keepalived.conf结束-------------
systemctl enable keepalived
systemctl start keepalived
负载均衡lb02:
yum install keepalived -y
vim /etc/keepalived/keepalived.conf
-------------/etc/keepalived/keepalived.conf---------------
global_defs {
router_id lb02
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 50
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
}
------------/etc/keepalived/keepalived.conf结束-------------
systemctl enable keepalived
systemctl start keepalived
2.keepalived高可用地址漂移测试
[root@lb01 ~]# ip addr | grep 10.0.0.3
#尝试停止master的keeplaived
[root@lb01 ~]# systemctl stop keepalived
在slave上查看是否有对应的VIP
[root@lb02 ~]# ip addr|grep 10.0.0.3
inet 10.0.0.3/32 scope global eth0
master故障,backup接管,master恢复后会抢占VIP。
3.keepalived高可用非抢占式
配置非抢占式步骤如下
1、两个节点的state都必须配置为BACKUP(官方建议)
2、两个节点都在vrrp_instance中添加nopreempt参数
3、其中一个节点的优先级必须要高于另外一个节点的优先级。
两台服务器都角色状态启用nopreempt后,必须修改角色状态统一为BACKUP,唯一的区分就是优先级。
#Master
vrrp_instance VI_1 {
state BACKUP
priority 150
nopreempt
}
#Backup
vrrp_instance VI_1 {
state BACKUP
priority 100
nopreempt
}
4.VIP在什么时候会漂移?
1. keepalived服务停止了,地址就会漂移。
2. 服务器直接关机、重启了,地址会漂移。
Nginx如果故障停止了,那么希望VIP漂移到另外一台节点。判断Nginx是否存活,如果存活则不处理。如果不存活,尝试1~3次,强制杀掉keeplaived。
mkdir /server/scripts -p
vim /server/scripts/check_web.sh
------------/server/scripts/check_web.sh---------------
#!/bin/sh
nginxpid=$(ps -C nginx --no-header|wc -l)
#1.判断nginx是否存活,如不存活则尝试启动nginx
if [ $nginxpid -eq 0 ];then
systemctl start nginx
sleep 3
#2.等待3秒后再次获取一次Nginx状态
nginxpid=$(ps -C nginx --no-header|wc -l)
#3.再次进行判断, 如Nginx还不存活则停止Keepalived,让地址进行漂移,并退出脚本
if [ $nginxpid -eq 0 ];then
systemctl stop keepalived
fi
fi
-----------/server/scripts/check_web.sh结束-------------
chmod +x /server/scripts/check_web.sh
vim /etc/keepalived/keepalived.conf
------------/etc/keepalived/keepalived.conf--------------
vrrp_script check_web { #定义一个脚本check——web
script "/server/scripts/check_web.sh" #定义该脚本的路径
interval 5 #定义每5秒知行一次
}
vrrp_instance VI_1 {
state BACKUP
priority 150
nopreempt
interface eth0
virtual_router_id 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3
}
#调用脚本,并运行该脚本
track_script { #调用脚本
check_web
}
}
-----------/etc/keepalived/keepalived.conf结束------------