Nginx部署高可用集群

https://support.huaweicloud.com/bestpractice-vpc/bestpractice_0010.html

这里讲述了Nginx的高可用部署方案

1 部署Nginx

两台机器均需要部署Nginx

假设网络环境:

  • A机:192.168.0.10
  • B机:192.168.0.11
  • VIP:192.168.0.100

2 安装keepalived

3 配置

A机:

! Configuration File for keepalived
global_defs {
router_id master-node
}
vrrp_script chk_http_port {
                      script  "/etc/keepalived/chk_nginx.sh"
                      interval 2
                      weight -5
                      fall 2
                      rise 1
                     }
vrrp_instance VI_1 {
                state MASTER
                interface eth0
                mcast_src_ip 192.168.0.10 # 当前ip
                virtual_router_id 51 # 要保持统一
                priority 101
                advert_int 1
                authentication {
                              auth_type PASS
                              auth_pass 1111
                             }
                unicast_src_ip 192.168.0.10 # 当前ip                                   
                virtual_ipaddress {
                             192.168.0.100 # vip
                             }
track_script {
           chk_http_port
            }
}

B机:

! Configuration File for keepalived
global_defs {
router_id master-node
}
vrrp_script chk_http_port {
                      script  "/etc/keepalived/chk_nginx.sh"
                      interval 2
                      weight -5
                      fall 2
                      rise 1
                     }
vrrp_instance VI_1 {
                state BACKUP
                interface eth0
                mcast_src_ip 192.168.0.11 # 当前ip
                virtual_router_id 51
                priority 100 # 优先级比主节点要低
                advert_int 1
                authentication {
                              auth_type PASS
                              auth_pass 1111
                             }
                unicast_src_ip 192.168.0.11 # 当前ip                                   
                virtual_ipaddress {
                             192.168.0.100 # vip
                             }
track_script {
           chk_http_port
            }
}

两台机器还需要创建检查脚本,/etc/keepalived/chk_nginx.sh:

#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0"  ]; then
  systemctl start nginx.service
   sleep 2
   counter=$(ps -C nginx  --no-heading|wc -l)
   if [ "${counter}" =  "0" ]; then
      systemctl stop keepalived.service
   fi
fi

4 验证

关闭A机,通过在B机执行ip a命令,发现vip绑定到了B机。

启动A机,执行ip a,发现vip重新绑定到A机,B机解绑vip。

Leave a Reply

Your email address will not be published. Required fields are marked *