postgresql-备份恢复

原来是你~~~ / 2023-07-20 / 原文

1、逻辑备份恢复

pg_dump/pg_restore 命令备份恢复

对数据库或表备份恢复

## 备份指定的数据库 test
$ pg_dump -U postgres -W -h 192.168.3.122 -p 1921 test > /pgdata/dumpbak/test.sql

## 备份指定库中的某个表 t1
$ pg_dump -U postgres -W -h 192.168.3.122 -p 1921 test -t t1 > /pgdata/dumpbak/t1.sql

## 备份文件以加密形式存储,该备份出来的文件可以通过pg_restore恢复
$ pg_dump -U postgres -W test -Fc > /pgdata/dumpbak/test.dump

## 数据恢复
$ pg_restore -d test /pgdata/dumpbak/test.dump 
$ psql -U postgres -W test < /pgdata/dumpbak/test.sql 

备份所有的库

## 文件内容格式为 hostname:port:database:username:password
$ more .pgpass 
*:*:*:postgres:123456
$ chmod 600 .pgpass
$ pg_dumpall > all.sql
2、物理备份恢复

pg_basebackup 工具备份

选项参数含义:

-D ,保存备份的路径

-Ft , 备份内容保存格式为tar包形式,有 p|t 两种形式,p为普通文本形式

-z , 压缩备份文件

-Pv , 显示进度和输出信息

$ pg_basebackup -D /pgdata/pg_backup/ -Ft -z -Pv -U postgres -h 192.168.3.122 -p 1921 -R

模拟数据丢失,进行恢复

$ pg_ctl stop -mf
$ rm -rf $PGDATA/*
$ rm -rf /archive/*

## 将备份文件解压到指定路径中
$ tar -zxvf base.tar.gz -C /pgdata/
$ tar -zxvf pg_wal.tar.gz -C /archive/

## 编辑文件
$ vim postgresql.auto.conf
restore_command = 'cp /archive/%f %p'
recovery_target = 'immediate'

## 启动数据库
$ pg_ctl start
$ psql
## 查看当前数据库处于恢复中
$ pg_controldata
## 此时数据还只是只读状态,无法进行写操作,执行以下函数恢复读写
> postgres=# select pg_wal_replay_resume();