CentOS7 安裝keepalived 實現 nginx 主備高可用
0x00 實驗環境
本次實驗所用環境如下:
虛擬機器:VirtualBox 6.1 建立的兩臺CentOS7虛擬機器
OS:CentOS Linux release 7.7.1908 (Core)
Nginx :nginx version: nginx/1.20.1
Keepalived:Keepalived v1.3.5 (03/19,2017), git commit v1.3.5-6-g6fa32f2
限制:此方法要求伺服器的hostname必須不能包含“nginx”字串,否則可能會影響到監控指令碼的執行(未驗證)。
0x01 禁用SELinux:
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config setenforce 0
0x02 安裝epel:
rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org yum install https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm
0x03 安裝keepalived:
yum install keepalived -y
執行日誌位置:
/var/log/messages
0x04 修改配置檔案:
master節點配置檔案內容(vim /etc/keepalived/keepalived.conf):
! Configuration File for keepalived global_defs { router_id LVS_nginx1 } vrrp_script trackngx { script "/root/chk_nginx_pid.sh" interval 5 } vrrp_instance VI_1 { state MASTER interface enp0s3 virtual_router_id 51 priority 150 advert_int 1 authentication { auth_type PASS auth_pass 51yunjiance.com } virtual_ipaddress { 172.171.19.238 } track_script { trackngx } }
backup節點配置檔案內容(vim /etc/keepalived/keepalived.conf):
! Configuration File for keepalived global_defs { router_id LVS_nginx2 } vrrp_script trackngx { script "/root/chk_nginx_pid.sh" interval 5 } vrrp_instance VI_1 { state BACKUP interface enp0s3 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 51yunjiance.com } virtual_ipaddress { 172.171.19.238 } track_script { trackngx } }
0x05 新增監控nginx程序指令碼(兩臺機器都要新增):
該指令碼會嘗試先啟動nginx,如果啟動失敗,則停止keepalived服務,保證節點順利下線。
注意,此指令碼會自動啟動nginx,可能對運維時產生一定的影響。
vim /root/chk_nginx_pid.sh
#!/bin/sh nginxpid=$(ps -C nginx --no-header | wc -l) if [ $nginxpid -eq 0 ] then systemctl start nginx sleep 3 nginxpid=$(ps -C nginx --no-header | wc -l) if [ $nginxpid -eq 0 ];then systemctl stop keepalived fi fi
修改為可執行檔案:
chmod +x chk_nginx_pid.sh
0x06 設定自啟動並啟動keepalived
keepalived隨系統自啟動:
systemctl enable keepalived
啟動keepalived:
systemctl start keepalived
0x07 驗證
手動停止nginx後會自動拉起nginx,關閉其中一臺主機後,另外一臺主機稍後會自動接管虛擬IP。
////////////////////////////////
////////Sixi.Let it be.../////
//////////////////////////////