網(wǎng)頁設(shè)計推薦網(wǎng)站百度推廣咨詢
配置 PostgreSQL
與 Keepalived
以實現(xiàn)高可用性通常包括以下步驟:
PostgreSQL 配置
-
安裝 PostgreSQL:在兩臺服務(wù)器上安裝相同版本的 PostgreSQL。
sudo yum install postgresql-server postgresql-contrib
-
初始化數(shù)據(jù)庫:在兩臺服務(wù)器上初始化 PGDATA 目錄。
sudo postgresql-setup initdb
-
配置主從復(fù)制:設(shè)置一臺服務(wù)器為主節(jié)點,另一臺為從節(jié)點。
-
在主服務(wù)器上:
- 修改
postgresql.conf
文件以允許復(fù)制。wal_level = replica max_wal_senders = 3 wal_keep_segments = 64 archive_mode = on archive_command = 'cp %p /path_to_archive/%f'
- 在
pg_hba.conf
文件中允許從服務(wù)器的連接。host replication all 192.168.9.183/32 md5
- 修改
-
在從服務(wù)器上:
- 停止 PostgreSQL 服務(wù)。
sudo systemctl stop postgresql
- 清空 PGDATA 目錄。
- 從主服務(wù)器上使用
pg_basebackup
進行基礎(chǔ)備份。pg_basebackup -h 192.168.9.195 -D /var/lib/pgsql/data -U replicator -v -P --wal-method=stream
- 創(chuàng)建
recovery.conf
文件以連接到主服務(wù)器。standby_mode = 'on' primary_conninfo = 'host=192.168.9.195 port=5432 user=replicator password=yourpassword' trigger_file = '/tmp/postgresql.trigger.5432'
- 停止 PostgreSQL 服務(wù)。
-
-
啟動 PostgreSQL 服務(wù):在兩臺服務(wù)器上啟動服務(wù)。
sudo systemctl start postgresql
Keepalived 配置
-
安裝 Keepalived:如前所述,在兩臺服務(wù)器上安裝
keepalived
。
sudo yum install keepalived -y
-
配置 Keepalived:編輯
/etc/keepalived/keepalived.conf
文件,在兩臺服務(wù)器上配置主從。-
在主服務(wù)器上:
vrrp_instance VI_1 {state MASTERinterface ens160virtual_router_id 51priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.9.200}track_script {chk_postgresql} }vrrp_script chk_postgresql {script "/usr/lib/keepalived/check_postgres.sh"interval 2weight 2 }
-
在從服務(wù)器上:
vrrp_instance VI_1 {state BACKUPinterface ens160virtual_router_id 51priority 50advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.9.200}track_script {chk_postgresql} }vrrp_script chk_postgresql {script "/usr/lib/keepalived/check_postgres.sh"interval 2weight 2 }
-
-
創(chuàng)建 PostgreSQL 檢查腳本:在兩臺服務(wù)器上創(chuàng)建腳本
/usr/lib/keepalived/check_postgres.sh
,用于檢查 PostgreSQL 服務(wù)狀態(tài)。#!/bin/bash PSQL="/usr/bin/psql" PGUSER="postgres" PGDATABASE="yourdatabase"$PSQL -U $PGUSER -d $PGDATABASE -c "select 1;" >/dev/null 2>&1 if [ $? != 0 ]; thenexit 1 fi exit 0
確保腳本可執(zhí)行:
sudo chmod +x /usr/lib/keepalived/check_postgres.sh
-
啟動 Keepalived:在兩臺服務(wù)器上啟動 Keepalived 服務(wù)。
sudo systemctl start keepalived sudo systemctl enable keepalived
測試和
驗證
- 驗證主從復(fù)制:確保主從復(fù)制正確設(shè)置且在運行。
- 測試 Failover:嘗試停止主服務(wù)器上的 PostgreSQL 服務(wù),確保 Keepalived 將虛擬 IP 地址轉(zhuǎn)移到從服務(wù)器。
- 監(jiān)控日志:查看 Keepalived 和 PostgreSQL 日志,確保沒有錯誤。
配置 PostgreSQL
和 Keepalived
時,一定要考慮數(shù)據(jù)一致性和故障轉(zhuǎn)移的機制。這通常涉及仔細的規(guī)劃和測試,以確保在生產(chǎn)環(huán)境中可靠地運行。