1、下载keepalived安装包
2、解压安装
tar -zxvf keepalived-2.0.4.tar.gz -C /usr/local
cd /usr/local/keepalived-2.0.4
./configure --prefix=/usr/local/keepalived-2.0.4
make && make install
3、将keepalived安装成linux系统服务
#新建文件夹
mkdir /etc/keepalived
#将配置文件放到默认路径下
cp /usr/local/keepalived-2.0.4/etc/keepalived/keepalived.conf /etc/keepalived/
#去keepalived源码目录下拷贝启动脚本到/etc/init.d/下
cp /usr/local/keepalived-2.0.4/etc/init.d/keepalived /etc/init.d
#keepalived启动脚本变量引用文件
cp /usr/local/keepalived-2.0.4/etc/sysconfig/keepalived /etc/sysconfig/
ln -s /usr/local/keepalived-2.0.4 /usr/sbin
ln -s /usr/local/keepalived-2.0.4/sbin/keepalived /sbin
4、设置keepalived开机自启
chkconfig keepalived on
5、修改keepalived配置文件(详解)
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id LVS_DEVEL
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_script check_nginx {
script "/usr/local/keepalived-2.0.4/nginx_check.sh" #检测nginx状态的脚本路径
interval 3 #检测时间间隔
weight -2 #如果条件成立,权重-20
}
vrrp_instance VI_1 { #定义虚拟路由,用来定义对外提供服务的VIP区域及其相关属性
state MASTER #主节点为MASTER,对应的备份节点为BACKUP
interface ens160 #绑定虚拟ip的网络接口,与本机ip地址所在的网络接口相同
virtual_router_id 51 #虚拟路由的id号,两个节点设置必须一样,可选ip最后一段使用,相同的VRID为一个组,它将决定多播的MAC地址
priority 100 #节点优先级,值范围0-254,MASTER要比BACKUP高
nopreempt #优先级高的设置nopreempt解决异常恢复后再次抢占的问题
advert_int 1 #组播信息发送间隔,两个节点设置必须一样,默认1s
authentication { #设定验证信息,两个节点必须一致
auth_type PASS #认证方式
auth_pass 1111 #认证密码
}
##将track_script块加入instance配置块
track_script{
chk_nginx #执行nginx监控的服务
}
virtual_ipaddress { #虚拟ip池
192.168.22.145 #虚拟ip,可以定义多个
}
}
6、编写Nginx状态检测脚本 nginx_check.sh
脚本要求:如果nginx停止运行,尝试启动,如果无法启动则杀死本机的keepalived进程,keepalied将虚拟ip绑定到备用机器上。内容如下:
#vi /etc/keepalived-2.0.4/nginx_check.sh
#!/bin/bash
A=`ps —C nginx -no—header |wc-1
if [$A -eq 0];then
/usr/local/nginx/sbin/nginx
sleep2
if [`ps —C nginx -no—header |wc -1` -eq 0];then
killall keepalived
fi
fi
保存后,给脚本赋予执行权限
chmod +x /etc/keepalived-2.0.4/nginx_check.sh
7、启动keepalived
service keepalived start