服务架构一分钟系列:Nginx+Keepalived部署

1基础环境
测试机器1 192.168.0.251 MASTER Keepalived+nginx
测试机器2 192.168.0.252 BACKUP Keepalived+nginx
虚拟vip 192.168.0.100 Vip

2 nginx配置
251/252都安装nginx,开放统一端口1000

server {
    listen       1000;
    server_name  localhost;
    #charset koi8-r;
    #access_log  logs/host.access.log  main;
    location / {
        root   /data/www;
        index  index.html index.htm;
        # example
        #ModSecurityEnabled on;
        #ModSecurityConfig /etc/nginx/modsecurity.conf;
    }
    error_page  404              /404.html;
    location = /404.html {
        root   /usr/share/nginx/html;
    }
}

3 keepalived安装

yum -y install libnl libnl-devel
yum install -y libnfnetlink-devel yum
install keepalived -y

4 keepalived配置

Master config:
global_defs {
   router_id shulaibao1    #hostname
}

vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh" #检测nginx的脚本
    interval 2    #每2秒检测一次
    weight -20   #如果某一个nginx宕机 则权重减20
}

vrrp_instance VI_1 {
    state MASTER   #状态MASTER BACKUP:MASTER->BACKUP抢占模式,MASTER宕掉切换掉BACKUP机器,但MASTER机器恢复又切换到MASTER机器访问。
    #BACKUP->BACKUP平衡模式,根据机器priority 分配到机器地址,一个节点宕掉切换到另一个节点,宕机节点恢复访问仍然还是保持在另一个节点避免延迟处理。
    interface eth0           #绑定的网卡
    virtual_router_id 51       #虚拟路由的ID号,两个节点设置必须一样
    mcast_src_ip  192.168.0.251  #本机的IP
    priority 100              #分配权重
    advert_int 1
    #nopreempt

设置验证信息,两个节点必须一致
    authentication {
        auth_type PASS
        auth_pass 1111
    }

 # 虚拟IP,两个节点设置必须一样。
    virtual_ipaddress {
        192.168.0.100
    }

nginx存活状态检测脚本
    track_script {
       chk_nginx
    }
}
BACKUP config:
global_defs {
   router_id shulaibao2                           #hostname
}

vrrp_script chk_nginx {
    script "/etc/keepalived/nginx_check.sh"       #检测nginx的脚本
    interval 2                                    #每2秒检测一次
    weight -20                                    #如果某一个nginx宕机 则权重减20
}

vrrp_instance VI_1 {
    state BACKUP                                  #状态 MASTER BACKUP
    interface eth0                                #绑定的网卡
    virtual_router_id 51
    mcast_src_ip 192.168.0.252
    priority 90
    advert_int 1
    #nopreempt

    authentication {
        auth_type PASS
        auth_pass 1111
    }

    virtual_ipaddress {
        192.168.0.100
    }

    track_script {
       chk_nginx
    }
}

5 Keepalived心跳检测nginx:节点nginx宕掉切换到另外节点

A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ]
        then
        echo 'nginx server is died'
        killall keepalived
Fi
Chmod +x ./nginx_check.sh

6 虚拟vip

251/252 ip addr: eth0:
BROADCAST,MULTICAST,UP,LOWER_UP mtu 1500
qdisc pfifo_fast state UP qlen 1000
link/ether d0:17:c2:99:6a:55 brd ff:ff:ff:ff:ff:ff
inet 192.168.0.251/24 brd 192.168.0.255 scope global eth0
inet 192.168.2.251/24 brd 192.168.2.255 scope global eth0
inet 192.168.0.100/32 scope global eth0
inet6 fe80::d217:c2ff:fe99:6a55/64 scope link
valid_lft forever preferred_lft forever

你可能感兴趣的:(springCloud生态圈,架构设计)