Nginx高可用实战

1、实验环境

一台Nginx主节点 192.168.1.101

一台Nginx备节点 192.168.1.102

二台tomcat服务器 192.168.1.103;192.168.1.104

2、安装keepalived

主备Nginx上分别安装keepalived

yum -y install keepalived

#编写主备nginx检查脚本
vi /etc/keepalived/nginx_check.sh

#!/bin/bash
CHK_PORT=$1
if [ -n "$CHK_PORT" ];then
        PORT_PROCESS=`ss -lnt|grep $CHK_PORT|wc -l`
        if [ $PORT_PROCESS -eq 0 ];then
                echo "Port $CHK_PORT Is Not Used,End."
                exit 1
        fi
else
        echo "Check Port Cant Be Empty!"
fi

#授权
chmod 755 nginx_check.sh

3、主节点(Master)配置

vi /etc/keepalived/keepalived.conf

#配置内容如下
! Configuration File for keepalived

global_defs {
router_id localhost
}

vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh 80"
interval 2
weight -20
}

vrrp_instance VI_1 {
state MASTER
interface ens33                                 #本地网卡名称
virtual_router_id 50
mcast_src_ip 192.168.1.101                      #本机IP
priority 100 
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
    }

track_script {
chk_nginx
    }

virtual_ipaddress {
        192.168.1.200                            #配置同网段空闲地址,做虚拟IP
    }
}

4、备节点(Backup)配置

vi /etc/keepalived/keepalived.conf

#配置内容如下
! Configuration File for keepalived

global_defs {
router_id localhost
}

vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh 80"
interval 2
weight -20
}

vrrp_instance VI_1 {
state BACKUP
interface ens33                                 #本地网卡名称
virtual_router_id 50
mcast_src_ip 192.168.1.102                      #本机IP
priority 90 
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
    }

track_script {
chk_nginx
    }

virtual_ipaddress {
        192.168.1.200                          #配置同网段空闲地址,做虚拟IP
    }
}

5、配置主备nginx轮询负载

vi /usr/local/nginx/conf/nginx.conf

#配置内容如下
upstream web {                                          
            server 192.168.1.104:8080;
            server 192.168.1.103:8080;
}

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #root   html;
            proxy_pass http://web;                 
            index  index.html index.htm;
        }
}

6、启动分别启动主备服务器Nginx和keepalived

systemctl start nginx
systemctl start keepalived

7、停止主服务器nginx服务测试

systemctl stop nginx

8、访问虚拟IP依然可以进行负载均衡

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值