温馨提示×

centos中postgresql如何主从

小樊
34
2026-10-06 08:39:35
栏目: 云计算

在 CentOS 上配置 PostgreSQL 主从(流复制,Streaming Replication) 是常见做法。下面以 PostgreSQL 12+ 为例,说明基本步骤(CentOS 7/8 通用)。


一、环境准备

假设:

  • 主库(Master):192.168.1.10
  • 从库(Standby):192.168.1.11
  • PostgreSQL 数据目录:/var/lib/pgsql/12/data
  • 系统用户:postgres

二、主库配置(Master)

1. 安装 PostgreSQL

yum install -y postgresql12-server postgresql12
/usr/pgsql-12/bin/postgresql-12-setup initdb
systemctl enable postgresql-12
systemctl start postgresql-12

2. 修改 postgresql.conf

listen_addresses = '*'
wal_level = replica
max_wal_senders = 10
wal_keep_size = 1GB
hot_standby = on

3. 配置 pg_hba.conf

允许从库连接:

host    replication     repluser        192.168.1.11/32    md5

4. 创建复制用户

su - postgres
psql
CREATE ROLE repluser WITH REPLICATION PASSWORD 'yourpassword' LOGIN;

5. 重启主库

systemctl restart postgresql-12

三、从库配置(Standby)

1. 安装 PostgreSQL(不初始化)

yum install -y postgresql12-server postgresql12

2. 使用 pg_basebackup 复制主库数据

su - postgres
pg_basebackup -h 192.168.1.10 -U repluser -D /var/lib/pgsql/12/data -P --wal-method=stream

3. 创建 standby.signal

touch /var/lib/pgsql/12/data/standby.signal

4. 配置 postgresql.conf(从库)

primary_conninfo = 'host=192.168.1.10 port=5432 user=repluser password=yourpassword'

5. 启动从库

systemctl enable postgresql-12
systemctl start postgresql-12

四、验证主从状态

主库执行:

SELECT * FROM pg_stat_replication;

看到从库连接即成功。

从库执行:

SELECT pg_is_in_recovery();

返回 t 表示从库。


五、常见补充说明

  • 只读从库:从库默认只读
  • 同步复制(可选):
    synchronous_commit = on
    synchronous_standby_names = 'standby1'
    
  • 自动故障切换:建议配合 repmgr 或 Patroni

如果你需要:

  • CentOS 6 / 特定 PG 版本
  • Docker 方式
  • 异步 / 同步复制详解
  • repmgr 高可用方案

可以继续告诉我。

0 踩