keepalived
搭建Keepalived
主节点Keepalived安装
环境:两台nginx服务器
- 下载Keepalived安装包
curl https://www.keepalived.org/software/keepalived-2.2.7.tar.gz -o keepalived-2.2.7.tar.gz -k
- 解压到跟nginx安装包同一个目录下
tar -zxvf keepalived-2.2.7.tar.gz
3. 配置Keepalived,进入keepalived-2.2.7目录下使用以下命令
./configure \
--prefix=/usr/local/keepalived \
--sysconf=/etc
# prefix 安装目录
# sysconf 核心配置文件
4. 编译和安装
make
make install
- 启动
cd /usr/local/keepalived/
ll
cd sbin/
./keepalived
主节点Keepalived核心配置文件
- 查看IP地址
- 进入etc/keepalived目录下配置Keepalived.conf文件
cd /etc/keepalived
vim keepalived.conf
修改以下配置
3. 启动keepalived,再查看IP地址,可以发现多了一个IP地址,也就是VIP
备节点配置
- 把主节点的Keepalived文件复制到备节点上
scp -r /usr/local/keepalived/ root@192.168.206.132:/usr/local/
- 在备节点查看是否复制成功
- 修改备节点核心配置文件
- 指定配置文件,查看进程
./keepalived -f /usr/local/keepalived/etc/keepalived/keepalived.conf
5. 查看ip地址,备节点获取不到VIP
6. 关掉主节点配置文件
7. 再次查看备节点IP地址,此时可看到VIP,说明主备切换正常
8. 使用VIP访问,亦可以正常访问
把keepalived注册成为系统服务
- 关闭keepalived
- 拷贝配置文件
cd keepalived-2.2.7/keepalived/etc/
cp init.d/keepalived /etc/init.d/
cp sysconfig/keepalived /etc/sysconfig/
3. 加载配置文件
systemctl daemon-reload
- 启动服务查看进程
systemctl start keepalived.service
ps -ef|grep keepalived
keepalived 配置nginx自动重启,实现7X24不间断服务
- 关闭主节点的nginx,访问VIP,会发现访问失败
./nginx -s stop
- 编辑脚本文件,进入Keepalived目录下,把脚本文件放在keepalived.conf同一个目录下
cd /etc/keepalived/
vim check_nginx_alive_or_not.sh
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
#判断nginx是否宕机,如果宕机了,尝试重启
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
#等待一小会再次检查nginx,如果没有启动成功,则停止keepalived,使其启动备用机
sleep 3
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
- 给脚本文件添加可执行权限,执行脚本文件
chmod +x check_nginx_alive_or_not.sh
./check_nginx_alive_or_not.sh
- 再次访问VIP,可以正常访问
- 配置Keepalived做定时监听,在核心配置文件keepalived.conf下添加以下内容
cd /etc/keepalived/
vim keepalived.conf
vrrp_script check_nginx_alive {
script "/etc/keepalived/check_nginx_alive_or_not.sh"
interval 2 #每隔两秒运行上一行脚本
weight 10 #如果脚本运行成功,则升级权重+10
}
track_script {
check_nginx_alive #追踪nginx脚本
}
6. 重启keepalived服务
systemctl restart keepalived.service
- 测试,关闭nginx服务,依旧可以继续访问VIP