防火墙 selinux 先都确保是关闭的
# tar xf keepalived-2.0.17.tar.gz
# cd keepalived-2.0.17
# ./configure --prefix=/usr/local/keepalived
# make && make install
# mkdir /etc/keepalived
# cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/
主配置文件
! Configuration File for keepalived global_defs { router_id LVS_DEVEL } vrrp_script check_run { script "/mysql_check.sh" interval 2 fail 3 } vrrp_sync_group VG1 { group { VI_1 } } vrrp_instance VI_1 { state BACKUP nopreempt # 设置为不抢占 interface ens33 # ens33以实际为准 virtual_router_id 51 priority 100 # 优先级高者为主 unicast_src_ip 192.168.1.14 # 配置单播的源地址 unicast_peer { 192.168.1.15 # 配置单播的目标地址 } advert_int 1 authentication { auth_type PASS auth_pass 1418 } track_script { check_run } virtual_ipaddress { 192.168.1.16 # VIP } }
从配置文件
! Configuration File for keepalived global_defs { router_id LVS_DEVEL } vrrp_script check_run { script "/mysql_check.sh" interval 2 fail 3 } vrrp_sync_group VG1 { group { VI_1 } } vrrp_instance VI_1 { state BACKUP nopreempt # 设置为不抢占 interface ens33 # ens33以实际为准 virtual_router_id 51 priority 90 # 优先级低者为从 unicast_src_ip 192.168.1.15 # 配置单播的源地址 unicast_peer { 192.168.1.14 #配置单播的目标地址 } advert_int 1 authentication { auth_type PASS auth_pass 1418 } track_script { check_run } virtual_ipaddress { 192.168.1.16 # VIP } }
mysql检查脚本
#!/bin/bash count=$(ps -C mysqld --no-heading |wc -l) if [ "${count}" = "0" ]; then #尝试启动一次mysqld,停止3秒后再次检测 systemctl restart mysqld #/etc/init.d/mysqld restart sleep 3 count=$(ps -C mysqld --no-heading |wc -l) if [ "${count}" = "0" ]; then #如果启动没成功,就停止keepalived触发主备切换 systemctl stop keepalived fi fi
nginx检查脚本
#!/bin/bash count=$(ps -C nginx --no-heading |wc -l) if [ "${count}" = "0" ]; then systemctl restart nginx #/etc/init.d/nginx restart sleep 3 count=$(ps -C nginx --no-heading |wc -l) if [ "${count}" = "0" ]; then systemctl stop keepalived fi fi