Borg 是 Python 写的去重备份工具,自带客户端加密、压缩、增量、仓库
deduplication。功能上和 Restic 相近,但生态早成熟两年,老牌系统管理
员居多。
Borgmatic 是 Borg 的 YAML wrapper,把 "备份 → 检查 → 清理 → 通知"
四件事写在一个配置文件里。
安装
sudo apt install -y borgbackup borgmatic
# 也可以 pip install --user borgmatic 拿更新版本
仓库初始化
我们做两份:本地 NAS + 异地(rsync.net / hetzner storage box / 自建机)。
两次 init:
# 本地 NAS(NFS / SMB 挂载到 /mnt/nas)
borg init -e repokey /mnt/nas/borg/host-foo
# 异地,通过 ssh+borg serve
borg init -e repokey \
ssh://[email protected]:23/./borg/host-foo
每次 init 会要求设置 passphrase;同样这两个密码 丢了就完了。
Borgmatic 配置
/etc/borgmatic/config.yaml:
location:
source_directories:
- /etc
- /srv
- /home/yourname/projects
exclude_patterns:
- '*/node_modules'
- '*/__pycache__'
- '*/.venv'
- '*/target'
- '*/.cache'
exclude_caches: true
exclude_if_present:
- .nobackup
repositories:
- path: /mnt/nas/borg/host-foo
label: nas
- path: ssh://[email protected]:23/./borg/host-foo
label: offsite
storage:
encryption_passcommand: 'cat /etc/borgmatic/passphrase'
compression: zstd,3
archive_name_format: '{hostname}-{now:%Y%m%d-%H%M%S}'
borg_keep_exclude_tags: true
retention:
keep_daily: 7
keep_weekly: 4
keep_monthly: 12
keep_yearly: 5
consistency:
checks:
- name: repository
frequency: 2 weeks
- name: archives
frequency: 1 month
hooks:
before_backup:
- echo "starting backup at $(date)"
after_backup:
- curl -fsSL --retry 3 'https://hc-ping.com/<uuid>' || true
on_error:
- curl -fsSL --retry 3 'https://hc-ping.com/<uuid>/fail' || true
/etc/borgmatic/passphrase:
my-very-long-random-passphrase
权限:sudo chmod 600 /etc/borgmatic/passphrase。
跑
sudo borgmatic --verbosity 1
# 等价于:create + prune + 周期性 check
只跑某一步:
sudo borgmatic create # 只备份
sudo borgmatic check # 只校验
sudo borgmatic prune # 只清理
sudo borgmatic list # 看快照列表
systemd timer
Borgmatic 包自带 unit:
sudo systemctl enable --now borgmatic.timer
systemctl list-timers borgmatic.timer
或者自己写 timer 覆盖时间。
还原
# 列快照
sudo borgmatic list --repository /mnt/nas/borg/host-foo
# 或
sudo borg list /mnt/nas/borg/host-foo
# 看快照内容
sudo borg list /mnt/nas/borg/host-foo::host-foo-20260520-024300 | head
# 还原一个文件到当前目录
cd /tmp
sudo borg extract /mnt/nas/borg/host-foo::host-foo-20260520-024300 etc/nginx/nginx.conf
# 挂载快照为只读文件系统(很方便)
sudo mkdir /mnt/snap
sudo borg mount /mnt/nas/borg/host-foo::host-foo-20260520-024300 /mnt/snap
ls /mnt/snap
sudo borg umount /mnt/snap
双仓库的取舍
- 本地仓库快但 fate-shared:火灾水患时一起没。
- 异地仓库慢但是真灾备;如果带宽紧张就只把
/etc/srv/critical推异地。
可以拆配置:
repositories:
- path: /mnt/nas/borg/host-foo
label: nas
# 仅在某些 source_directory 同步到异地,靠 borg patterns 文件
更简单的做法:写两份 borgmatic 配置 local.yaml / offsite.yaml,
各自有 source_directories,timer 在不同时间触发。
踩过的坑
- Borg 仓库 不能 让两个 client 同时写。两台机器要往同一个仓库
备份必须串行或用--lock-wait。 - 加密类型
repokey把 key 放仓库里(密码加密),方便但密码弱时不安全;
keyfile把 key 放客户端~/.config/borg/keys/,要单独备份。 - 大文件改动(虚拟机磁盘)每次 dedup 都要扫整个文件,慢。建议这种文件
排除,单独做内置工具的快照备份。 - 远端 ssh 用专门 key 加
command="borg serve --restrict-to-repository ..."
限制;别用你的常规 key 跑 borg。
登录后参与评论。