在CentOS上配置PostgreSQL的复制功能,通常是为了实现高可用性、负载均衡或数据备份。以下是配置PostgreSQL复制的基本步骤:
1. 准备工作主服务器(Master):配置为允许复制。从服务器(Slave):配置为连接到主服务器并接收数据。2. 配置主服务器2.1 编辑postgresql.conf
在主服务器上编辑 postgresql.conf
文件,确保以下参数设置正确:
listen_addresses = '*'# 允许所有IP连接wal_level = replica# 设置为replica以启用流复制max_wal_senders = 10 # 最大WAL发送者数量wal_keep_segments = 64 # 保留的WAL段数量
2.2 编辑 pg_hba.conf
在主服务器上编辑 pg_hba.conf
文件,添加从服务器的连接权限:
# TYPEDATAbaseUSERADDRESS METHODhostreplication replicator<从服务器IP>/32md5
2.3 创建复制用户在主服务器上创建一个用于复制的用户,并授予必要的权限:
CREATE USER replicator WITH REPLICATION PASSWORD 'your_password' LOGIN;
2.4 重启PostgreSQL服务sudo systemctl restart postgresql
3. 配置从服务器3.1 停止从服务器上的PostgreSQL服务sudo systemctl stop postgresql
3.2 备份主服务器的数据目录在主服务器上备份数据目录,并将其传输到从服务器:
sudo tar -czvf /path/to/backup.tar.gz /var/lib/pgsql/datascp /path/to/backup.tar.gz <从服务器IP>:/tmp/
3.3 在从服务器上恢复数据在从服务器上解压备份文件并恢复数据目录:
sudo tar -xzvf /tmp/backup.tar.gz -C /sudo chown -R postgres:postgres /var/lib/pgsql
3.4 编辑 postgresql.conf
在从服务器上编辑 postgresql.conf
文件,确保以下参数设置正确:
listen_addresses = '*'# 允许所有IP连接hot_standby = on # 启用热备模式
3.5 编辑 recovery.conf
在从服务器上创建 recovery.conf
文件,并添加以下内容:
standby_mode = 'on'primary_conninfo = 'host=<主服务器IP> dbname=postgres user=replicator password=your_password'restore_command = 'cp /var/lib/postgresql/archive/%f %p'trigger_file = '/tmp/postgresql.trigger.5432'
3.6 启动从服务器上的PostgreSQL服务sudo systemctl start postgresql
4. 验证复制状态在主服务器上执行以下SQL查询,查看复制状态:
SELECT * FROM pg_stat_replication;
在从服务器上执行以下SQL查询,查看是否成功连接到主服务器:
SELECT * FROM pg_stat_activity WHERE datname = 'postgres';
注意事项确保主服务器和从服务器的时间同步。定期检查复制状态,确保没有错误发生。根据实际需求调整 max_wal_senders
和 wal_keep_segments
参数。通过以上步骤,你可以在CentOS上成功配置PostgreSQL的复制功能。