postgresql备份与PITR恢复

前置条件:

postgresql:9.5.7datapath:/postgresql/databackpath:/postgresql/backup


数据准备:

test=# select * from test; id |         name         ----+----------------------  1 | qwe                   2 | asd                 (2 rows)


创建基础备份:

pg_basebackup需要指定一个超级用户或者具有REPLICATION权限的用户

pg_basebackup -h 192.168.56.117 -U repl -W -p 5432 -v -P -Xs -Fp -D /postgresql/backup/ -l backup_test

[postgres@localhost postgresql]$ pg_basebackup -h 192.168.56.117 -U repl -W -p 5432 -v -P -Xs -Fp -D /postgresql/backup/ -l backup_testPassword: pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedtransaction log start point: 0/2000028 on timeline 1pg_basebackup: starting background WAL receiver29983/29983 kB (100%), 1/1 tablespace                                         transaction log end point: 0/2000130pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: base backup completed

备份完成后会在备份目录/postgresql/backup下生成原格式文件(-Fp),可以配置为压缩模式(-Ft),并记录备份时段的日志(-Xs),在归档日志目录下,生成备份标记文件:

[postgres@localhost postgresql]$ ll /postgresql/archive/总用量 32772-rw-------. 1 postgres postgres 16777216 9月   8 10:02 000000010000000000000001-rw-------. 1 postgres postgres 16777216 9月   8 10:02 000000010000000000000002-rw-------. 1 postgres postgres      288 9月   8 10:02 000000010000000000000002.00000028.backup

查看备份标记文件,可以获取备份完成时间,对应的日志文件位置等信息:

[postgres@localhost postgresql]$ cat /postgresql/archive/000000010000000000000002.00000028.backup START WAL LOCATION: 0/2000028 (file 000000010000000000000002)STOP WAL LOCATION: 0/2000130 (file 000000010000000000000002)CHECKPOINT LOCATION: 0/2000060BACKUP METHOD: streamedBACKUP FROM: masterSTART TIME: 2020-09-08 10:02:56 CSTLABEL: backup_testSTOP TIME: 2020-09-08 10:02:56 CST


插入增量测试数据:

2020-09-08 10:05:20

psql\c testinsert into test values(3,'zxc');create table test2(id int primary key,age int);


PITR恢复:

postgresql PITR是基于pg_basebackup+wal log实现的。

停止pg服务并清空数据目录:

su - postgrespg_ctl -D /postgresql/data stoprm -rf /postgresql/data/*

将备份目录下的数据文件拷贝至目标数据目录:

cp -r /postgresql/backup/* /postgresql/data

数据目录下创建recover.conf并配置:

restore_command = 'cp /postgresql/archive/%f %p'recovery_target_time = '2020-09-08 10:03:10'

启动数据库服务:

pg_ctl -D /postgresql/data start


数据验证:

test=# select * from test; id |         name         ----+----------------------  1 | qwe                   2 | asd                 (2 rows)
test=# \d test2;Did not find any relation named "test2".

经验证数据已经恢复到2020-09-08 10:03:10的时间点


猜你喜欢

转载自blog.51cto.com/15080020/2655561