- Python 86.8%
- HTML 12.7%
- Shell 0.4%
- Dockerfile 0.1%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| agent | ||
| compose/backup-ui | ||
| config | ||
| systemd | ||
| ui | ||
| .gitignore | ||
| INSTALL.md | ||
| README.md | ||
BackToTheDoc
Where we're going, we don't need bash scripts.
Full Docker backup agent (spiritual successor of single_docker_backup.sh) with a Unix-socket
control plane, SQLite as the control plane (the store is the ground truth), and a separate
web-UI container that talks to the agent over that socket. Restore-first: every snapshot ships
with its own generated restore.sh next to the data, plus a global restore_all.sh — and you
can trigger a restore from the UI with one click.
[docker.sock] [backtothedoc-agent] <--> /run/backtothedoc/bttd.sock (HTTP over unix socket)
^ ^ ^
Docker daemon SQLite (policy) [backtothedoc-ui container] --> browser
Features
- Full Docker backup per container: inspect.json, original image (docker save), optional commit-image, named volumes as tar.gz, bind mounts via rsync, network JSON, generated restore scripts.
- Strategies per container:
full(images+volumes+binds),data(volumes+binds),config(binds only). - Per-container regime: cron schedule (with a friendly cron selector in the UI: daily /
weekly / monthly / every-N-hours / raw), strategy, consistency hook (
none/stop/exec— e.g. HA SQLite viasqlite3 ... .backup), retention, excludes. - Restore from the UI: "Restore last snapshot" on the container page runs the same
generated script a bare-metal recovery would use (image, network incl. subnet, volumes,
binds, env, restart policy, hostname, and the container's static IPv4 for
ipvlan/macvlan setups). Runs appear in the history with
RESTOREas trigger. - Snapshot versioning: every backup lands in its own timestamped snapshot dir with a
manifest, its own volumes/binds and its own
restore.sh. The container page lists the snapshots actually on disk (so the store survives a database wipe) with per-snapshot Restore and Delete, and retention prunes to the newest N (default 14). Old latest-only stores keep working as a single "legacy" row. - Purge workflow: "Delete backups & history" removes a container's snapshot files from the backup store (shared images/volumes used by other containers are kept) and clears its run history. Only after that, "Remove" deletes the regime — the UI hides the Remove button and the API returns 409 until the purge is done. No orphaned files.
- Honest dashboard: per-run sizes in the history (what this backup wrote), the total store size on top, a "What" column (scheduled backup / manual backup / RESTORE), and auto-refresh while a run is active.
- Containers easily added/removed: live Docker container list in the UI, one-click toggle.
- Stacks backup as full regimes: multiple host folders (compose/.env/units), each with its own schedule, retention and excludes. The Backups page has three sections (Containers / Orphaned backups / Stacks); per-snapshot Restore/Delete, and restore asks for the destination path (bare-metal: the configured location may not exist yet).
- Systemd-triggered scheduling: a single timer fires
POST /tickevery 15 minutes; the agent decides what is due based on the DB. - User logins: users + sessions in SQLite, scrypt password hashing. No roles in v1.
The first user is created via the first-run screen in the web-UI; later users via
backtothedoc-agent adduser. - MCP connector: the UI container also serves a streamable-HTTP MCP endpoint
(
/mcp, Bearer API key) with tools to list/modify targets, trigger runs and read logs, so AI clients can manage backups. See INSTALL.md step 4. - Headless-friendly: every UI action is a socket API call, so
curl --unix-socket, HA automations or MCP tooling can do the same.
Layout
agent/ Python package (FastAPI agent) + tests + pyproject
ui/ Thin web-UI container (FastAPI + Jinja, talks to /run/backtothedoc/bttd.sock)
systemd/ socket / service / tick timer units + tick helper script
compose/ docker-compose.yml + .env.example for the UI stack
config/ example /etc/backtothedoc.toml
Install (agent, on the Docker host)
# as root, on the host that runs your containers (e.g. Corellia)
cd <repo>
git pull
pipx install --force ./agent # installs backtothedoc-agent
mkdir -p /etc /var/lib/backtothedoc
cp config/backtothedoc.toml /etc/ # adjust backup_root etc.
backtothedoc-agent adduser bttd-tick # service account for the systemd tick
# (your own login is created via the first-run screen in the web-UI)
cp systemd/backtothedoc.service /etc/systemd/system/
cp systemd/backtothedoc-tick.service systemd/backtothedoc-tick.timer /etc/systemd/system/
cp systemd/bttd-tick /usr/local/sbin/ && chmod +x /usr/local/sbin/bttd-tick
systemctl daemon-reload
systemctl enable --now backtothedoc.service # agent owns /run/backtothedoc/bttd.sock
systemctl enable --now backtothedoc-tick.timer # (socket activation is optional, not needed)
Verify headless:
curl --unix-socket /run/backtothedoc/bttd.sock http://localhost/healthz
Full step-by-step install (including first run) is in INSTALL.md.
Install (web-UI, as a container)
cd <repo>
docker build -t backtothedoc-ui:latest ui/
cp compose/backup-ui/.env.example compose/backup-ui/.env # set IP (192.168.5.144 on Corellia)
docker compose -f compose/backup-ui/docker-compose.yml up -d
The UI mounts only the /run/backtothedoc directory (read-only, so agent restarts never
invalidate the mount). It has no Docker socket, no backup data and no database access: a
compromised UI cannot touch your backups.
Updating
cd <repo> && git pull
pipx install --force ./agent && systemctl restart backtothedoc.service # agent changes
docker build -t backtothedoc-ui:latest ui/ && \
(cd compose/backup-ui && docker compose up -d --force-recreate) # UI changes
Disaster recovery (new server)
The backup store describes itself completely: regimes (regimes.json), snapshots
(manifests + restore scripts) and run history (containers/<name>/history.json).
SQLite is only the control plane (users, sessions, settings) — losing it is a
non-event. On a fresh host:
# 1. install the agent (no toml needed — the first-run screen asks where the
# store lives, e.g. the rescued backup drive mounted at /mnt/old)
# 2. create the admin account and fill in the store path in the web-UI
# 3. rebuild regimes + run history:
backtothedoc-agent rebuild
# 4. open "Backups": every backup shows under
# "Orphaned backups" with a Restore button per container
- With
regimes.json(v2) in the store: every container schedule, strategy, consistency hook, exclude, retention and note — and since v0.29 every stack regime too (path, schedule, retention, excludes) — comes back at full fidelity. Stack restores ask for the destination path, because on a fresh host the configured stack location may not exist yet. - Without it (an old store):
rebuildscanscontainers/*/inspect.json(or the newestsnapshots/*/manifest.jsonin v0.26+ stores) and reconstructs what it can, applying safe defaults (daily 03:30, consistency none) and telling you what to review in the UI. - Restores themselves are done from the per-snapshot
restore.shscripts (regenerated frominspect.jsonat restore time, so old snapshots heal from script bugs without a re-backup) orrestore_all.sh, or the UI as usual —--fromlets you rebuild from a store at a different path than the configuredbackup_root.
API (on the socket)
| Method | Path | Function |
|---|---|---|
| GET | /healthz | liveness (no auth) |
| POST | /auth/login, /auth/logout | session cookie |
| GET | /docker/containers | live container list + store-only ("orphaned") containers |
| GET/POST | /targets | list / add targets |
| PATCH | /targets/{name} | edit regime |
| DELETE | /targets/{name} | remove regime (409 until history purged) |
| DELETE | /targets/{name}/data | purge: snapshot files + run history |
| DELETE | /runs | clear (all or ?container=) run history |
| GET | /status, /runs, /runs/{id}/log | status & history |
| POST | /run, /run/{name} | force full run / single container |
| POST | /restore/{name}?snapshot= | restore container (latest snapshot, or a specific one; no regime needed) |
| POST | /settings/backup_root | change the store path at runtime (settings > toml) |
| GET | /auth/needs-setup | first-run status (user + store path) |
| GET/POST | /settings | read / update host settings (store path) |
| GET/POST | /stacks | list / create stack regimes (own path, schedule, retention) |
| PATCH/DELETE | /stacks/{name} | update / remove a stack regime (409 until purged) |
| DELETE | /stacks/{name}/data | purge a stack: snapshots + history |
| GET | /stacks/{name}/snapshots | stack snapshots on disk |
| POST | /stacks/{name}/backup | backup one stack now |
| POST | /stacks/{name}/restore?snapshot=&to= | restore stack to a destination path |
| DELETE | /stacks/{name}/snapshots/{sid} | delete one stack snapshot |
| GET | /targets/{name}/snapshots | snapshots on disk (newest first, legacy row last) |
| DELETE | /targets/{name}/snapshots/{sid} | delete one snapshot (files + history rows) |
| POST | /tick | scheduler step (systemd timer) |
Consistency hooks
none— cold copy (default)stop— stop/start the container around the copy (databases)exec— run a command inside the container first, e.g. for Home Assistant:sqlite3 /config/home-assistant_v2.db ".backup /config/ha_backup.db"
Test
cd agent && python -m unittest discover -s tests -v
Store layout
<store>/ # e.g. /srv/media/backups
├── regimes.json # v2: all regimes incl. stacks (auto-export on every change)
├── restore_all.sh # newest snapshot per container
├── images/
│ ├── <safe_image_ref>.orig.tar.gz # original image (strategy full); safe = / and : → _
│ └── <container>.commit.tar.gz # optional commit image (save_commit_images)
├── networks/<net>.json # incl. subnet, for network re-creation
├── containers/<name>/
│ ├── history.json # run/restore history (mirror; ground truth for rebuild)
│ └── snapshots/<YYYYMMDD-HHMMSS>/
│ ├── inspect.json # docker inspect at backup time
│ ├── manifest.json # written LAST: presence = complete snapshot
│ ├── volumes/<volume>.tar.gz # real gzip (v0.30.1); restore unpacks with tar -xf
│ ├── binds/<safe_src>… # rsync copy of every bind (dirs and files)
│ ├── bind-mounts.txt
│ └── restore.sh # plain bash; regenerated at restore time
└── stacks/<name>/
├── history.json
└── snapshots/<ts>/{stacks.zip, manifest.json, restore.sh}
Legacy stores (pre-v0.24 latest-only layout, restore_<container>.sh scripts) keep working
and show up in the UI as a single "legacy" row.
Design decisions
- Disk is the ground truth; SQLite is only the control plane. Every snapshot is
self-describing (manifest, inspect, restore script), run history lives next to the data
(
history.json), and regimes auto-export toregimes.json.backtothedoc-agent rebuildreconstructs the database from the store, and Remove stays blocked until the snapshots are actually purged from disk (v0.25). Losing the database is a non-event; losing the store is the disaster — so the design treats the store accordingly. - Restore-first, and the restore path is boring on purpose. Each snapshot ships a plain
bash
restore.shnext to the data, and the engine regenerates it from the snapshot'sinspect.jsonat restore time (v0.30): old snapshots heal from script bugs without a re-backup, and you can always run the script by hand on a rescue shell.set -euo pipefail: a restore either completes or names the exact step that died. - Image chain on restore: commit-tar > orig-tar from the store > pullable ref. The
commit image wins (state at backup time); otherwise the orig-tar is loaded from the store;
only then does the restore rely on the image still being on the host —
docker runpulls a registry ref automatically. Untagged images (locally built, sha256 refs) come back asbackup/<container>:originstead of dangling (v0.30.2). Consequence: strategydatakeeps backups lean, but a bare-metal restore of those containers needs their image from a registry — locally built images belong onfull. - Shell out, don't SDK. The engine uses
docker/rsync/tarsubprocesses instead of docker-py: zero heavy dependencies, every artifact is inspectable with standard tools, and the restore scripts double as documentation. - Let the tool do the compression.
tar -czfwrites real gzip (v0.30.1); the restore side unpacks withtar -xf, which auto-detects — so pre-v0.30.1 "tar.gz" volume archives that were actually plain tar still restore. Lesson: never pipe a subprocess stdout into a Python gzip layer; the child writes to the raw fd. - The store never backs itself up. The store is auto-excluded from every bind rsync
(v0.30.3) — a bind that contains the store (like
/srv/mediawhen the store lives at/srv/media/backups) cannot drag the whole archive into a snapshot. Corollary: a snapshot dir withoutmanifest.jsonis by definition a partial or failed run, not a backup. - Excludes: paths skip binds, patterns filter. An exclude entry equal to (or an ancestor
of) a bind path skips that whole bind (
/srv/mediadrops the share but keeps smb.conf); every other entry is an rsync pattern within a bind (*.log). Single-file binds are first-class targets (v0.30.3/0.30.4). - One run at a time. The engine holds a lock: a second run (tick or manual) is skipped,
never queued. Predictable IO on the backup target, no pile-up, and a runaway is visible as
skippedinstead of multiplying. - Least-privilege split. The agent runs on the host (it needs the Docker CLI, volume paths and rsync); the UI runs in a container with only the read-only socket directory mounted — no docker.sock, no store, no database. A compromised UI cannot touch the backups.
- Scheduling by timer, not by daemon. systemd fires
POST /tickevery 15 minutes and the agent diffs cron expressions against the clock: no scheduler threads, drift-tolerant, and every regime slot is just a cron expression in the database. - Old stores keep working. Legacy latest-only layouts, plain-tar volume archives, stale restore scripts: format changes stay backward compatible, because a restore must never depend on having today's agent version around.
Changelog
- v0.30.5 — Docs only, no redeploy needed. README: new Store layout and
Design decisions sections (the "why" behind store-first, the image chain,
shell-out-over-SDK, the store-never-backs-itself-up rule, excludes semantics,
the single engine lock, least-privilege split, backward compatibility); restore
wording fixed for the snapshot era (per-snapshot
restore.sh, regenerated at restore time); Status bumped to the v0.30.4 reality (73 tests). INSTALL.md: rewritten to match the actual Corellia setup — git clone + pipx instead of copy-to-/opt + pip, anddocker build -t backtothedoc-ui:latest ui/from the repo root beforedocker compose up(the compose file has no build section, which cost an extra deploy round on v0.30.4 day). - v0.30.4 — The target page finally has an Excludes field. The engine, the API and the database all supported per-target excludes since v0.30.3 (and the stack page always had its own excludes field), but the container regime form never exposed it — so there was literally nowhere to type them (found when Steve asked where to enter samba's excludes). The field takes comma-separated entries: a path that matches a bind mount skips that whole bind, anything else is an rsync pattern within a bind. The backup store is excluded automatically either way.
- v0.30.3 — Bind backups can no longer swallow the store (found via
Steve's samba: a config-only backup was at 11GB and climbing, invisible
in the UI because manifests are only written at the end of a run). Three
fixes in the bind-rsync logic: (1) the backup store is now always
excluded from every bind transfer — the store lives under
/srv/media/backupsand the samba container binds/srv/media, so rsync was copying the entire store, history and image tars included, into its own snapshot; (2) an exclude entry that equals a bind path (or an ancestor of it) now skips that whole bind, soexclude=/srv/mediakeeps smb.conf and the private dir while dropping the media share; (3) single-file binds (like samba'ssmb.conf) are actually synced now — the old code only rsynced directory binds, so file binds silently vanished from every snapshot even though the restore script could always restore them. - v0.30.2 — Restores no longer leave the restored image dangling. A
locally built image has no repo tag (its Config.Image is a sha256:... ref),
so its docker-save tar has no RepoTags and
docker loadbrings it back as<none>:<none>— exactly whatdocker image prunecollects, meaning one prune could delete the image a freshly restored container runs on (found via Steve's fritz-mcp: its restore came back dangling in Portainer). The restore script now inspects the load output: on "Loaded image ID:" (untagged) it re-tags the image asbackup/<container>:origand recreates the container on that tag. Tagged images (e.g. alpine:3.20) are untouched. - v0.30.1 — Volume archives are real gzip now. The backup piped tar into a gzip.GzipFile used as subprocess stdout — subprocess writes to the raw fd and bypasses the gzip layer, so every volume ".tar.gz" on disk was actually an uncompressed tar (found via Steve's manual restore test: "tar -xzf: not in gzip format"). tar's own -z does the compression now, and the restore script unpacks with tar -xf, which auto-detects compression — so old (plain tar) and new (gzip) volume archives both restore, and existing snapshots heal without a re-backup.
- v0.30 — Restore is truly store-first now (found by Steve's orphaned testje). Root cause of the failed restore: snapshot restore scripts resolved the store root one level too deep (base_up=3 instead of 4), so the image tars and network jsons in the store were never found — restores silently depended on the image still being on the host (or pullable). Fixes: (1) correct BASE, and the script loads the original image tar from the store when the image is missing on the host (commit image stays preferred); (2) named volumes are re-attached to the recreated container (data was restored but never mounted); (3) the original entrypoint + command are restored, so a restored container does the same thing as before instead of falling back to the image default; (4) the engine regenerates restore.sh from the snapshot's inspect.json at restore time, so existing snapshots with broken scripts heal without a new backup. Volume unpack falls back to the restored image when alpine is not on the host. New regression suite (test_restore_script.py) runs the generated script against a mock docker: 59 tests green.
- v0.29.2 — Stacks get the same schedule picker as containers: no cron writing needed anymore. The picker (Every day / week / month, Every N hours, or custom) now lives in a shared include (cron_picker.html) used by the container page, the stack page and the add-stack form; it preselects the mode matching the existing schedule. UI-only change.
- v0.29.1 — UI polish: the Backups page sections are tabs now (Containers / Orphaned backups / Stacks) with a count badge per tab, instead of one long page. The chosen tab is remembered per browser (localStorage). No API or store changes.
- v0.29 — Stacks are full regimes: multiple stack folders, each with its own
cron schedule (own slot via /tick), retention and excludes — nothing piggybacks
on full runs anymore. The Containers page is renamed Backups with three
sections: Containers, Orphaned backups and Stacks. Per-stack pages with
regime editing, snapshots on disk, per-snapshot Restore/Delete, and
purge-first Remove (same rule as containers). Restore always asks for the
destination path (
to), because on a rebuilt server the configured location may not exist yet; the generatedrestore.shalso accepts a path argument. Store layout:stacks/<name>/snapshots/<ts>/{stacks.zip, manifest.json, restore.sh}+stacks/<name>/history.json; runs recorded asstack:<name>. regimes.json is v2 and carries stack regimes along, so a bare-metal rebuild (import regimes + import history) restores stack regimes too. API: GET/POST /stacks, PATCH/DELETE /stacks/{name}, DELETE /stacks/{name}/data, GET /stacks/{name}/snapshots, POST /stacks/{name}/backup, POST /stacks/{name}/restore?snapshot=&to=. - v0.28 — Rebuild resyncs the history cache exactly: it now clears the runs table and re-imports it from the store mirrors, so after moving the store (or any DB/store drift) the dashboard shows exactly what the store says — ghost runs disappear, real history returns.
- v0.27 — Settings page & menu: change the store path, stacks folder,
stacks retention and excludes from the UI after first-run (persisted in
SQLite settings, applied live). Stacks backup: the host folder with your
compose files / .env / units is zipped into
stacks/snapshots/<ts>/with every full run (own manifest, retention, restore.sh and history rows as container_stacks), with per-snapshot Restore/Delete on the settings page and sensible excludes (.git, pycache, build, *.egg-info) by default. API: GET/POST /settings, GET /stacks/snapshots, POST /stacks/backup, POST /stacks/restore, DELETE /stacks/snapshots/{sid}. - v0.26 — Store-first architecture: the store describes itself completely,
SQLite is only the control plane. Run history now lives next to the data
(
containers/<name>/history.json, mirrored after every run/restore —rebuildbrings it back after a DB wipe, purge removes it with the files). Backup store path is a setting in SQLite (set via the first-run screen);/etc/backtothedoc.tomlis now optional legacy fallback — precedence is settings > toml. Containers page gains "In the backup store, not on this host": store containers Docker doesn't know, each with a Restore button — the bare-metal flow (restore works without a regime now). The rebuild scan also understands snapshot-only stores (manifest.json fallback). - v0.25 — Remove gating is disk-based now: the containers list blocks Remove
while backups exist on disk, not just while run history exists. After a DB
wipe + rebuild the history is empty but the store is not — the store is the
ground truth, so Remove stays blocked (hint: "x runs, y snapshots on disk —
purge first") and
DELETE /targets/{name}returns 409 until purged. - v0.24 — Snapshot versioning: every run creates a timestamped snapshot
containers/<name>/snapshots/<YYYYMMDD-HHMMSS>/(manifest, inspect, volumes, binds,restore.sh). The target page lists snapshots that are actually on disk (ground truth — survives a DB wipe), each row with Restore and Delete (files + history). Retention keeps the newest N snapshots (default 14, per target). Old latest-only stores keep working and show up as a single "legacy" row.restore_all.shprefers the newest snapshot per container. - v0.22 — Rebuild button in the UI: on a fresh install (empty DB, recoverable store) the dashboard offers "Rebuild regimes from backup store" (POST /rebuild); setup screen enforces the min-8-char password visibly.
- v0.21 — Disaster recovery:
regimes.jsonauto-export on every regime change,backtothedoc-agent rebuildrebuilds the DB from the store (full fidelity) or by scanning old stores (defaults + honest warnings); stalerunningruns are marked failed at agent boot. - v0.20 — Cron selector: fixed the swapped minute/hour regression; hours schedules
(
0 */n * * *) now recognized in the friendly selector. - v0.19 — Never cache HTML; failed saves surface the agent's error on the page.
- v0.18 — Remove button hidden (muted "purge first" hint) while history exists; README overhaul.
- v0.17 — Purge workflow:
DELETE /targets/{name}/data(files + history, shared resources kept), Remove blocked (409) until purged,db.count_runs. - v0.16 — Per-run sizes in the history; dashboard top shows the store total.
- v0.15 — "What" column on the dashboard (scheduled / manual / RESTORE).
- v0.14 —
DELETE /runs+ clear-history per container (later absorbed by purge). - v0.13 — Restore scripts re-apply the container's static IPv4 (
--ipfrom inspect.json). - v0.12 — Restore from the UI (
POST /restore/{name}, orange button, restore runs in history). - v0.11 —
restore_all.shregenerated on every run, not only full runs. - v0.10 — Cron selector time-format fix (no more "undefined * * *").
- v0.9 — Auto-refresh dashboard/target page while a run is active.
- v0.8 — Socket moved to its own dir
/run/backtothedoc/(dir-mount survives agent restarts); socket activation dropped from the default install. - v0.7 —
DELETE /targets/{name}really removes the regime; cron selector in the UI. - v0.1–0.6 — Engine, socket API, auth, scheduling, UI, MCP endpoint, first-run screen.
Status
v0.30.4 — running in production on Corellia (agent via pipx + systemd, UI as a container).
Engine, restore (UI + scripts), purge workflow, socket API, auth, scheduling, stacks,
snapshot versioning, the store-first architecture (history in the store, settings in
SQLite, orphaned-container recovery) and the full v0.30.x restore chain (store-first image
loading, real gzip volumes, no dangling restored images, store-safe bind rsync) are
functional. 73 unit + regression tests green (cd agent && python3 -m unittest discover -s tests).
Off-site push (store -> remote NAS) is a v2 idea. The original design rationale lives in
CorBackup_Agent_Ontwerp_2026-11-27.md (Nextcloud, Computer setup/Homelab); the current
design decisions are documented in this README.