1. 程式人生 > >ubuntu keepalived 筆記

ubuntu keepalived 筆記

環境:

master:Ubuntu 12.04(192.168.31.186)
backup: Ubuntu 12.04(192.168.31.110)
VIP: 192.168.31.100

keepalived的原理可以這樣簡單理解:

keepalived安裝在兩臺物理伺服器上,並相互監控對方是否在正常執行。
當master正常的時候:master上的keepalived會繫結vip(192.168.8.100)

tail -f /var/log/syslog

Feb 18 05:41:41 keepalived1 Keepalived_vrrp[2561]: VRRP_Instance(VI_1) Sending gratuitous ARPs on
eth0 for 192.168.31.100 Feb 18 05:41:41 keepalived1 Keepalived_healthcheckers[2560]: Netlink reflector reports IP 192.168.31.100 added Feb 18 05:41:46 keepalived1 Keepalived_vrrp[2561]: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth0 for 192.168.31.100

當master發生故障的時候,backup上的keepalived會檢測到,並且繫結vip(192.168.8.100)
即虛擬IP漂移至backup
當master恢復vip又重新繫結

安裝

apt-get install keepalived

keepalived配置檔案

vim /etc/keepalived/keepalived.conf
global_defs {
    router_id L1
}
vrrp_instance VI_1 {
    state MASTER //設定伺服器模式,需要大寫,備用機可以寫 state BACKUP
    interface eth0
    virtual_router_id 51 //VRRP組名,兩個節點的設定必須一樣,以指明各個節點屬於同一VRRP組
    priority 100 //主節點的優先順序(1-254之間),備用節點必須比主節點優先順序低
advert_int 1 authentication { //設定驗證資訊,兩個節點必須一致 auth_type PASS auth_pass 123456 } virtual_ipaddress { //指定虛擬IP, 兩個節點設定必須一樣 192.168.31.100 }

mastr和backup的區別是 state和priority

啟動

service keepalived start

測試

在兩臺機器上安裝nginx,安裝步驟省略
安裝完成後修改nginx預設頁面為不同的內容
然後訪問 http://192.168.31.100

預設應該顯示192.168.31.186的內容
然後 重啟192.168.31.186或停止192.168.31.186的keepalived 服務
這重新整理頁面
顯示的是192.168.31.110的內容
如果192.168.31.186恢復正常vip會切回到192.168.31.186上

監控http服務

修改配置檔案

vim /etc/keepalived/keepalived.conf 


global_defs {
    router_id master
}
vrrp_script chk_nginx_port {
    script "/check_nginx.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 1111
   }
   virtual_ipaddress {
       192.168.31.100
   }
   track_script {
      chk_nginx_port
   }
}
vim /check_nginx.sh


#!/bin/bash 


V_NUM=`eval "netstat -nlpt | grep '80' | wc -l"`

if [ $V_NUM -lt 1 ];then
    /etc/init.d/keepalived stop
    exit
fi

檢查80埠如果沒監聽,就停止keepalived服務,vip就轉到192.168.31.110上

這時就需要人為的修復http服務,然後重啟keepalived服務