安装postgresql请见:https://blog.csdn.net/qq_19402941/article/details/79392419
1.主库创建流复制角色
CREATE ROLE app_rep LOGIN replication ENCRYPTED PASSWORD 'passwd@123';
2.主库增加pg_hba.conf授信,在最后增加从库的IP,允许免密访问
vim /var/lib/pgsql/10/data/pg_hba.conf
host replication all 从库地址192.168.1.xx/32 trust
3.启动主库数据服务
systemctl start postgresql-10
4.从库安装好PostgreSQL10,需要initdb,然后执行
pg_basebackup -D /var/lib/pgsql/10/data -h 192.168.2.xx -p 5432 -U app_rep -X stream
备注:
-h,主库主机,-p,主库服务端口;
-U,复制用户;
-D,输出到指定目录;
5.创建恢复文件recovery.conf
cp /usr/pgql-10/share/recovery.conf.sample /var/lib/pgsql/10/data/recovery.conf
vim /var/lib/pgsql/10/data/recovery.conf
recovery_target_timeline = 'latest'
standby_mode = on
primary_conninfo = 'host=主库地址10.10.10.xx port=5432 user=同步用的用户名 password=密码'
6.修改pg_hba.conf文件,为以后主从切换做准备
vim /var/lib/pgsql/10/data/pg_hba.conf
host replication all 主库地址192.168.1.xx/32 trust
7.修改data文件夹下postgresql.conf,从库可以查询
vim /var/lib/pgsql/10/data/postgresql.conf
hot_standby = on #在备份的同时允许查询
8.启动从库数据服务
systemctl start postgresql-10
主从数据库切换
1.关闭主数据库
systemctl stop postgresql-10
2.激活备库
切换到postgrsql用户
su postgres
激活备库
/usr/pgsql-10/bin/pg_ctl -D /var/lib/pgsql/10/data promote
查看状态(in archive recovery==备库,in production==主库)
/usr/pgsql-10/bin/pg_controldata -D /var/lib/pgsql/10/data | grep 'Database cluster state'
3.在主库的data文件夹下创建recovery.conf文件
vim /var/lib/pgsql/10/data/recovery.conf
recovery_target_timeline = 'latest'
standby_mode = on
primary_conninfo = 'host=从库地址10.10.10.xx port=5432 user=同步用的用户名 password=密码'
4.重新启动数据库
systemctl start postgresql-10
5.查看状态
/usr/pgsql-10/bin/pg_controldata -D /var/lib/pgsql/10/data | grep 'Database cluster state'
参考:https://blog.csdn.net/unmobile/article/details/80154330
https://www.laomm.com/post/372.html