在Debian上配置PostgreSQL复制涉及几个步骤,包括设置主服务器和从服务器。以下是一个基本的指南:
主服务器配置安装PostgreSQL
sudo apt updatesudo 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
添加以下行以允许从服务器连接:
hostreplication replicator <从服务器IP>/32md5
重启PostgreSQL服务
sudo systemctl restart postgresql
创建复制用户在主服务器上创建一个用于复制的用户:
sudo -u postgres psqlCREATE USER replicator WITH REPLICATION PASSWORD 'your_password' LOGIN;GRANT ALL PRIVILEGES ON DATAbase your_database TO replicator;
安装PostgreSQL
sudo apt updatesudo 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
添加以下行以允许从主服务器连接:
hostreplication replicator <主服务器IP>/32md5
启动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 psqlCREATE DATAbase test_db;\c test_dbCREATE TABLE test_table (id SERIAL PRIMARY KEY, name VARCHAR(100));INSERT INTO test_table (name) VALUES ('Test Data');
在从服务器上检查是否同步:
sudo -u postgres psql\c test_dbSELECT * FROM test_table;
如果数据已经同步,说明配置成功。
注意事项确保主服务器和从服务器的时间同步。确保防火墙允许PostgreSQL端口(默认5432)的通信。定期检查复制状态,可以使用pg_stat_replication
视图。通过以上步骤,你应该能够在Debian上成功配置PostgreSQL复制。