配置KeepAlive支持雙節點nginx高可用。本文從nginx的安裝、keepalived的安裝與配置、nginx-keepalived高可用等三個過程進行實驗。 ...
實驗環境
序號 | 主機名 | IP地址 |
---|---|---|
1 | nginx1 | 192.168.204.11 |
2 | nginx2 | 192.168.204.12 |
安裝nginx
安裝nginx
yum install -y epel-*
yum install -y nginx
編寫HTML文件
nginx1上
echo -e "nginx1" > /usr/share/nginx/html/index.html
nginx2上
echo -e "nginx2" > /usr/share/nginx/html/index.html
啟動nginx
systemctl start nginx
systemctl enable nginx
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
訪問瀏覽器
安裝配置keepalived
1.安裝keepalived
yum install keepalived -y
2.在nginx1上配置keepalived
修改配置文件
vim /etc/keepalived/keepalived.conf
啟動
systemctl start keepalived
systemctl enable keepalived
3.在nginx2上配置keepalived
修改配置文件
vim /etc/keepalived/keepalived.conf
啟動
systemctl start keepalived
systemctl enable keepalived
4.在宿主機ping 192.168.204.10
,使用arp -a
查看緩存
5.瀏覽器訪問虛擬地址
6.在nginx1上宕掉ens33網卡
在宿主機使用arp -a
查看緩存
在主機使用瀏覽器訪問虛擬地址
可以看到,對192.168.204.10
的請求已從nginx1
節點轉移到了nginx2
節點
配置keepalived支持nginx高可用
1.編寫NGINX狀態監測腳本
編寫腳本/etc/keepalived/nginx_check.sh
#!/bin/bash
# file:/etc/keepalived/nginx_check.sh
N=`ps -C nginx --no-header | wc -l`
if [ $N -eq 0 ]; then
systemctl restart nginx
sleep 2
if [ `ps -C nginx --no-header | wc -l` -eq 0 ]; then
killall keepalived
fi
fi
賦予可執行許可權
chmod +x /etc/keepalived/nginx_check.sh
測試腳本
2.配置keepalived支持NGINX高可用
在nginx1節點上編輯/etc/keepalived/keepalived.conf
vim /etc/keepalived/keepalived.conf
重新啟動keepalived
systemctl restart keepalived
3.測試高可用
瀏覽器訪問虛擬地址
在nginx1節點運行stop.sh腳本,然後使用瀏覽器訪問虛擬地址
#!/bin/bash
# file:stop.sh
for ((i=0; i<=100; i++))
do
systemctl stop nginx
echo 'stoped. sleep 1s...'
sleep 1
done