Keepalived在PostgreSQL高可用中的运用

一、需求背景

规避单web故障,单db故障,确保web对外稳定服务。解决db的单点问题成了需要突破的问题。

二、理论基础

阅读 https://github.com/chenzhiwei/linux/tree/master/keepalived

三、具体实施步骤

1、N台db安装Keepalived(N>=2),N台服务器之间做好PostgreSQL流复制主从。

关键知识:

a) Keepalived所有主库角色state为MASTER,配置为nopreempt;备库角色state为BACKUP,配置为nopreempt,且priority值高于主库。

b) PostgreSQL主备创建时,使用pg_basebackup可迅速创建流复制主从关系。

pg_basebackup -h master -p port -U replication_user-D slave_PGDATA -x -P

2、PostgreSQL主备探测和切换脚本

keepalived.conf

vrrp_script check_pg {
script "/usr/local/bin/pg_check.sh" #探测脚本
interval 2
}
vrrp_instance VI_1 {
    state MASTER
    nopreempt
    interface eth1
    virtual_router_id 50
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1024
    }
    track_script {
        check_pg
    }
    virtual_ipaddress {
        x.x.x.x
    }
notify_master "/usr/local/bin/pg_trigger.sh" #当Keepalived state切换为master时,执行的动作

pg_check.sh

#!/bin/sh

source /etc/profile
LOGFILE="/var/log/PostgeSQL-State.log"
EXITMASTER=""
EXITSLAVE=""

master () {
psql -U postgres -p 6543  -d ott-vms -c "SELECT 1"; >> /dev/null 2>&1
[[ $? -eq 0 ]] && EXITMASTER=0 || EXITMASTER=1
}

master
if [ ${EXITMASTER} -ne 0 ]
then
    echo "---`date +%Y%m%d%H%M`---" >>${LOGFILE}
    echo "Master Downed,Let Slave to New Master." >>${LOGFILE}
    exit 1
else
    exit 0
fi

pg_trigger.sh

#!/bin/sh
su -l postgres -c "touch /cache1/PostgreSQL/9.1/data/postgresql.trigger"
weinxin
聂扬帆博客
一个分享IT运维相关工作经验和实战技巧的个人博客

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: