数据量在几十 GB 以内的库,我觉得没必要上 pgBackRest 这类物理备份方案,pg_dump 加一个靠谱的备份工具就够了。
备份脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| #!/usr/bin/env bash
set -euo pipefail
export RESTIC_REPOSITORY="s3:https://s3.example.com/backup-pg"
export RESTIC_PASSWORD_FILE=/etc/backup/restic.pass
source /etc/backup/s3.env
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
for db in $(psql -U postgres -Atc "SELECT datname FROM pg_database WHERE NOT datistemplate AND datname <> 'postgres'"); do
pg_dump -U postgres -Fc -Z0 -f "$WORK/$db.dump" "$db"
done
pg_dumpall -U postgres --globals-only > "$WORK/globals.sql"
restic backup --tag pg --host db1 "$WORK"
restic forget --tag pg --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune
|
几个细节:
-Fc 自定义格式,恢复时可以用 pg_restore -j 并行,还能只恢复某一张表。-Z0 不压缩。因为 restic 自己会压缩和去重,pg_dump 压缩后每天的文件都完全不同,去重就失效了。实测不压缩时每天新增的数据量只有压缩时的五分之一左右。--globals-only 导出角色和权限,很多人只备份了数据库,恢复时才发现用户都没了。
定时
用 systemd timer,参考之前那篇。
备份不验证等于没备份
每周一次自动恢复测试:
1
2
3
4
5
| restic restore latest --tag pg --target /tmp/restore-test
createdb -U postgres restore_check
pg_restore -U postgres -d restore_check -j 4 /tmp/restore-test/tmp/*/app.dump
psql -U postgres -d restore_check -Atc "SELECT count(*) FROM orders"
dropdb -U postgres restore_check
|
行数和线上差得不多,就算通过。曾经靠这个发现过一次 S3 凭证过期导致备份已经停了五天。
什么时候需要换方案
- 库超过一两百 GB,dump 和恢复时间太长
- 要求恢复到任意时间点(PITR)
这时候就该看 WAL 归档 + pgBackRest 了。