Keepalived + nginx高可用

2020-01-15  本文已影响0人  说说道道

选择版本:

Keepalived-2.0.7、nginx-1.15.0


image.png

安装前准备:

1、准备好两台Web 服务器
2、配置好两台nginx 服务器分别负载到以上两台web服务上
3、开启web服务,访问测试nginx负载正常

通过安装包安装keepalived,安装两台keepalived一主一从

  a、    tar xvf keepalived-2.0.7.tar.gz
  b、    将文件cp 到/usr/local/src 目录下
  c、    重命名 mv keepalived-2.0.7 keepalived
  d、    ./configure --prefix=/usr/local/keepalived
  e、    make install
  f、    cp /usr/local/keepalived/etc/sysconfig/keepalived  /etc/sysconfig/keepalived
  g、    cp /usr/local/keepalived/sbin/keepalived /usr/sbin/keepalived
  h、    cp /usr/local/keepalived/keepalived/etc/init.d/keepalived  /etc/init.d/keepalived

配置keepalived

a、 mkdir /etc/keepalived
b、 在/etc/keepalived目录下创建keepalived.conf
c、 主节点配置

global_defs {
   router_id 45
}
vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight -20
}
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 200
    mcast_src_ip 10.11.11.45
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1234
    }
    virtual_ipaddress {
        10.11.11.200
    }
    track_script {
        chk_nginx
    }
}

d、 从节点配置

global_defs {
   router_id 58
}
vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"
    interval 2
    weight -20
}
vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 200
    mcast_src_ip 10.11.11.58
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1234
    }
    virtual_ipaddress {
        10.11.11.200
    }
    track_script {
        chk_nginx
    }
}

e、 在/etc/keepalived目录下创建nginx_check.sh脚本

#!/bin/bash
A=`ps -C nginx --no-heading|wc -l` 
if [ $A -eq 0 ];then 
    /usr/local/nginx/sbin/nginx 
    sleep 2 
    if [ `ps -C nginx --no-heading |wc -l` -eq 0 ];then 
        killall keepalived 
    fi 
fi

f、 给nginx_check.sh脚本添加可执行权限

chmod u+x nginx_check.sh

g、 启动keepalived

service keepalived start

h、 停止keepalived

service keepalived stop

3、 测试keepalived

a、 通过启/停keeplived测试
停止keepalived观察主节点10.11.11.200虚拟ip消失


image.png

从节点虚拟IP出现


image.png
Web服务正常访问
image.png

b、 通过启/停nginx测试


image.png
image.png

停止nginx两秒之后无需手动启动nginx两秒之后再次查看nginx发现nginx进程又一次存在。说明nginx_check.sh脚本生效,若在启动nginx失败时则会停止keepalived进去上述第一种状态,虚拟IP10.11.11.200漂移至从节点,nginx服务依旧可用。

上一篇下一篇

猜你喜欢

热点阅读