Back to tutorials
Tutorial

Docker Compose Backups With Restic on a VPS

Learn to backup Docker volumes with restic on a VPS: encrypted snapshots, automation, retention, and a tested restore you can verify.

By Anurag Singh
Updated on Dec 04, 2026
Category: Tutorial
Share article
Docker Compose Backups With Restic on a VPS

Docker Compose makes self-hosting painless. Backups are where people get sloppy.

Your database and uploads live in volumes, not in the container image. If a disk dies or you redeploy in a hurry, that data can disappear fast.

This tutorial shows you how to backup Docker volumes with restic on a VPS. You’ll get encryption, sensible retention, and a restore test you can rerun anytime.

The workflow stays deliberately simple. Pause or dump what needs consistency. Snapshot into an encrypted restic repo. Prune old snapshots. Then restore into a clean directory and confirm the data is usable.

You’ll end up with a script and a systemd timer. It works on Ubuntu, Debian, AlmaLinux, or Rocky Linux.

What you’ll build (and what you need first)

  • Backups: An encrypted restic repository stored offsite (SFTP recommended) or on a mounted backup disk.
  • Scope: Docker Compose volumes + a copy of your compose project files (.env, compose.yml) so restores are repeatable.
  • Automation: A systemd service + timer (no cron drift, logs in journald).
  • Verification: A restore into /var/restore-test with a quick integrity check.

Prereqs

  • A Linux server you control (VPS or dedicated). If you’re running multiple apps, consider a HostMyCode VPS so you can attach extra storage and lock down SSH properly.
  • Docker + Docker Compose plugin (docker compose version works).
  • Root or sudo access.
  • An offsite destination: an SFTP user on another server, or a storage box you can mount/SSH into.

Pick a backup target that won’t disappear with your VPS

If your backups sit on the same disk as your containers, you don’t have a backup. You have a second copy that fails at the same time.

Good options for self-hosters:

  • SFTP to another VPS: straightforward and easy to reason about. A small “backup VPS” with cheap storage goes a long way.
  • Dedicated backup server / storage VM: a better fit once you’re storing lots of media or multi-GB databases.
  • Attached block storage + replication offsite: workable, but only if you actually replicate offsite.

If you host apps for clients, split roles when you can. Keep one node for app workloads and another for backups.

That’s a clean fit for managed VPS hosting. You can keep the primary node lean while still getting help with storage and security hardening.

Step 1: Identify exactly what to back up in your Compose project

Start by listing what’s running and what volumes exist. This step makes it harder to miss something later.

docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'

docker volume ls

Next, confirm which volumes each container actually mounts. Replace your_stack with a container name from docker ps:

docker inspect your_stack --format '{{json .Mounts}}' | jq .

If you don’t have jq installed:

# Ubuntu/Debian
sudo apt-get update && sudo apt-get install -y jq

# AlmaLinux/Rocky
sudo dnf install -y jq

You’re looking for mounts with "Type": "volume". Typical examples:

  • postgres_data (PostgreSQL)
  • mariadb_data (MariaDB/MySQL)
  • uploads (user files)
  • redis_data (optional; many people skip Redis and rebuild it)

Also back up the Compose project directory itself. It contains what you need to bring the stack back up cleanly.

  • compose.yml / docker-compose.yml
  • .env (secrets and config)
  • reverse proxy config, custom Nginx/Caddy files, and app config overrides

Common mistake: backing up volumes but not your .env. The restore “works,” but the app won’t start because DB passwords and app secrets are gone.

Step 2: Install restic and create a dedicated backup identity

Install restic from your distro packages where possible. This keeps updates predictable.

# Ubuntu/Debian
sudo apt-get update && sudo apt-get install -y restic openssh-client

# AlmaLinux/Rocky
sudo dnf install -y epel-release
sudo dnf install -y restic openssh-clients

Create a local system user for backups. Separate identities make permissions and audit trails simpler.

sudo useradd -r -m -d /var/lib/restic -s /usr/sbin/nologin restic
sudo mkdir -p /etc/restic
sudo chown root:root /etc/restic
sudo chmod 750 /etc/restic

Step 3: Create an offsite SFTP destination (recommended)

This assumes you have a second server to receive backups. If you don’t, fix that first.

For most stacks, a small VPS with a larger disk is enough.

On the backup destination server, create a user locked to SFTP-only access.

sudo useradd -m -d /srv/restic -s /usr/sbin/nologin restic-backup
sudo passwd -l restic-backup
sudo mkdir -p /srv/restic/repos
sudo chown -R restic-backup:restic-backup /srv/restic

Enable SFTP access. In /etc/ssh/sshd_config, ensure you have:

Subsystem sftp internal-sftp

Optionally restrict the user (recommended). Add at the bottom:

Match User restic-backup
  ChrootDirectory /srv/restic
  ForceCommand internal-sftp
  X11Forwarding no
  AllowTcpForwarding no

Note: Chroot requires correct ownership/permissions. The chroot directory (/srv/restic) must be owned by root and not writable by the user:

sudo chown root:root /srv/restic
sudo chmod 755 /srv/restic
sudo mkdir -p /srv/restic/repos
sudo chown -R restic-backup:restic-backup /srv/restic/repos

Restart SSH:

sudo systemctl restart sshd

Step 4: Create SSH keys for backups (no passwords)

On the source VPS (the one running Docker Compose), create a dedicated SSH key for restic.

sudo -u restic mkdir -p /var/lib/restic/.ssh
sudo -u restic chmod 700 /var/lib/restic/.ssh

sudo -u restic ssh-keygen -t ed25519 -a 64 -f /var/lib/restic/.ssh/id_ed25519 -N ''

Copy the public key to the destination server’s authorized_keys for the restic-backup user. If you can SSH as an admin, you can do:

sudo -u restic ssh-copy-id -i /var/lib/restic/.ssh/id_ed25519.pub restic-backup@BACKUP_SERVER_IP

Test the connection:

sudo -u restic ssh -i /var/lib/restic/.ssh/id_ed25519 restic-backup@BACKUP_SERVER_IP -p 22

If you’re tightening security anyway, do it now while you’re touching SSH. HostMyCode has a practical guide: set up SSH keys and disable password login.

Step 5: Decide how you’ll get consistent backups (databases matter)

For uploads and config, file-level snapshots are usually fine. Databases are different.

You need consistency at the moment you capture them. You have two practical choices:

  • Short maintenance stop: stop the stack, back up volumes, start again. For small sites, downtime is often 15–60 seconds.
  • Logical dump + files backup: keep the site up, dump the DB to a file, then back up the dump plus uploads/config volumes.

This tutorial uses logical dumps. They avoid downtime and give you output that’s easy to validate.

Keep the “stop-the-world” option in your pocket. It’s useful for heavy-write periods, big migrations, or suspected corruption.

Step 6: Create the backup workspace and environment file

Create a directory to stage dumps. Then create a config file for restic variables.

sudo mkdir -p /var/backups/compose-restic
sudo chown -R restic:restic /var/backups/compose-restic
sudo chmod 750 /var/backups/compose-restic

Create /etc/restic/compose.env:

sudo tee /etc/restic/compose.env > /dev/null <<'EOF'
# Restic repository via SFTP
RESTIC_REPOSITORY=sftp:restic-backup@BACKUP_SERVER_IP:/repos/compose-prod

# Store this password safely. Anyone with it can restore/decrypt.
RESTIC_PASSWORD=REPLACE_WITH_A_LONG_RANDOM_PASSWORD

# Optional hardening
RESTIC_CACHE_DIR=/var/lib/restic/cache
BORG_UNKNOWN=0
EOF

sudo chmod 640 /etc/restic/compose.env
sudo chown root:restic /etc/restic/compose.env

Create the cache directory:

sudo mkdir -p /var/lib/restic/cache
sudo chown -R restic:restic /var/lib/restic/cache
sudo chmod 700 /var/lib/restic/cache

Common mistake: leaving RESTIC_PASSWORD in a world-readable file. Keep permissions tight, and don’t commit it to Git.

Step 7: Initialize the restic repository

You only do this once. It creates the repository metadata at the destination path.

sudo -u restic bash -c 'set -a; source /etc/restic/compose.env; set +a; restic init'

Verify:

sudo -u restic bash -c 'set -a; source /etc/restic/compose.env; set +a; restic snapshots'

You should see “no snapshots” and no errors.

Step 8: Write a backup script for Docker Compose volumes + DB dumps

The script below does five jobs:

  1. Uses your compose project path
  2. Creates database dumps (Postgres or MariaDB/MySQL)
  3. Copies volume data from /var/lib/docker/volumes
  4. Includes the Compose directory (excluding common junk)
  5. Prunes old snapshots with retention rules

Create /usr/local/sbin/compose-restic-backup.sh:

sudo tee /usr/local/sbin/compose-restic-backup.sh > /dev/null <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

# ---- Config you MUST set ----
COMPOSE_DIR="/opt/compose/myapp"         # path containing compose.yml and .env
PROJECT_NAME="myapp"                    # used for tags

# DB container names (set to empty if not used)
POSTGRES_CONTAINER=""                   # e.g. "myapp-postgres-1"
POSTGRES_DB=""                          # e.g. "appdb"
POSTGRES_USER=""                        # e.g. "appuser"

MARIADB_CONTAINER=""                    # e.g. "myapp-mariadb-1"
MARIADB_DB=""                           # e.g. "appdb"
MARIADB_USER=""                         # e.g. "appuser"
MARIADB_PASSWORD=""                     # prefer docker secrets in real stacks

# Volumes to back up (docker volume names)
VOLUMES=(
  "${PROJECT_NAME}_uploads"
  "${PROJECT_NAME}_data"
)

STAGING_BASE="/var/backups/compose-restic"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
STAGING_DIR="${STAGING_BASE}/${PROJECT_NAME}-${STAMP}"

# ---- Load restic env ----
set -a
source /etc/restic/compose.env
set +a

log() { echo "[$(date -u +%F' '%T)] $*"; }

require_cmd() {
  command -v "$1" >/dev/null 2>&1 || { echo "Missing command: $1"; exit 1; }
}

require_cmd docker
require_cmd restic
require_cmd tar

mkdir -p "${STAGING_DIR}/dumps" "${STAGING_DIR}/compose" "${STAGING_DIR}/volumes"
chmod 700 "${STAGING_DIR}"

log "Staging to ${STAGING_DIR}"

# ---- Copy compose project (keep it small) ----
log "Copying compose project files"
rsync -a --delete \
  --exclude '.git/' \
  --exclude 'node_modules/' \
  --exclude '.cache/' \
  --exclude 'tmp/' \
  "${COMPOSE_DIR}/" "${STAGING_DIR}/compose/"

# ---- Database dumps ----
if [[ -n "${POSTGRES_CONTAINER}" ]]; then
  log "Dumping PostgreSQL from container ${POSTGRES_CONTAINER}"
  docker exec "${POSTGRES_CONTAINER}" pg_dump -U "${POSTGRES_USER}" -d "${POSTGRES_DB}" \
    | gzip -9 > "${STAGING_DIR}/dumps/postgres-${POSTGRES_DB}.sql.gz"
fi

if [[ -n "${MARIADB_CONTAINER}" ]]; then
  log "Dumping MariaDB/MySQL from container ${MARIADB_CONTAINER}"
  docker exec "${MARIADB_CONTAINER}" \
    sh -lc "mysqldump -u'${MARIADB_USER}' -p'${MARIADB_PASSWORD}' '${MARIADB_DB}' --single-transaction --quick" \
    | gzip -9 > "${STAGING_DIR}/dumps/mysql-${MARIADB_DB}.sql.gz"
fi

# ---- Volume backup (file copy) ----
log "Copying Docker volume contents"
for v in "${VOLUMES[@]}"; do
  if docker volume inspect "$v" >/dev/null 2>&1; then
    src="/var/lib/docker/volumes/${v}/_data"
    dst="${STAGING_DIR}/volumes/${v}"
    mkdir -p "$dst"
    # Preserve permissions and xattrs where possible
    rsync -aHAX --numeric-ids "${src}/" "${dst}/"
  else
    log "WARNING: volume not found: ${v} (skipping)"
  fi
done

# ---- Run restic backup ----
log "Running restic backup"
restic backup "${STAGING_DIR}" \
  --tag "${PROJECT_NAME}" \
  --tag "docker-compose" \
  --tag "${STAMP}"

# ---- Retention policy ----
log "Applying retention policy"
restic forget \
  --tag "${PROJECT_NAME}" \
  --keep-daily 7 \
  --keep-weekly 4 \
  --keep-monthly 6 \
  --prune

log "Checking repository integrity (quick)"
restic check --read-data-subset=1/50

log "Cleaning staging"
rm -rf "${STAGING_DIR}"

log "Backup complete"
EOF

sudo chmod 750 /usr/local/sbin/compose-restic-backup.sh
sudo chown root:restic /usr/local/sbin/compose-restic-backup.sh

Set your variables: edit the script and update COMPOSE_DIR, PROJECT_NAME, container names, and volumes.

sudo nano /usr/local/sbin/compose-restic-backup.sh

How to get container names reliably:

docker ps --format '{{.Names}}' | sort

How to get volume names for the project:

docker volume ls --format '{{.Name}}' | grep '^myapp_'

Step 9: Run your first backup (manual) and verify logs

Run the script as the restic user. It needs Docker access.

Add restic to the docker group:

sudo usermod -aG docker restic
# Log out/in doesn’t apply to system users; restart is not required.
# Use newgrp for the current shell if testing interactively as restic.

Now run:

sudo -u restic /usr/local/sbin/compose-restic-backup.sh

If you hit permission errors while reading volumes, Docker may use a nonstandard root path. LSM settings can also block access.

Confirm the Docker root:

docker info --format '{{.DockerRootDir}}'

Most systems use /var/lib/docker. If yours differs, update the script’s volume path to match.

Check snapshots:

sudo -u restic bash -c 'set -a; source /etc/restic/compose.env; set +a; restic snapshots --tag myapp'

Step 10: Add a tested restore procedure (don’t skip this)

If you haven’t restored a backup, you don’t know if it works. Do the restore test now, while the stack is still fresh in your head.

Create a restore directory:

sudo mkdir -p /var/restore-test
sudo chown restic:restic /var/restore-test
sudo chmod 700 /var/restore-test

Restore the latest snapshot tagged for your project:

sudo -u restic bash -c '
  set -a; source /etc/restic/compose.env; set +a;
  SNAP=$(restic snapshots --tag myapp --latest 1 --json | jq -r ".[0].short_id");
  echo "Restoring snapshot $SNAP";
  restic restore "$SNAP" --target /var/restore-test
'

Verify contents:

sudo ls -la /var/restore-test
sudo find /var/restore-test -maxdepth 3 -type f | head

Now do a basic sanity check for your dumps:

sudo gzip -t /var/restore-test/var/backups/compose-restic/*/dumps/*.gz

If you back up a PostgreSQL dump, validate it’s not empty:

sudo zcat /var/restore-test/var/backups/compose-restic/*/dumps/postgres-*.sql.gz | head

If you want to go one step further, spin up a temporary container and import the dump into a disposable database. That tends to catch broken credentials and truncated dump files.

Step 11: Automate with systemd (service + timer)

Create a service unit at /etc/systemd/system/compose-restic-backup.service:

sudo tee /etc/systemd/system/compose-restic-backup.service > /dev/null <<'EOF'
[Unit]
Description=Restic backup for Docker Compose volumes
Wants=network-online.target
After=network-online.target docker.service

[Service]
Type=oneshot
User=restic
Group=restic
ExecStart=/usr/local/sbin/compose-restic-backup.sh
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7
# Hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/backups/compose-restic /var/lib/restic /var/restore-test /var/lib/docker /etc/restic

[Install]
WantedBy=multi-user.target
EOF

Create a timer at /etc/systemd/system/compose-restic-backup.timer:

sudo tee /etc/systemd/system/compose-restic-backup.timer > /dev/null <<'EOF'
[Unit]
Description=Daily restic backup timer (Docker Compose)

[Timer]
OnCalendar=*-*-* 02:30:00
RandomizedDelaySec=15m
Persistent=true

[Install]
WantedBy=timers.target
EOF

Enable and start:

sudo systemctl daemon-reload
sudo systemctl enable --now compose-restic-backup.timer

Check next run time:

systemctl list-timers --all | grep compose-restic

Run once immediately (recommended):

sudo systemctl start compose-restic-backup.service
sudo journalctl -u compose-restic-backup.service -n 200 --no-pager

Step 12: Practical hardening and operational tips

  • Don’t back up Redis unless it’s critical. For caches, a rebuild is usually fine. For queues, treat it like data.
  • Watch your retention settings. 7 daily / 4 weekly / 6 monthly is a solid baseline. Adjust to your storage and recovery needs.
  • Keep dumps fast and inspectable. Plain SQL + gzip is easy to spot-check. If you need faster restores, consider pg_dump --format=c, but accept that quick “head of file” checks become less useful.
  • Monitor backup health. A timer that fails quietly is worse than no backup, because it builds false confidence.

For monitoring, you can add lightweight dashboards and alerting. If you want a fast setup that works on a typical VPS, see Install Netdata on Ubuntu VPS for real-time monitoring.

You can also monitor the timer/service status and disk usage trends.

Troubleshooting: common failures and quick fixes

  • “permission denied” reading volume data: confirm Docker root dir (docker info), confirm the systemd service has ReadWritePaths for it, and ensure your distro’s security modules aren’t blocking. Start by running the script manually as root once to separate permissions from restic/repo issues.
  • Restic says repository not found: verify RESTIC_REPOSITORY path and that the SFTP user can see it. Test with sudo -u restic sftp restic-backup@BACKUP_SERVER_IP.
  • Backups are huge: you’re probably dragging along build artifacts, caches, or media you don’t need. Add --exclude rules to the rsync section, or remove non-essential volumes from the list.
  • DB dump fails: the container name is wrong, or the CLI tool isn’t installed in the image. Official Postgres/MariaDB images include pg_dump/mysqldump. If you use a custom image, exec into the container and confirm the binaries exist.

If you’re hitting disk space alerts during staging, move STAGING_BASE to a larger mount. HostMyCode also has a walkthrough for cleaning space safely: Disk full on VPS: find large files and free space safely.

Optional: Consistent “stop-the-world” backups for high-write apps

If your app writes constantly (busy WooCommerce, large helpdesk, high traffic API), logical dumps may be too slow or too large.

In those cases, a short maintenance stop is often the most reliable option:

cd /opt/compose/myapp

docker compose down
# run your backup script (volume copy + restic) here

docker compose up -d

Use this sparingly, but don’t dismiss it. For many self-hosted stacks, it’s the most predictable path to consistent volume data.

Summary checklist (copy/paste for your runbook)

  • Restic installed and repo initialized offsite
  • Compose directory backed up (compose.yml, .env, proxy configs)
  • DB dumps created on each run (Postgres and/or MariaDB/MySQL)
  • Docker volumes copied from DockerRootDir volumes path
  • Retention applied with restic forget --prune
  • At least one successful restore test into /var/restore-test
  • systemd timer enabled; journald logs reviewed

If you’re running production apps, backups are only useful if the server underneath stays predictable. You want stable storage, sane networking, and enough headroom that nightly snapshots don’t compete with your workloads. Start with a HostMyCode VPS, or use managed VPS hosting if you’d rather spend your time on the application than on maintenance windows.

FAQ

Do I really need to back up Docker volumes if I have images in a registry?

Yes. Images are replaceable; volumes hold your database files, uploads, and app state. Without volumes (and your .env/compose files), your restore won’t be complete.

Is it safe to back up /var/lib/docker/volumes directly?

For many self-hosted stacks, yes, especially for non-database data. For databases, prefer dumps (as shown) or stop the stack briefly to avoid inconsistent files.

How often should I run restic backups?

Daily is a baseline. If you run transactional apps (orders, tickets), consider 2–6 times per day. Keep retention realistic for your storage budget.

How do I know my backups aren’t corrupted?

Run restic check periodically and do restore tests. This tutorial includes a small data read test on each run and a full restore test workflow.

Can I use this for WordPress in Docker Compose?

Yes. Back up the WordPress uploads volume, the database dump, and your Compose directory. If you also run scheduled tasks, consider moving WP-Cron to real cron for reliability; see Set up WordPress cron jobs with real server cron.

Keep it boring: schedule it, check it, restore it

The best backup setup is the one you can understand six months from now, under pressure.

Restic gives you encrypted snapshots, retention controls, and integrity checks without turning your VPS into a side project. Treat restores as routine maintenance, not a once-a-year fire drill.

Docker Compose Backups With Restic on a VPS | HostMyCode