天天看點

Keepalived+Nginx網站高可用keepalived+nginx部署企業級網站高可用方案

keepalived+nginx部署企業級網站高可用方案

  • 環境準備
node1(Nginx1):192.168.10.10
node2(Nginx2):192.168.10.20
node3(WEB1):192.168.10.30
node4(WEB2):192.168.10.40
VIP:192.168.10.100
           
  • web部署
在node3和node4執行下面的腳本:
#!/bin/bash
yum install net‐tools httpd ‐y
systemctl stop firewalld
setenforce 0
echo "<h1>This is RS1</h1>" > /var/www/html/index.html # 修改不同的首頁以便測試!
systemctl start httpd
           
  • nginx部署
node1和node2節點執行以下腳本:
#!/bin/bash
systemctl stop firewalld
setenforce 0
yum install nginx ‐y
cat > /etc/nginx/conf.d/proxy.conf << EOF
upstream websers{
    server 192.168.10.30;
    server 192.168.10.40;
}
server{
    listen 8080;
    server_name 192.168.10.10;
    location / {
        proxy_pass http://websers;
}
}
EOF
nginx ‐s reload
           
  • Keepalived部署
在node1和node2節點執行以下腳本:
#!/bin/bash
yum install keepalived ‐y
mv /etc/keepalived/keepalived.conf{,.bak}
cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
    router_id node1 # node2修改
}
vrrp_instance VI_1 {
    state MASTER # node2節點BACKUP
    interface ens33
    virtual_router_id 10
    priority 100 # node2節點小于100
    advert_int 1
    authentication {
    auth_type PASS
    auth_pass 1111
    }
    virtual_ipaddress {
    192.168.10.100
    }
}
           
  • 要自定義腳本檢測nginx服務是否正常
[[email protected] ~]# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
    router_id node1
}
# 定義script
vrrp_script chk_http_port {
    script "/usr/local/src/check_nginx_pid.sh"
    interval 1
    weight ‐2 # 優先級‐2
}
vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 10
    priority 100
    advert_int 1
    authentication {
    auth_type PASS
    auth_pass 1111
    }
    # 調用script腳本
    track_script {
    chk_http_port
    }
    virtual_ipaddress {
    192.168.10.100
    }
}
[[email protected] ~]# cat /usr/local/src/check_nginx_pid.sh
#!/bin/bash
# 當nginx正常的時候狀态碼為0
# 當nginx不正常時候狀态碼為1
# 因為當退出狀态碼為非0的時候會執行切換
nginx_process_number=`ps -C nginx --no-header | wc -l`
if [ $nginx_process_number -eq 0 ];then
#   systemctl restart nginx
    nginx_process_number=`ps -C nginx --no-header | wc -l`
    if [ $nginx_process_number -eq 0 ];then
        exit 1
    else
        exit 0
    fi
else
    exit 0
fi