源码安装

  1. wget http://www.keepalived.org/software/keepalived-1.3.5.tar.gz
  2. tar -zxvf keepalived-1.3.5.tar.gz
  3. 安装openssl openssl-devel
  4. yum -y install openssl openssl-devel
  5. ./configure --prefix=/usr/local/keepalived --sbindir=/usr/sbin/ --sysconfdir=/etc/ --mandir=/usr/local/share/man/
  6. make && make install

yum安装

  1. keepalived yum安装
  2. 预先安装好epel-release
  3. yum list installed|grep epel-release
  4. 查找可用安装的keepalived
  5. yum search keepalived
  6. 命令进行安装
  7. yum install keepalived -y
  8. 启动keepalived服务
  9. systemctl start keepalived
  10. 使用yum安装的会有一个默认配置文件模板
  11. 路径为/etc/keepalived/keepalived.conf
  12. yum install ipvsadm -y

vi /etc/keepalived/keepalived.conf

  1. ! Configuration File for keepalived
  2. #简单的头部,这里主要可以做邮件通知报警等的设置,此处就暂不配置了;
  3. global_defs {
  4. #notificationd LVS_DEVEL
  5. }
  6. #预先定义一个脚本,方便后面调用,也可以定义多个,方便选择;
  7. vrrp_script chk_haproxy {
  8. script "/etc/keepalived/check_mysql.sh" #具体脚本路径
  9. interval 2 #脚本循环运行间隔
  10. }
  11. #VRRP虚拟路由冗余协议配置
  12. vrrp_instance VI_1 { #VI_1 是自定义的名称;
  13. state BACKUP #MASTER表示是一台主设备,BACKUP表示为备用设备【我们这里因为设置为开启不抢占,所以都设置为备用】
  14. nopreempt #开启不抢占
  15. interface eth0 #指定VIP需要绑定的物理网卡
  16. virtual_router_id 11 #VRID虚拟路由标识,也叫做分组名称,该组内的设备需要相同
  17. priority 129 #定义这台设备的优先级 1-254;开启了不抢占,所以此处优先级必须高于另一台
  18. advert_int 1 #生存检测时的组播信息发送间隔,组内一致
  19. authentication { #设置验证信息,组内一致
  20. auth_type PASS #有PASS 和 AH 两种,常用 PASS
  21. auth_pass asd #密码
  22. }
  23. virtual_ipaddress {
  24. 192.168.0.200 #指定VIP地址,组内一致,可以设置多个IP
  25. }
  26. track_script { #使用在这个域中使用预先定义的脚本,上面定义的
  27. chk_haproxy
  28. }
  29. #notify_backup "/etc/init.d/haproxy restart" #表示当切换到backup状态时,要执行的脚本
  30. #notify_fault "/etc/init.d/haproxy stop" #故障时执行的脚本
  31. }

检测mysql是否存活脚本check_mysql.sh

  1. mysql -h 192.168.0.11 -u root -p123456 -P 3312 -e "show status;" >/dev/null 2>&1
  2. if [ $? == 0 ]
  3. then
  4. echo " $host mysql login successfully "
  5. exit 0
  6. else
  7. echo " mysql login faild"
  8. killall keepalived
  9. exit 2
  10. fi

如果启动失败,给配置文件加权限

  1. chmod +x /etc/keepalived/check_mysql.sh
  2. chmod 644 keepalived.conf

查看keepalived日志

  1. tail -f /var/log/messages

查看IP漂移

  1. ip a

结论

主节点(权限高)挂掉后,ip会漂移到从,主节点重新启动后,ip又会漂移回主节点