在CentOS上搭建PostgreSQL集群可以采用多种方案,包括主从复制、流复制以及使用第三方工具如repmgr或Patroni等。以下是几种常见的搭建方案:
1. PostgreSQL主从复制
主从复制是一种常见的高可用性策略,适用于需要读取操作负载分担的场景。
步骤:
- 安装PostgreSQL:在两台节点上分别安装PostgreSQL。
yum install -y postgresql-server postgresql-contrib
- 配置主节点和从节点:
- 主节点配置(
/etc/postgresql/10/main/postgresql.conf
):
listen_addresses = '*' port = 5432 wal_level = replica max_wal_senders = 2 wal_keep_segments = 16 wal_sender_timeout = 60
- 从节点配置类似,修改
listen_addresses
为对应的主节点IP。
- 初始化数据库:
/usr/pgsql-10/bin/postgresql-10-setup initdb
- 启动数据库服务:
systemctl enable postgresql systemctl start postgresql
- 配置pg_hba.conf:允许从节点连接到主节点。
host replication replica 192.168.1.2/32 md5
- 创建复制用户:
CREATE ROLE replica WITH LOGIN REPLICATION PASSWORD 'replica_password';
- 从主节点复制数据:
pg_basebackup -h master_ip -U replica -D /var/lib/pgsql/data -P -X stream -R
- 启动从节点:
systemctl start postgresql
2. 使用repmgr实现主备集群
repmgr是一个开源工具,用于管理PostgreSQL服务器集群内的复制和故障转移。
步骤:
- 安装repmgr:
yum install -y repmgr
-
配置repmgr:在每个节点上编辑
/etc/repmgr.conf
文件,配置节点信息。 -
初始化repmgr:
repmgr init -r /var/lib/pgsql/data
- 启动repmgr服务:
systemctl enable repmgr systemctl start repmgr
- 验证复制状态:
repmgr cluster show
3. PostgreSQL流复制(Streaming Replication)
流复制是一种高效的高可用性解决方案,可以在主服务器和一个或多个从服务器之间实现数据的实时复制。
步骤:
- 配置主节点:
- 编辑
postgresql.conf
文件,设置listen_addresses
为'*'
,开启归档模式archive_mode on
,设置归档命令等。 - 编辑
pg_hba.conf
文件,允许从节点连接。
- 创建复制用户:
CREATE ROLE replica WITH LOGIN REPLICATION PASSWORD 'replica_password';
- 从主节点复制数据:
pg_basebackup -h master_ip -U replica -D /var/lib/pgsql/data -P -X stream -R
- 配置从节点:
- 编辑从节点的
postgresql.conf
文件,设置primary_conninfo
指向主节点。 - 启动从节点。
以上方案可以根据具体需求选择,如果需要更高的可用性和自动故障转移,可以考虑使用repmgr结合etcd或Patroni等工具实现更复杂的集群管理。