1、抢占模式(默认)
- MASTER上的nginx挂了,BACKUP会成为新的MASTER,MASTER上的nginx启动后,BACKUP会恢复备的角色。
- 正式环境不要有注释,也不要有多余空格,脚本要有执行权限,查看日志是/var/log/message
(1) MASTER
# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalivedglobal_defs {router_id 10.4.7.11 # 主备不能相同enable_script_security # 启用脚步安全script_user root # 设置脚步执行用户
}
vrrp_script chk_nginx {script "/etc/keepalived/check_port.sh 7443" # 检测脚本并给脚本传参 7443是nginx端口interval 2weight -20
}vrrp_instance VI_1 {state MAKSTER # 这是主interface ens33 # 网卡名virtual_router_id 251 # 主备需要相同priority 100 # 主优先级要高于备advert_int 1authentication {auth_type PASSauth_pass 1111}track_script {chk_nginx # 跟踪脚本状态与上面的vrrp_script名称一致}virtual_ipaddress { # 虚拟ip10.4.7.10}
}# BACKUP
# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalivedglobal_defs {router_id 10.4.7.12 # 主备不能相同enable_script_security # 启用脚步安全script_user root # 设置脚步执行用户
}vrrp_script chk_nginx {script "/etc/keepalived/check_port.sh 7443"interval 2weight -20
}vrrp_instance VI_1 {state BACKUPinterface ens33virtual_router_id 251priority 90advert_int 1authentication {auth_type PASSauth_pass 1111}track_script {chk_nginx}virtual_ipaddress {10.4.7.10}
}# check_port.sh
#!/bin/bash
CHK_PORT=$1
if [[ -n ${CHK_PORT} ]]
thenPORT_PROCESS=`ss -lnt |grep ${CHK_PORT}|wc -l`if [[ ${PORT_PROCESS} -eq 0 ]]thenecho "Port ${CHK_PORT} is not used,End."exit 1fi
elseecho "Check Port Cant be empty!"
fi# chmod +x /etcd/keepalived/check_port.sh
2、非抢占模式 (生产环境推荐使用)
- master上的nginx挂了backup会成为新的master,master上的nginx起来后并不会把主的角色抢占过来,需要去backup上重启keepalived才能让主的角色重新回到master。
- 正式环境不要有注释内容,不要有多余空格,脚本要有执行权限,查看日志是 /var/log/message
# MASTER
# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalivedglobal_defs {router_id 10.4.7.11enable_script_security # 启用脚步安全script_user root # 设置脚步执行用户
}vrrp_script chk_nginx {script "/etc/keepalived/check_port.sh 7443"interval 2weight -20
}vrrp_instance VI_1 {state MAKSTERinterface ens33virtual_router_id 251nopreempt # master上需要配置非抢占模式priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}track_script {chk_nginx}virtual_ipaddress {10.4.7.10}
}#backup
# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalivedglobal_defs {router_id 10.4.7.12enable_script_security # 启用脚步安全script_user root # 设置脚步执行用户
}vrrp_script chk_nginx {script "/etc/keepalived/check_port.sh 7443"interval 2weight -20
}vrrp_instance VI_1 {state BACKUPinterface ens33virtual_router_id 251priority 90advert_int 1authentication {auth_type PASSauth_pass 1111}track_script {chk_nginx}virtual_ipaddress {10.4.7.10}
}# 脚本内容
# cat /etc/keepalived/check_port.sh
#!/bin/bash
#该脚本检测7443端口是否存在,如果不存在则退出该脚本CHK_PORT=$1
if [[ -n ${CHK_PORT} ]]
thenPORT_PROCESS=`ss -lnt |grep ${CHK_PORT}|wc -l`if [[ ${PORT_PROCESS} -eq 0 ]]thenecho "Port ${CHK_PORT} is not used,End."exit 1fi
elseecho "Check Port Cant be empty!"
fi# chmod +x /etc/keepalived/check_port.sh