keepalived实现nginx的高可用

百般思念 提交于 2020-02-24 14:40:07

1.使用yum安装keepalived

yum install keepalived -y

2.修改配置文件keepalived.conf

主服务器配置文件

global_defs {
    router_id NodeA
}
vrrp_script check_run {
    script "/etc/keepalived/check_nginx.sh"  #自定义检查nginx的脚本
    interval 2
    weight 2
}
vrrp_instance VI_1 {
    state MASTER    #设置为主服务器
    interface eth0  #监测网络接口
    virtual_router_id 51  #虚拟路由标识,主、备必须一样
    priority 100   #(主、备机取不同的优先级,主机值较大,备份机值较小,值越大优先级越高)
    advert_int 1   #VRRP Multicast广播周期秒数
    nopreempt #恢复后也不抢占资源    authentication {
    auth_type PASS  #VRRP认证方式,主备必须一致
    auth_pass 1111   #(密码)
    }
    track_script {
        check_run
    }
    virtual_ipaddress {
      虚拟IP/掩码 #VRRP HA虚拟地址
    }
}

检查nginx服务状态的脚本,check_nginx.sh 

#!/bin/bash
netstat -npl|grep -q nginx
if [[ $? -ne 0 ]]; then
  /usr/local/nginx/sbin/nginx
  if [[ $? -ne 0 ]]; then
    service keepalived stop
  fi
fi

 

备用服务器配置文件

global_defs {
    router_id NodeB
}
vrrp_script check_run{
    script "/etc/keepalived/check_nginx.sh"
    interval 2
    weight 2
}
vrrp_instance VI_1 {
    state BACKUP    #设置为备服务器
    interface eth0  #监测网络接口
    virtual_router_id 51  #虚拟路由标识,主、备必须一样
    priority 90   #(主、备机取不同的优先级,主机值较大,备份机值较小,值越大优先级越高)
    advert_int 1   #VRRP Multicast广播周期秒数
    nopreempt #恢复后也不抢占资源    authentication {
    auth_type PASS  #VRRP认证方式,主备必须一致
    auth_pass 1111   #(密码)
    }
    track_script {
        check_run
    }
    virtual_ipaddress {
      虚拟IP/掩码  #VRRP HA虚拟地址
    }
}

3.主、备服务器启动keepalived和nginx服务

 /etc/init.d/keepalived start
 /etc/init.d/nginx start

查看主服务器虚拟IP是否存在

ip addr

关闭主服务器的keepalived服务,测试虚拟IP是否切换到备用服务器上

ps:

当主备服务器都出现了VIP,可能是网络环境不支持广播方式,此时要使用单播方式

unicast_src_ip 10.205.22.185    #本机IP
unicast_peer {
         10.205.22.186  #备机IP
     }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!