在Debian上配置PostgreSQL的复制功能,通常涉及设置主服务器(Master)和从服务器(Slave)。以下是详细的步骤:
首先,确保在主服务器和从服务器上都安装了PostgreSQL。
sudo apt update
sudo apt install postgresql postgresql-contrib
postgresql.conf
编辑主服务器的postgresql.conf
文件,通常位于/etc/postgresql/<version>/main/
目录下。
sudo nano /etc/postgresql/<version>/main/postgresql.conf
找到并修改以下参数:
listen_addresses = '*' # 允许所有IP连接
wal_level = replica # 设置为replica以启用流复制
max_wal_senders = 10 # 最大WAL发送者数量
wal_keep_segments = 64 # 保留的WAL段数量
pg_hba.conf
编辑主服务器的pg_hba.conf
文件,以允许从服务器连接。
sudo nano /etc/postgresql/<version>/main/pg_hba.conf
添加以下行以允许从服务器连接:
host replication replicator <slave_ip>/32 md5
将<slave_ip>
替换为从服务器的IP地址。
在主服务器上创建一个用于复制的用户,并授予必要的权限。
sudo -u postgres psql
在psql命令行中执行以下SQL语句:
CREATE ROLE replicator WITH REPLICATION PASSWORD 'your_password' LOGIN;
将your_password
替换为你选择的密码。
在主服务器上重启PostgreSQL服务以应用更改。
sudo systemctl restart postgresql
在从服务器上停止PostgreSQL服务。
sudo systemctl stop postgresql
在主服务器上创建一个基础备份,并将其传输到从服务器。
sudo pg_basebackup -D /var/lib/postgresql/<version>/main -U replicator --password --wal-method=stream
按照提示输入复制用户的密码。
recovery.conf
在从服务器的数据目录中创建或编辑recovery.conf
文件。
sudo nano /var/lib/postgresql/<version>/main/recovery.conf
添加以下内容:
standby_mode = 'on'
primary_conninfo = 'host=<master_ip> dbname=postgres user=replicator password=your_password'
restore_command = 'cp /var/lib/postgresql/wal_archive/%f %p'
trigger_file = '/tmp/postgresql.trigger.5432'
将<master_ip>
替换为主服务器的IP地址,your_password
替换为复制用户的密码。
在从服务器上启动PostgreSQL服务。
sudo systemctl start postgresql
在主服务器上创建一个测试数据库或表,并在从服务器上检查是否同步。
在主服务器上:
sudo -u postgres psql
CREATE DATABASE testdb;
CREATE TABLE test_table (id SERIAL PRIMARY KEY, name VARCHAR(100));
INSERT INTO test_table (name) VALUES ('Test');
在从服务器上:
sudo -u postgres psql
\l # 列出所有数据库
\dt # 列出所有表
SELECT * FROM test_table;
如果从服务器上能够看到相同的数据,说明复制配置成功。
pg_stat_replication
视图。postgresql.conf
和recovery.conf
中的参数。通过以上步骤,你应该能够在Debian上成功配置PostgreSQL的复制功能。