一、環境準備
192.168.113.11 | Nginx+Keepalive(Master) |
192.168.113.22 | Nginx+keepalive(Backup) |
192.168.113.33 | Nginx(web服務器) |
192.168.113.44 | Nginx(服務器) |
?
二、環境搭建準備
2.1 Nginx源碼編譯安裝
參考作責之前發布《Nginx源碼編譯安裝》https://blog.csdn.net/m0_55213400/article/details/147066230?spm=1001.2014.3001.5501
2.2 Nginx配置負載均衡反向代理
? ? ? ? 192.168.113.11
? ? ? ? 192.168.113.22
在http{ }模塊定義地址池upstream releserver {server 192.168.113.33:80;server 192.168.113.44:80;}server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_connect_timeout 5s;proxy_read_timeout 30s;proxy_send_timeout 10s;proxy_pass http://releserver; 調用地址池}
2.3 web服務器配置? ? ? ??
? ? ? ? 192.168.113.33
? ? ? ? 192.168.113.44
? ? ? ? 站點目錄:自定義
location / {#allow 0.0.0.0/24; # 公司內網#allow 10.0.0.0/8; # 內部服務器#deny all; # 拒絕其他所有IPproxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_connect_timeout 5s;proxy_read_timeout 30s;proxy_send_timeout 10s;root /usr/local/nginx/html/laoshi/admin;index index.html index.htm;}
2.3 Keepalive編譯安裝
? ? ? ? keepalive官網下載鏈接https://www.keepalived.org/download.htmlhttps://www.keepalived.org/download.html
????????? 編譯步驟如下
yum install -y gcc gcc-c++ make automake autoconf libtooltar -zxvf keepalived-2.3.4.tar.gzcd keepalived-2.3.4/./configure --prefix=/usr/local/keepalived --sysconfdir=/etc --with-init=systemd --with-openssl --with-snmpmake && make installcd /etc/keepalived/cp keepalived.conf.sample keepalived.conf
2.4?設置允許虛擬IP
? ? ? ? 主備都需要
echo 'net.ipv4.ip_nonlocal_bind = 1' >> /etc/sysctl.conf && sysctl -p
2.5 開始配置keepalive? ?主備都需要配置(重點)
????????virtual_router_id 51? 必須與主備保持一致
????????priority 100? ?如果主為100 則備低于100
????????auth_type PASS? ?必須主備保持一致
? ? ? ? auth_pass 1111? ? ?必須主備保持一致
! Configuration File for keepalivedglobal_defs {router_id 192.168.113.11
}vrrp_script check_nginx {script "/usr/local/bin/check_nginx.sh"interval 2 #每隔2S執行腳本weight -20}vrrp_instance VI_1 {state MASTERinterface ens33virtual_router_id 51priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.113.100 #定義虛擬IP}track_script {check_nginx}# Allow packets addressed to the VIPs above to be receivedaccept
}
? ? ? ? 判斷Nginx運行狀態腳本
#!/bin/bash
#檢查Nginx狀態是否存在
if [ $(ps -C nginx --no-header | wc -l) -eq 0 ];then#Nginx不存在systemctl restart nginxsleep 3#以防萬一再次嘗試重啟一下nginxif [ $(ps -C nginx --no-header | wc -l) -eq 0 ];then#重啟失敗 強制停止keepalived服務systemctl stop keepalivedexit 1fi
fi
exit 0
三、驗證是否正常?
? ? ? ? 此時 虛擬IP正常顯示 master
? ? ? ? 此時 備主機不顯示虛擬IP
? ? ? ? 訪問測試 http://192.168.111.100
? ? ? ??訪問測試 http://192.168.111.100
? ? ? ? 主服務器關機測試
? ? ? ? VIP飄移正常