keepalived

搭建Keepalived

主节点Keepalived安装

环境:两台nginx服务器
img
img

  1. 下载Keepalived安装包
curl https://www.keepalived.org/software/keepalived-2.2.7.tar.gz -o keepalived-2.2.7.tar.gz -k 
  1. 解压到跟nginx安装包同一个目录下
tar -zxvf keepalived-2.2.7.tar.gz 

img
3. 配置Keepalived,进入keepalived-2.2.7目录下使用以下命令

./configure \
--prefix=/usr/local/keepalived \ 
--sysconf=/etc  
# prefix  安装目录
# sysconf 核心配置文件

img
4. 编译和安装

make
make install
  1. 启动
cd /usr/local/keepalived/
ll
cd sbin/
./keepalived 

img

主节点Keepalived核心配置文件

  1. 查看IP地址
  2. 进入etc/keepalived目录下配置Keepalived.conf文件
cd /etc/keepalived
vim keepalived.conf

修改以下配置
img
3. 启动keepalived,再查看IP地址,可以发现多了一个IP地址,也就是VIP
img

备节点配置

  1. 把主节点的Keepalived文件复制到备节点上
scp -r /usr/local/keepalived/ root@192.168.206.132:/usr/local/
  1. 在备节点查看是否复制成功
    img
  2. 修改备节点核心配置文件
    img
  3. 指定配置文件,查看进程
./keepalived -f /usr/local/keepalived/etc/keepalived/keepalived.conf  

img
5. 查看ip地址,备节点获取不到VIP
img
6. 关掉主节点配置文件
img
7. 再次查看备节点IP地址,此时可看到VIP,说明主备切换正常
img
8. 使用VIP访问,亦可以正常访问
img

把keepalived注册成为系统服务

  1. 关闭keepalived
    img
  2. 拷贝配置文件
cd keepalived-2.2.7/keepalived/etc/
cp init.d/keepalived /etc/init.d/
cp sysconfig/keepalived /etc/sysconfig/

img
3. 加载配置文件

systemctl daemon-reload
  1. 启动服务查看进程
systemctl start keepalived.service
ps -ef|grep keepalived

img

keepalived 配置nginx自动重启,实现7X24不间断服务

  1. 关闭主节点的nginx,访问VIP,会发现访问失败
./nginx -s stop

img

  1. 编辑脚本文件,进入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
  1. 给脚本文件添加可执行权限,执行脚本文件
chmod  +x check_nginx_alive_or_not.sh
./check_nginx_alive_or_not.sh
  1. 再次访问VIP,可以正常访问
    img
  2. 配置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脚本
}

img
6. 重启keepalived服务

systemctl restart keepalived.service
  1. 测试,关闭nginx服务,依旧可以继续访问VIP
posted @ 2023-05-05 17:11  小肚腩吖  阅读(62)  评论(0编辑  收藏  举报