首页 > 代码库 > 使用Keepalived实现PostgreSQL的高可用
使用Keepalived实现PostgreSQL的高可用
一、功能
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等信息
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
}
}
$ sudo vim /etc/keepalived/keepalived.conf
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的高可用