PostgreSQL 14 主从库安装配置
主库
安装
shell
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum install -y postgresql14-server
## 主库初始化数据库
/usr/pgsql-14/bin/postgresql-14-setup initdb
## 启动
sudo systemctl enable postgresql-14
sudo systemctl start postgresql-14
初始化
shell
su - postgres
psql
## 创建 postgres 密码
ALTER USER postgres WITH PASSWORD '123456';
# #创建 从库 replica 用户密码
CREATE ROLE replica login replication encrypted password 'replica';
## 检查账号
SELECT usename from pg_user;
# 结果如下
# usename
# ----------
# postgres
# replica
# (2 rows)
# 查看权限
SELECT rolname from pg_roles;
# 结果如下
# rolname
# ----------
# postgres
# replica
# (2 rows)
# 退出
\q
exit
配置
pg_hba.conf
shell
vi /var/lib/pgsql/14/data/pg_hba.conf
## 添加从库网段
host all all 0.0.0.0/0 trust
# replication privilege.
local replication all peer
host replication replica 192.168.0.9/25 md5
postgresql.conf
shell
vi /var/lib/pgsql/14/data/postgresql.conf
listen_addresses = '*'
wal_level = hot_standby
synchronous_commit = remote_write
# synchronous_commit 参考文档可选其他 on
max_wal_senders = 32 #同步最大的进程数量
wal_sender_timeout = 60s #流复制主机发送数据的超时时间
max_connections = 100 #最大连接数,从库的max_connections必须要大于主库的
重启
shell
sudo systemctl restart postgresql-14
从库
安装
shell
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum install -y postgresql14-server
## 从主库同步数据
pg_basebackup -D /var/lib/pgsql/14/data -h 192.168.1.12 -p 5432 -U replica -X stream -P
配置
postgresql.conf
shell
vi /var/lib/pgsql/14/data/postgresql.conf
## 移除或注释 wal_level
wal_level = xxx
## 修改或添加以下
primary_conninfo = 'host=192.168.1.12 port=5432 user=replica password=replica'
recovery_target_timeline = 'latest'
创建 standby.signal
shell
vi /var/lib/pgsql/14/data/standby.signal
standby_mode = on
## 声明从库
权限
shell
chown -R postgres.postgres /var/lib/pgsql/14/data
启动
shell
sudo systemctl enable postgresql-14
sudo systemctl start postgresql-14
测试同步
主库
shell
ps aux |grep sender
# 返回 postgres: walsender replica 192.168.0.9(56192) streaming 0/7000148
su - postgres
psql
select application_name, state, sync_priority, sync_state from pg_stat_replication;
# 返回 async
select pid,state,client_addr,sync_priority,sync_state from pg_stat_replication;
# 返回 async
从库
shell
ps aux |grep receiver
# 返回 postgres: walreceiver streaming 0/7000148