在Debian上配置PostgreSQL复制涉及几个步骤,包括设置主服务器和从服务器。以下是一个基本的指南:
安装PostgreSQL
sudo apt update
sudo apt install postgresql postgresql-contrib
配置postgresql.conf
编辑主服务器的/etc/postgresql/<version>/main/postgresql.conf
文件:
sudo nano /etc/postgresql/13/main/postgresql.conf
找到并修改以下参数:
listen_addresses = '*' # 允许所有IP连接
wal_level = replica # 设置为replica以支持流复制
max_wal_senders = 10 # 最大WAL发送者数量
wal_keep_segments = 64 # 保留的WAL文件数量
配置pg_hba.conf
编辑主服务器的/etc/postgresql/<version>/main/pg_hba.conf
文件:
sudo nano /etc/postgresql/13/main/pg_hba.conf
添加以下行以允许从服务器连接:
host replication replicator <从服务器IP>/32 md5
重启PostgreSQL服务
sudo systemctl restart postgresql
创建复制用户 在主服务器上创建一个用于复制的用户:
sudo -u postgres psql
CREATE USER replicator WITH REPLICATION PASSWORD 'your_password' LOGIN;
GRANT ALL PRIVILEGES ON DATABASE your_database TO replicator;
安装PostgreSQL
sudo apt update
sudo apt install postgresql postgresql-contrib
停止PostgreSQL服务
sudo systemctl stop postgresql
复制主服务器的数据目录 停止从服务器上的PostgreSQL服务后,复制主服务器的数据目录到从服务器:
sudo rsync -a --progress /var/lib/postgresql/13/main/ /var/lib/postgresql/13/main/
编辑postgresql.conf
编辑从服务器的/etc/postgresql/13/main/postgresql.conf
文件:
sudo nano /etc/postgresql/13/main/postgresql.conf
找到并修改以下参数:
listen_addresses = '*' # 允许所有IP连接
wal_level = replica # 设置为replica以支持流复制
max_wal_senders = 10 # 最大WAL发送者数量
wal_keep_segments = 64 # 保留的WAL文件数量
hot_standby = on # 启用热备模式
编辑pg_hba.conf
编辑从服务器的/etc/postgresql/13/main/pg_hba.conf
文件:
sudo nano /etc/postgresql/13/main/pg_hba.conf
添加以下行以允许从主服务器连接:
host replication replicator <主服务器IP>/32 md5
启动PostgreSQL服务
sudo systemctl start postgresql
配置从服务器
在从服务器上创建一个恢复命令文件(例如/var/lib/postgresql/13/main/recovery.conf
):
sudo nano /var/lib/postgresql/13/main/recovery.conf
添加以下内容:
standby_mode = 'on'
primary_conninfo = 'host=<主服务器IP> dbname=your_database user=replicator password=your_password'
restore_command = 'cp /var/lib/postgresql/archive/%f %p'
trigger_file = '/tmp/postgresql.trigger.5432'
重启PostgreSQL服务
sudo systemctl restart postgresql
在主服务器上创建一个测试数据库和表,并插入一些数据:
sudo -u postgres psql
CREATE DATABASE test_db;
\c test_db
CREATE TABLE test_table (id SERIAL PRIMARY KEY, name VARCHAR(100));
INSERT INTO test_table (name) VALUES ('Test Data');
在从服务器上检查是否同步:
sudo -u postgres psql
\c test_db
SELECT * FROM test_table;
如果数据已经同步,说明配置成功。
pg_stat_replication
视图。通过以上步骤,你应该能够在Debian上成功配置PostgreSQL复制。