nginx 高可用配置实例

环境准备

  • 两个linux虚拟机并各自开启nginx

  • 虚拟机中安装keepalived

    安装好的keepalived会在/etc下,并生成相关配置
    在这里插入图片描述

监测脚本

nginx_check.sh

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

放置位置

/usr/local/src

在这里插入图片描述

启动keepalived服务实例

在两台虚拟机上都要启动该服务

systemctl start keepalived.service

查看启动状态

ps  -ef | grep keepalived

在这里插入图片描述

修改主nginx节点配置

虚拟地址可以设置多个,每行一个
必须和nginx服务器处于同一网段

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.79.132
   smtp_connect_timeout 30
   router_id RD1    # 路由id,必须唯一,可以在本机的/etc/hosts文件中设置
}
vrrp_script chk_http_port{
  	script "/usr/local/src/nginx_check.sh"  # 检测脚本
  	interval 2
  	weight 2
}
vrrp_instance VI_1 {
    state MASTER                    # 指定keepalived的角色,master为主,backup为备
    interface ens33					# 当前进行vrrp通讯的网络接口卡(当前centos的网卡)	
    virtual_router_id 51            # 虚拟路由编号,主从要一致!
    priority 100  					#权重,主服务器要高于从服务器,数值越大获得请求的优先级越高
    advert_int 1  					#检查间隔,默认为1s(vrrp组播周期秒数)
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.79.138  			 #可以设置多个,每行一个,注意必须和nginx服务器处于同一网段
    }
}

修改从节点配置

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.79.133
   smtp_connect_timeout 30
   router_id RD2
}
vrrp_script chk_http_port{
	script "/usr/local/src/nginx_check.sh"
	interval 2
	weight 2
}
vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.79.138
    }
}

查看绑定状态

ip a

在这里插入图片描述

测试

重启nginx

要先cd 到nginx的sbin目录下

./nginx  -s stop
./nginx

重启keepalived服务

systemctl  restart keepalived.service

查看keepalived服务日志

tail -f /var/log/messages

在这里插入图片描述

停掉nginx的主节点

在这里插入图片描述
虚拟网络IP依然可以访问
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值