歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux管理 >> Linux配置

Keeplived配置Nginx雙機高可用

一、簡介
不管是Keepalived還是Heartbeat做高可用,其高可用,都是站在服務器腳本去說的高可用,而不是服務的角度。
也就是說,如果服務器DOWN機或者網絡出現故障,高可用是可以實現自動切換的。如果運行的服務,比如Nginx掛掉
這些高可用軟件是意識不到的,需要自己寫腳本去實現服務的切換。

二、安裝配置Keepalived
# ./configure
# make
# make install
# cp /usr/local/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/
# cp /usr/local/etc/sysconfig/keepalived /etc/sysconfig/
# cp /usr/local/sbin/keepalived /usr/bin/
# chkconfig --add keepalived 
# mkdir /etc/keepalived/
# cp /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/

編輯MASTER的主配置文件(MASTER: 1.1.1.1)
# vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
   router_id LVS_DEVEL
}
vrrp_script chk_nginx {
        script "/opt/monnginx.sh"
        interval 2
        weight 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass mdnginx
    }
    virtual_ipaddress {
        1.1.1.100
    }
    track_script {
        chk_nginx
  }
}

編輯BACKUP的主配置文件(BACKUP:1.1.1.2)
# vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
   router_id LVS_DEVEL
}
vrrp_script chk_nginx {
        script "/opt/monnginx.sh"
        interval 2
        weight 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass mdnginx
    }
    virtual_ipaddress {
        1.1.1.100
    }
    track_script {
        chk_nginx
  }
}

三、啟動服務與腳本編寫(主機和備機都要執行)
# service nginx start
# service keepalived start

編寫監控Nginx的腳本
# vim /opt/monnginx.sh
#!/bin/bash
# author: honway.liu
# date: 2013-03-15

if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
        service nginx start
fi
sleep 3
if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
        service keepalived stop
fi

改進腳本,加上報警功能。
# vim /opt/monnginx.sh

#!/bin/bash
# author: honway.liu
# date: 2013-03-15
IPADDR=$(ip addr show eth0|awk '{print $2}' | sed -n 3p)
contact=([email protected])
num=${#contact[@]}
function email() {
for ((i=0;i<num;i++));do
        echo "$IPADDR service problem" | mail -s "WARNING" ${contact[i]} -- -f [email protected]
done
}

if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
        service nginx start
fi
email

sleep 3

if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
        service keepalived stop
email
fi
這裡的報警使用的是139郵箱,在139郵箱裡面設置有郵件的時候,通知到手機,並且以長短信的方式。
需要開戶本機的sendmail服務。
Copyright © Linux教程網 All Rights Reserved