故障转移后使用 pg_rewind 将旧主库重新加入为副本
PostgreSQL复制命令
# Prerequisite (must be set BEFORE the incident): wal_log_hints = on OR data checksums; full_page_writes = on
pg_controldata $PGDATA | grep -E 'wal_log_hints|checksum'
# 1) The old primary must be stopped:
pg_ctl -D $PGDATA stop -m fast
# 2) Dry run first:
pg_rewind --target-pgdata=$PGDATA --source-server='host=<new_primary_host> port=5432 user=postgres dbname=postgres' --progress --dry-run
# 3) Actual rewind + standby configuration (standby.signal + primary_conninfo):
pg_rewind --target-pgdata=$PGDATA --source-server='host=<new_primary_host> port=5432 user=postgres dbname=postgres' --progress --write-recovery-conf
# 4) Review postgresql.auto.conf copied from the source (port, primary_slot_name), then start:
pg_ctl -D $PGDATA start作用
通过从新主库复制 timeline 分叉点之后变化的块,使旧主库的数据目录与新主库一致;无需完整 basebackup,几分钟内即可将其变为副本。
适用场景
当旧主库在故障转移/提升后恢复,并且落后于新 timeline、存在分叉的变更时。
注意
故障转移后留在旧主库上、从未到达新主库的事务会被永久删除。pg_rewind 还会从源端复制配置文件(postgresql.conf、postgresql.auto.conf、pg_hba.conf);启动前请修正端口和复制槽设置。如果分叉点以来所需的 WAL 已不在源端,请用 -c(--restore-target-wal)从归档获取。源连接需要超级用户或拥有文档中所列函数权限的角色。在 Patroni 中,通过 use_pg_rewind: true 自动完成。