一、所需資源
兩台虛擬機:172.20.53.85,172.20.53.87。在兩台機器上裝上nginx+keepalived
VIP:172.20.53.250
二、安裝nginx
1.創建安裝目錄
mkdir -p /usr/soft
2.進入安裝目錄並下載nginx
wget http://nginx.org/download/nginx-1.14.0.tar.gz
3.解壓
tar -zxvf nginx-1.14.0
4.新建用於安裝nginx的文件夾
mkdir nginx
5.將安裝路徑指定到新建的文件夾
(檢查過程可能會因確少某些依賴包報錯,根據需要先安裝完依賴包再執行)
./configure --prefix=/usr/soft/nginx
6.編譯安裝
make
make install
三、安裝配置keepalived
1.安裝
yum install -y keepalived
2.配置
# 172.20.53.85(主機) $ vim /etc/keepalived/keepalived.conf vrrp_instance VI_1 { state MASTER #主從標志 interface ens0 #網卡標志 virtual_router_id 51 priority 100 #權重,主機必須比備機大 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 172.20.53.250 #虛擬ip } } # 172.20.53.87(備機) $ vim /etc/keepalived/keepalived.conf vrrp_instance VI_1 { state BACKUP interface eth0 virtual_router_id 51 priority 90 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 172.20.53.250 } }
3.開啟服務
systemctl enable keepalived.service
systemctl start keepalived.service
4.查看虛擬IP是否綁定主機
ip addr show eth0
eth0為網卡標識,可通過ifconfig查看。
此時虛擬IP已綁定主機,若發現備機也同時綁定了,先關閉防火牆和selinux再重試
5.結合nginx
- 為方便區分主備機,修改一下nginx首頁標題
vim /usr/soft/nginx/html/index.html <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!(85)</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html>
- 訪問虛擬IP
已經訪問到主機(85)的nginx。關閉主機(85)的keepalived服務再重新訪問,則跳轉到備機(87)了
- 高可用思路
可以編寫腳本檢測主機nginx是否掛掉,當掛掉嘗試啟動nginx,如果啟動失敗則關閉keepalived服務,虛擬ip自動跳轉到備機
- 添加檢測腳本
vim /data/script/nginx_check.sh
A=`ps -C nginx --no-header |wc -l` if [ $A -eq 0 ];then systemctl start nginx sleep 2 if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then systemctl stop keepalived.service fi fi
- 配置keepalived配置文件
# 主機(85)配置 global_defs { router_id LVS_DEVEL } vrrp_script chk_nginx { script "/data/script/nginx_check.sh" interval 2 weight -20 } vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } track_script { chk_nginx } virtual_ipaddress { 172.20.53.250 } }
# 備機(87)配置 global_defs { router_id dreamer1 } vrrp_script chk_nginx { script "/etc/keepalived/nginx_check.sh" interval 2 weight -20 } vrrp_instance VI_1 { state BACKUP interface eth0 virtual_router_id 51 priority 90 advert_int 1 authentication { auth_type PASS auth_pass 1111 } track_script { chk_nginx } virtual_ipaddress { 172.20.53.250 } }
- 重啟並查看keepalived日志
tailf /var/log/messages -n 50 | grep 'Keepalive'
成功加載腳本