Back

Keepalived+Nginx部署实验

小实验

Keepalived简介

一个免费开源的轻量级别高可用解决方案,通过VRRP协议实现多台机器之间的故障转移服务。

规划方案

master :192.168.137.6

backup :192.168.10.8

vip :192.168.10.11

OS:CentOS Linux 7 (Core)

网卡名都是ens34

实现:vip 上跑一个Nginx服务

思路:安装+配置+脚本+启动排错+验证

环境安装

sudo yum -y install nginx

sudo yum -y install keepalive

主程序文件:/usr/sbin/keepalived.conf

主配置文件:/usr/sbin/keepalived.conf

服务配置

master 和backup区别:配置中的state和priority不一样

master :vi /usr/sbin/keepalived.conf

vrrp_instance VI_1 {
    state MASTER
    interface ens34
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }

    virtual_ipaddress {
        192.168.137.11/24 dev ens34
    }
    preempt delay 60
}
vrrp_script chk_nginx_port {
	script "/opt/chk_nginx.sh"
	interval 2
	weight -5
	fall 2
	rise 1
	}

backup:vi /usr/sbin/keepalived.conf

vrrp_instance VI_1 {
    state BACKUP
    interface ens34
    virtual_router_id 51
    priority 80
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }

    virtual_ipaddress {
        192.168.137.11/24 dev ens34
    }
    preempt delay 60
}
vrrp_script chk_nginx_port {
	script "/opt/chk_nginx.sh"
	interval 2
	weight -5
	fall 2
	rise 1
	}

脚本配置

vi /opt/chk_nginx.sh

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

赋权:chmod 775 /opt/chk_nginx.sh

启动排错

systemctl start nginx

systemctl start keepalived

通过ip a可以发现vip没有启动

systemctl status keepalived 查看状态,发现很多中文的空格未识别,修改配置文件,删去空格,重试

systemctl restart keepalived

通过ip a可以发现vip已经启动

效果如下:

验证

通过ip192.168.137.11可以看到nginx欢迎界面,我们在主备上修改这个界面

vi /usr/share/nginx/html/index.html

分别在

Welcome to nginx!

后加上111和222

访问192.168.137.11可以看到111

systemctl stop keepalived关闭主机1的keepalived服务

再次访问192.168.137.11可以看到222

重新开启

变回111

验证成功

Built with Hugo
Theme Stack designed by Jimmy
© Licensed Under CC BY-NC-SA 4.0