备份
pg_basebackup是基于流复制协议可以实现完全备份,并支持热备份
这个工具会把整个数据库实例的数据都拷贝出来,而不只是把实例中的部分(如某个数据库或某些表)单独备份出来。
使用replication协议连接到数据库实例上,所以主数据库中的pg_hba.conf必须允许replication连
接,也就是在pg_hba.conf中必须有类似下面的内容
#trust是信任 md5的意思是基于密码验证 replication是流复制协议
在备份服务器上备份远程数据库到本地
[postgres@localhost ~]$pg_basebackup -h 10.0.0.7 -U postgres -D /backup/ -Ft -Pv -p 5432 -R
-h 指定主机
-D 指定备份目标目录 注意此目录必须事先清空,
-Ft 指定备份文件格式 tar
-Pv 实现备份过程 可以不加
-R 写一个用于复制的配置文件,必须加
-p 如果不是默认端口号5432 需要加-p指定端口号
[postgres@localhost ~]$ll /backup/
总用量 68884
-rw------- 1 postgres postgres 271083 11月 20 09:45 backup_manifest
-rw------- 1 postgres postgres 53480960 11月 20 09:45 base.tar
-rw------- 1 postgres postgres 16778752 11月 20 09:45 pg_wal.tar
base.tar 是数据文件 pg_wal.tar 是归档日志文件
还原到备份数据库
先将数据库停服 数据库清空,archive目录清空
[postgres@localhost ~]$pg_ctl stop
waiting for server to shut down....2022-11-20 10:02:37.443 CST [36290] LOG: received fast shutdown request
2022-11-20 10:02:37.444 CST [36290] LOG: aborting any active transactions
2022-11-20 10:02:37.445 CST [36290] LOG: background worker "logical replication launcher" (PID 36297) exited with exit code 1
2022-11-20 10:02:37.445 CST [36292] LOG: shutting down
2022-11-20 10:02:37.451 CST [36290] LOG: database system is shut down
done
server stopped
[root@localhost ~]#rm -rf /pgsql/data/*
[root@localhost ~]#rm -rf /archive/*
[root@localhost ~]#tar xf /backup/pg_wal.tar -C /archive/
[root@localhost ~]#tar xf /backup/base.tar -C /pgsql/data/
修改postgressql.conf配置文件 修改下面两行 也可以在文尾加上
restore_command = 'cp /archive/%f %p' 存放刚刚备份过来的wal文件的目录,
recovery_target = 'immediate' 表示服务重启立即恢复
#recovery_target_name = '' # 恢复到指定的还原点
#recovery_target_time = '' # 恢复到指定时间
#recovery_target_xid = '' #事务编号还原
#recovery_target_lsn = '' # lsn号还原
#recovery_target_inclusive = on # 指定是否停止
启动服务 验证数据
[postgres@localhost ~]$pg_ctl start
waiting for server to start....2022-11-20 10:25:13.224 CST [36761] LOG: redirecting log output to logging collector process
2022-11-20 10:25:13.224 CST [36761] HINT: Future log output will appear in directory "log".
done
server started
[postgres@localhost ~]$psql
psql (14.6)
Type "help" for help.
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
db1 | postgres | UTF8 | zh_CN.UTF-8 | zh_CN.UTF-8 |
db2 | postgres | UTF8 | zh_CN.UTF-8 | zh_CN.UTF-8 |
hellodb | postgres | UTF8 | zh_CN.UTF-8 | zh_CN.UTF-8 |
postgres | postgres | UTF8 | zh_CN.UTF-8 | zh_CN.UTF-8 |
template0 | postgres | UTF8 | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
(6 rows)
postgres=#
恢复数据以后 会在dada目录下生成一个backup_label.old 文件 这个文件记录了 备份的说明信息 包括时间协议等等什么的