1. 程式人生 > >用keeplived實現nginx高可用

用keeplived實現nginx高可用

1.上傳keepalived安裝包:

cd /usr/local/source
rz

2.解壓

yum install unzip
unzip keepalived-1.3.4.zip

3.安裝:

mv keepalived-1.3.4 /usr/local/keepalived/
cd /usr/local/keepalived/
chmod 775 
chmod 775 configure
./configure --prefix=/data/program/keepalived --sysconf=/etc 
make && make install

4.修改配置檔案

cd /etc/keepalived/
vim keepalived.conf

keepalived.conf:


global_defs {
    notification_email {
        [email protected]
    }
    notification_email_from [email protected]
    smtp_server smtp.hysec.com
    smtp_connection_timeout 30
    router_id nginx_master
}
vrrp_script chk_http_port {
    script "/usr/local/src/check_nginx_pid.sh"
    interval 2
    weight 2
}
vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 66
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
        chk_http_port
    }
    virtual_ipaddress {
        192.168.126.128
    }
}

5.建立check_nginx_pid.sh檔案

 cd /usr/local/src/
 mkdir check_nginx_pid.sh

check_nginx_pid.sh內容:

#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then
      /usr/local/nginx/sbin/nginx                #重啟nginx
      if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then    #nginx重啟失敗,則停掉keepalived服務,進行VIP轉移
              killall keepalived
      fi
fi

修改許可權:

chmod 775 check_nginx_pid.sh

6.backup的安裝和配置跟master一樣,除了keepalived.conf:

global_defs {
    notification_email {
        [email protected]
    }
    notification_email_from [email protected]
    smtp_server smtp.hysec.com
    smtp_connection_timeout 30
    router_id nginx_backup
}
vrrp_script chk_http_port {
    script "/usr/local/src/check_nginx_pid.sh"
    interval 2
    weight 2
}
vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 66
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
        chk_http_port
    }
    virtual_ipaddress {
        192.168.126.128
    }
}

6.啟動master,backup的keepalived:

/data/program/keepalived/sbin/keepalived

7.檢視日誌:
在這裡插入圖片描述
在這裡插入圖片描述
8.測試keepalived master宕機的表現
關閉linux

shutdown -h now

檢視backup的日誌:
在這裡插入圖片描述
backup變成了master.
再重啟master檢視日誌:
在這裡插入圖片描述
重啟後還是master
檢視backup日誌:
在這裡插入圖片描述
又變回backup
git上配置檔案地址:https://github.com/shidebin/installationPackage