標籤:
一、功能
Keepalived通過對伺服器集區中的對象進行健全狀態檢查,同時實現了對失效機器和服務的故障隔離,並把其從服務池中刪除;如果失效的機器或者服務恢複正常,Keepalived會自動將其加入服務池中。PostgreSQL資料庫有時會發生宕機的情況,因此使用Keepalived對兩台伺服器進行配置,主伺服器負責使用者互動,從伺服器負責即時備份,當發生故障時可以實現高可用。
二、工作原理
當 Master 與 Slave 均運作正常時, Master負責服務,Slave負責備份;
當 Master 掛掉Slave 正常時, Slave接管服務,同時關閉主從複製功能;
當 Master 恢複正常,則從Slave同步資料,同步資料之後關閉主從複製功能,恢複Master身份,於此同時Slave等待Master同步資料完成之後,恢複Slave身份。
三、配置過程
環境:Master: 10.6.1.143
Slave: 10.6.1.144
Virtural IP Address (VIP): 10.6.1.200
步驟:
1、在Master和Slave上安裝Keepalived
$ sudo apt-get install keepalived
2、修改Master和Slave的/etc/hosts檔案
$ sudo vim /etc/hosts
3、預設安裝完成keepalived之後是沒有設定檔的,因此我們需要手動建立:
首先,在Master上建立如下設定檔:
$ sudo vim /etc/keepalived/keepalived.conf
該檔案主要配置監控指令碼、監控時間、監控網路、虛機IP等資訊
! Configuration File for keepalived
global_defs {
router_id PostgreSQL-HA2
}
vrrp_script monitor_pgsql_status {
script "/etc/keepalived/scripts/monitor_pgsql_status.sh"
interval 30
}
vrrp_instance V_PostgreSQL-HA {
state BACKUP
interface eth0
notify_master /etc/keepalived/scripts/to_master.sh
notify_backup /etc/keepalived/scripts/to_backup.sh
notify_stop /etc/keepalived/scripts/to_backup.sh
virtual_router_id 51
priority 80
advert_int 1
garp_master_delay 10
authentication {
auth_type PASS
auth_pass password
}
track_script {
monitor_pgsql_status
}
virtual_ipaddress {
虛擬IP/連接埠 dev eth1
}
}
然後,在Slave上建立如下設定檔:
$ sudo vim /etc/keepalived/keepalived.conf! Configuration File for keepalived
global_defs {
router_id PostgreSQL-HA2
}
vrrp_script monitor_pgsql_status {
script "/etc/keepalived/scripts/monitor_pgsql_status.sh"
interval 30
}
vrrp_instance V_PostgreSQL-HA {
state BACKUP
interface eth0
notify_master /etc/keepalived/scripts/to_master.sh
notify_backup /etc/keepalived/scripts/to_backup.sh
notify_stop /etc/keepalived/scripts/to_backup.sh
virtual_router_id 51
priority 80
advert_int 1
garp_master_delay 10
authentication {
auth_type PASS
auth_pass password
}
track_script {
monitor_pgsql_status
}
virtual_ipaddress {
虛擬IP/連接埠 dev eth1
}
}
4、在Master和Slave上建立監控Redis的指令碼
注意:
1. 需要在PostgreSQL中建立postgres使用者,並賦予SELECT執行許可權(可其許可權限定至最小範圍);
2. 根據實際情況修改變數psql和VIP。
$ mkdir /etc/keepalived/scripts
$ vim /etc/keepalived/scripts/monitor_pgsql_status.sh
5、編寫以下負責運作的關鍵指令碼:
notify_master /etc/keepalived/scripts/to_master.sh
notify_backup /etc/keepalived/scripts/to_backup.sh
因為Keepalived在轉換狀態時會依照狀態來呼叫:
當進入Master狀態時會呼叫notify_master,在to_master.sh中執行相應的操作
當進入Backup狀態時會呼叫notify_backup,在to_backup.sh中執行相應的操作
當Keepalived程式終止時則呼叫notify_backup
6、給指令碼都加上可執行許可權:
$ sudo chmod +x /etc/keepalived/scripts/*.sh
可以使用如下命令進行主從模式的切換:
sudo su
/etc/init.d/keepalived restart
附:agent部署過程:
解壓安裝DBCheck包
為start.sh何stop.sh指令碼賦予許可權 並測試
進入/etc/keepalived/scripts目錄
在to_master.sh指令碼最後添加:cd /home/test/DBCheck && ./start.sh conf
在to_backup.sh指令碼開頭添加:cd /home/test/DBCheck && ./stop.sh kill
使用Keepalived實現PostgreSQL的高可用