兩臺機器都執行yum install -y keepalived
兩臺機器都安裝nginx,其中133上已經編譯安裝過nginx,134上須要yum安裝nginx:html
yum install -y epel-release yum install -y nginx
> /etc/keepalived/keepalived.conf vim /etc/keepalived/keepalived.conf
global_defs { notification_email { chinantfy@qq.com //接收通知郵件的郵箱 } notification_email_from root@chinantfy.com //發送通知郵件的郵箱 smtp_server 127.0.0.1 smtp_connect_timeout 30 router_id LVS_DEVEL } vrrp_script chk_nginx { script "/usr/local/sbin/check_ng.sh" //檢查nginx的sh路徑 interval 3 } vrrp_instance VI_1 { state MASTER //主上爲MASTER,備用上爲BACKUP interface ens33 //用哪一個網卡通訊 virtual_router_id 51 //主和備用同樣 priority 100 //備用要比主的低 advert_int 1 authentication { auth_type PASS auth_pass chinantfy>com } virtual_ipaddress { 192.168.127.100 //設置一個公用ip } track_script { chk_nginx } }
vim /usr/local/sbin/check_ng.sh
#!/bin/bash #時間變量,用於記錄日誌 d=`date --date today +%Y%m%d_%H:%M:%S` #計算nginx進程數量 n=`ps -C nginx --no-heading|wc -l` #若是進程爲0,則啓動nginx,而且再次檢測nginx進程數量, #若是還爲0,說明nginx沒法啓動,此時須要關閉keepalived if [ $n -eq "0" ]; then /etc/init.d/nginx start n2=`ps -C nginx --no-heading|wc -l` if [ $n2 -eq "0" ]; then echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log systemctl stop keepalived fi fi
給腳本755權限linux
chmod 755 /usr/local/sbin/check_ng.sh systemctl start keepalived //133啓動服務
nginx默認配置文件在
/usr/local/nginx/conf/vhost/default.conf 文件能夠找到
nginx
> /etc/keepalived/keepalived.conf vim /etc/keepalived/keepalived.conf
global_defs { notification_email { chinantfy@qq.com //接收通知郵件的郵箱 } notification_email_from root@chinantfy.com //發送通知郵件的郵箱 smtp_server 127.0.0.1 smtp_connect_timeout 30 router_id LVS_DEVEL } vrrp_script chk_nginx { script "/usr/local/sbin/check_ng.sh" //檢查nginx的sh路徑 interval 3 } vrrp_instance VI_1 { state BACKUP //主上爲MASTER,備用上爲BACKUP interface ens33 //用哪一個網卡通訊 virtual_router_id 51 //主和備用同樣 priority 90 //備用要比主的低 advert_int 1 authentication { auth_type PASS auth_pass chinantfy>com } virtual_ipaddress { 192.168.127.100 //設置一個公用ip } track_script { chk_nginx } }
134上編輯監控腳本vim
vim /usr/local/sbin/check_ng.sh
#!/bin/bash #時間變量,用於記錄日誌 d=`date --date today +%Y%m%d_%H:%M:%S` #計算nginx進程數量 n=`ps -C nginx --no-heading|wc -l` #若是進程爲0,則啓動nginx,而且再次檢測nginx進程數量, #若是還爲0,說明nginx沒法啓動,此時須要關閉keepalived if [ $n -eq "0" ]; then systemctl start nginx n2=`ps -C nginx --no-heading|wc -l` if [ $n2 -eq "0" ]; then echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log systemctl stop keepalived fi fi
chmod 755 /usr/local/sbin/check_ng.sh > /usr/share/nginx/html/index.html //因爲nginx是yum安裝,因此默認配置文件路徑與133不一樣 vim /usr/share/nginx/html/index.html BACKUP BACKUP systemctl start keepalived //134啓動服務
master開啓時,在133用ip addr 命令能夠看到vip ,backup開啓時在134能夠查到vip,
若是切換服務失敗,就檢查防火牆,iptables或者selinux 後端