nginx + keepalived 高可用配置

参考文档《keepalived-doc》

 

ip  
192.168.153.14 主 
192.168.153.15 备 

1、安装nginx

yum -y install gcc pcre-devel zlib-devel openssl openssl-devel
# 安装 nginx wget https:
//nginx.org/download/nginx-1.9.9.tar.gz tar -xzvf nginx-1.9.9.tar.gz cd nginx-1.9.9 ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module # 安装 make && make install # 启动 /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf # 重启 /usr/local/nginx/sbin/nginx -s reload # 设置开机启动 vim nginx.service

  [Unit]
  Description=nginx service
  After=network.target

  [Service]
  Type=forking
  ExecStart=/usr/local/nginx/sbin/nginx
  ExecReload=/usr/local/nginx/sbin/nginx -s reload
  ExecStop=/usr/local/nginx/sbin/nginx -s quit
  PrivateTmp=true
  [Install]
  WantedBy=multi-user.target

  # 保存退出,将文件移动或复制到 /usr/lib/systemd/system/

  cp ./nginx.service /usr/lib/systemd/system/

# 重启配置服务
systemctl daemon-reload
# 启动
systemctl start nginx
# 查看状态
systemctl status nginx
  
# 复制安装包到其他服务器并安装
scp ./nginx-1.9.9.tar.gz root@192.168.153.15:/opt/

2、安装Keepalived

yum -y install keepalived
vim /etc/keepalived/keepalived.conf
# 新增nginx健康监测

  vrrp_script check_nginx{
      script "/etc/keepalived/check_nginx.sh" # 心跳执行的脚本,检测nginx是否启动
      interval 2                              #(检测脚本执行的间隔,单位是秒)
  }

  vrrp_instance VI_1 {
    state MASTER
    #interface eth0
    interface ens33     # 修改为本机网卡名称
    virtual_router_id 51
    priority 101        # 优先级,备机要小于主机优先级
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        # 192.168.200.16
        # 192.168.200.17
        # 192.168.200.18
        192.168.153.100 # 虚拟ip
    }

    # 跟踪脚本

    track_script {
        check_nginx
    }

}

  # /etc/keepalived新增check_nginx.sh监测脚本

  vim /etc/keepalived/check_nginx.sh

  #!/bin/bash
  # 检测nginx是否启动了
  A=`ps -C nginx --no-header |wc -l`
  if [ $A -eq 0 ];then                                     # 如果nginx没有启动就启动nginx
        systemctl start nginx                              # 重启nginx
        if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then # nginx重启失败,则停掉keepalived服务,进行VIP转移
               killall keepalived
        fi
   fi

# 复制到备机
scp ./check_nginx.sh root@192.168.153.15:/etc/keepalived/
scp ./keepalived.conf root@192.168.153.15:/etc/keepalived/
# 备机 编辑配置修改如图标示即可
  
# 开机启动
systemctl enable --now keepalived

# MASTER ip a 查看
ip a

  # 备机

  

 

测试访问虚拟ip 192.168.153.100 当前是153.14 master绑定了vip

 

 关闭掉 153.14 的keepalived

systemctl stop keepalived

再次访问,vip已经漂移到了153.15备机上

 备机查看

 

 

现在再启动master上的keepalived,我们会发现ip会再漂移回master

systemctl start keepalived

 

posted @ 2023-01-09 20:34  php的自我修养  阅读(105)  评论(0编辑  收藏  举报