This tutorial was written with AI assistance from the project's official documentation. Verification status is stated at the end of the article.
Architecture and why these pieces fit together
This stack separates concerns into three short-lived, deterministic stages:
-
db— a standardpostgres:16-alpineinstance with a named volumepg_data. It exposes apg_isreadyhealthcheck so downstream jobs wait for a real database, not just a listening socket. -
pg-dumper— a one-shot container that seeds a deterministic marker row, runspg_dumpinto a shared staging volume, and exits 0 only if the dump file is non-empty. It uses the samepostgres:16-alpineimage, so no extra tooling is required. -
backup-verify— a one-shotrestic/restic:0.17.3container that initializes the repository if needed, backs up/staging, runsrestic check --read-data, restores the latest snapshot into/tmp/restore-test, and asserts the marker text is present. It exits 0 only when the full round-trip succeeds.
All persistent state lives in named volumes (pg_data, backup_staging, restic_repo). No host bind mounts, no Docker socket. The entire stack is defined in a single compose.yml plus a .env file, so it runs identically in a sandbox and on a VPS.
The staging volume is mounted read-only into backup-verify, which enforces a clean boundary: the backup job cannot mutate the dump it is verifying. The Restic repository is local by default (/repo), but the same container works unchanged against S3-compatible object storage by swapping RESTIC_REPOSITORY.
Prerequisites, ports, and VPS sizing
- Docker Engine 24+ with the Compose v2 plugin.
- A 1 GB VPS is sufficient for the default local-repository mode. Restic's
check --read-datareads the entire repository, so keep the staging volume small (a few hundred MB) or move the repository to object storage. - No inbound ports are required. The stack does not expose HTTP; it is a batch pipeline.
- Set a strong
RESTIC_PASSWORDin.env. Losing it means losing the ability to decrypt backups. - Optional: an S3-compatible bucket (Cloudflare R2, Backblaze B2, AWS S3) if you want off-host storage. The default local repository is fine for verification and for VPS-local snapshots.
Single-file Docker Compose setup
Create the project directory and write both files:
mkdir -p restic-backup && cd restic-backup
cat <<'EOF' > compose.yml
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: ${POSTGRES_USER:-app}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB:-appdb}
volumes:
- pg_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 20
restart: unless-stopped
pg-dumper:
image: postgres:16-alpine
depends_on:
db:
condition: service_healthy
environment:
PGHOST: db
PGUSER: ${POSTGRES_USER:-app}
PGPASSWORD: ${POSTGRES_PASSWORD}
PGDATABASE: ${POSTGRES_DB:-appdb}
volumes:
- backup_staging:/staging
configs:
- source: dump_script
target: /usr/local/bin/dump.sh
mode: 0755
entrypoint: ["/bin/sh", "/usr/local/bin/dump.sh"]
restart: "no"
backup-verify:
image: restic/restic:0.17.3
depends_on:
pg-dumper:
condition: service_completed_successfully
environment:
RESTIC_REPOSITORY: ${RESTIC_REPOSITORY:-/repo}
RESTIC_PASSWORD: ${RESTIC_PASSWORD}
volumes:
- backup_staging:/staging:ro
- restic_repo:/repo
entrypoint: ["/bin/sh", "-ec"]
command:
- |
restic snapshots >/dev/null 2>&1 || restic init
restic backup /staging
restic check --read-data
rm -rf /tmp/restore-test
restic restore latest --target /tmp/restore-test
test -s /tmp/restore-test/staging/appdb.sql
grep -q 'restic-marker' /tmp/restore-test/staging/appdb.sql
echo "backup-verify: snapshot, check, and restore OK"
restart: "no"
configs:
dump_script:
content: |
#!/bin/sh
set -eu
psql -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE IF NOT EXISTS restic_marker (
id integer PRIMARY KEY,
note text NOT NULL
);
INSERT INTO restic_marker (id, note)
VALUES (1, 'restic-marker')
ON CONFLICT (id) DO UPDATE SET note = EXCLUDED.note;
SQL
pg_dump -Fp -f /staging/appdb.sql
test -s /staging/appdb.sql
echo "pg-dumper: wrote $(wc -c < /staging/appdb.sql) bytes to /staging/appdb.sql"
volumes:
pg_data:
backup_staging:
restic_repo:
EOF
cat <<'EOF' > .env
POSTGRES_USER=app
POSTGRES_PASSWORD=replace-with-a-strong-db-password
POSTGRES_DB=appdb
RESTIC_PASSWORD=replace-with-a-strong-restic-password
RESTIC_REPOSITORY=/repo
EOF
Notes on the design:
-
pg-dumperseeds a deterministic row (restic_marker) so the restore check has a stable string to grep for. TheON CONFLICTclause makes re-runs idempotent. -
pg_dump -Fcproduces a custom-format archive. It is compact and restorable withpg_restore, which is what you want for real databases. -
backup-verifyrunsrestic check --read-data, which reads every pack file in the repository. That is the strongest integrity check Restic offers, and it is why the staging volume should stay modest on a 1 GB VPS. - The
restic_repovolume is mounted at/repoand is the defaultRESTIC_REPOSITORY. When you switch to S3, the volume is simply unused.
Local verification before going live
Run the pipeline once and inspect exit codes:
docker compose up --abort-on-container-exit --exit-code-from backup-verify
You should see pg-dumper log the byte count, then backup-verify log the snapshot, check, and restore confirmation. Both one-shot services must exit 0.
Inspect the repository and the restored file:
docker compose run --rm backup-verify sh -ec 'restic snapshots'
docker compose run --rm backup-verify sh -ec 'restic ls latest'
If you want to confirm the marker survived the round-trip without re-running the full pipeline:
docker compose run --rm backup-verify sh -ec 'rm -rf /tmp/restore-test && restic restore latest --target /tmp/restore-test && grep -c restic-marker /tmp/restore-test/staging/appdb.sql'
Tear down without losing data:
docker compose down
docker compose down -v deletes pg_data, backup_staging, and restic_repo. Use it only when you intend to start from scratch.
Production cutover (HTTPS / remote backups)
This stack has no HTTP surface, so there is no HTTPS cutover. The production cutover is about moving the Restic repository off the VPS and scheduling the pipeline.
Point Restic at S3-compatible storage
Set the repository URL and credentials in .env. For Cloudflare R2:
RESTIC_REPOSITORY=s3:https://<account-id>.r2.cloudflarestorage.com/<bucket>
AWS_ACCESS_KEY_ID=<r2-access-key>
AWS_SECRET_ACCESS_KEY=<r2-secret-key>
For Backblaze B2:
RESTIC_REPOSITORY=s3:https://s3.<region>.backblazeb2.com/<bucket>
AWS_ACCESS_KEY_ID=<b2-key-id>
AWS_SECRET_ACCESS_KEY=<b2-application-key>
For AWS S3:
RESTIC_REPOSITORY=s3:s3.amazonaws.com/<bucket>
AWS_ACCESS_KEY_ID=<aws-access-key>
AWS_SECRET_ACCESS_KEY=<aws-secret-key>
Add the AWS variables to the backup-verify service environment in compose.yml (or pass them via docker compose run -e). The restic_repo volume becomes unused in this mode; you can drop it from the service if you want a tighter definition.
Schedule nightly runs
A systemd timer is the most reliable option on a VPS. Create /etc/systemd/system/restic-backup.service:
[Unit]
Description=Restic backup pipeline
After=docker.service
Requires=docker.service
[Service]
Type=oneshot
WorkingDirectory=/opt/restic-backup
ExecStart=/usr/bin/docker compose run --rm pg-dumper
ExecStart=/usr/bin/docker compose run --rm backup-verify
And /etc/systemd/system/restic-backup.timer:
[Unit]
Description=Nightly Restic backup
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
[Install]
WantedBy=timers.target
Enable with systemctl enable --now restic-backup.timer. A cron equivalent is:
30 2 * * * cd /opt/restic-backup && docker compose run --rm pg-dumper && docker compose run --rm backup-verify
Apply retention
Run retention after a successful backup. Add it to the timer or run it manually:
docker compose run --rm backup-verify sh -ec 'restic forget --keep-daily 7 --keep-weekly 4 --prune'
--prune rewrites pack files and can be slow on object storage. Run it weekly rather than nightly if bandwidth is a concern.
Day-2 operations, backups, and trade-offs
Upgrades. Bump the Restic image tag in compose.yml and re-run the pipeline. Restic repositories are forward-compatible within a major version; check the release notes before crossing a major boundary. For PostgreSQL, the pg_dump format is stable across minor versions, but restoring into a newer major requires pg_restore from that major.
Failure modes.
-
pg-dumperexits non-zero ifpg_dumpfails or the file is empty. Thedepends_on: service_completed_successfullyonbackup-verifyprevents a snapshot of a broken dump. -
restic check --read-datafails on corrupted pack files. That is the signal to restore from an older snapshot and investigate storage. - The restore grep fails if the marker row is missing. That usually means the dump was taken before the seed ran, or the wrong database was dumped.
Backups of the backup. The restic_repo volume is itself a single point of failure in local mode. For anything beyond a sandbox, use S3-compatible storage so the repository lives off the VPS. If you must stay local, snapshot the volume with your provider's block-storage snapshots.
Trade-offs.
-
check --read-datais thorough but reads the whole repository. On a 1 GB VPS with a local repository, keep the staging volume under a few hundred MB or run the full check weekly and a lighterrestic checknightly. - The pipeline is sequential: dump, then backup, then verify. That is intentional — it keeps the failure semantics simple. If you need parallelism, split the verify step into its own timer.
- The marker table is a verification aid, not a schema migration. Do not rely on it for application data.
Restore drill. Once a quarter, restore a snapshot into a scratch database and run your application's smoke tests against it. The automated grep proves the file is intact; only a real restore proves the data is usable.
Measured in our sandbox run: total memory 24.9 MB (sum of per-container peaks over a 30s idle window after startup) across 3 containers; largest container 24.9 MB. The run took 49.9s with the image already cached; a fresh server also has to download it. Required secret(s) POSTGRES_PASSWORD, RESTIC_PASSWORD were generated for the test run, as the tutorial instructs. Verified one-shot jobs: backup-verify (exit 0), pg-dumper (exit 0).
Verification: we ran this docker-compose stack in a disposable Docker environment and recorded the measurements above. They describe that run, not a guarantee for your host.
Originally published with full interactive benchmark metrics and server sizing notes at https://vpsfolio.pages.dev/stacks/docker-compose-automated-restic-backup-restore/.
Top comments (0)