安装keepalive
安装依赖插件:
yum install -y gcc openssl-devel popt-devel
wget -q http://www.keepalived.org/software/keepalived-1.2.13.tar.gz tar -zxvf keepalived-1.2.13.tar.gz cd keepalived-1.2.13 ./configure && make && make install cp /usr/local/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/ cp /usr/local/etc/sysconfig/keepalived /etc/sysconfig/ mkdir /etc/keepalived cp /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/ cp /usr/local/sbin/keepalived /usr/sbin/ chkconfig --add keepalived chkconfig --level 345 keepalived on
在master 主机上的配置
cat /etc/keepalived/keepalived.conf vrrp_script chk_mysql_port { #检测mysql服务是否在运行。有很多方式,比如进程,用脚本检测等等 script "/opt/chk_mysql.sh" #这里通过脚本监测 interval 2 #脚本执行间隔,每2s检测一次 weight -5 #脚本结果导致的优先级变更,检测失败(脚本返回非0)则优先级 -5 fall 2 #检测连续2次失败才算确定是真失败。会用weight减少优先级(1-255之间) rise 1 #检测1次成功就算成功。但不修改优先级 } vrrp_instance VI_1 { state MASTER interface ens33 #指定虚拟ip的网卡接口,不一定是eth0根据ifconfig确定 virtual_router_id 51 #路由器标识,MASTER和BACKUP必须是一致的 priority 100 #定义优先级,数字越大,优先级越高,在同一个vrrp_instance下,MASTER的优先级必须大于BACKUP的优先级。这样MASTER故障恢复后,就可以将VIP资源再次抢回来 advert_int 1 authentication { auth_type PASS auth_pass 123456 } virtual_ipaddress { 192.168.11.25 } track_script { chk_mysql_port } }
在slave上的配置
cat /etc/keepalived/keepalived.conf vrrp_script chk_mysql_port { script "/opt/chk_mysql.sh" interval 2 weight -5 fall 2 rise 1 } vrrp_instance VI_1 { state BACKUP interface ens33 virtual_router_id 51 priority 99 advert_int 1 authentication { auth_type PASS auth_pass 123456 } virtual_ipaddress { 192.168.11.25 } track_script { chk_mysql_port } }
检测脚本的配置
cat /opt/chk_mysql.sh #!/bin/bash counter=$(netstat -na|grep "LISTEN"|grep "3306"|wc -l) if [ "${counter}" -eq 0 ] then ## /etc/init.d/keepalived stop
service keepalived stop else echo "running..." >> /opt/keepalived-running-info.log sleep 5000 fi
注:
chk_mysql.sh 这个文件要有执行权限 chom -x chk_mysql.sh
要安装netstat 这个命令
# 在master和slave上执行 //sudo /etc/init.d/keepalived start
service keepalived start //keepalived启动
service keepalived stop //keepalive 停止