Database backups with Docker: the volume copy loses data silently
Measured, not claimed: what a volume copy really loses under load – plus a script that finds every database container itself and fails loudly.
Table of contents
“Never back up a running database file” appears in every backup guide, usually without evidence. We measured it on our test server, and the result is more uncomfortable than the usual warning.
The copy is not broken. It starts, it passes every integrity check, and that is exactly why nobody notices that data is missing.
What are we building?
A backup script that finds every running database container by itself, so you never have to add a line for a new app. When something goes wrong it fails loudly instead of quietly dropping an empty file. Plus the matching restore commands per engine, each one timed.
Covered: PostgreSQL and MariaDB/MySQL, plus SQLite as a separate case, where container discovery cannot work by design.
Every number below comes from this site’s test VPS: PostgreSQL 18.6 with two million rows (195 MB) and MariaDB 12.3.3 with one million rows.
Requirements
- A server with Docker and at least one containerised database (Compose basics).
zstdfor compression:apt install zstd.- A working restic backup. This article produces the dumps; restic moves them off the server. Both together are the backup. A dump file on the same disk is not one.
VPS 1000 G12.5
4 vCores · 8 GB RAM · 128 GB SSD
from €14.50/month
The server every measurement was taken on.
💶 1 month free:
Single use, valid for VPS 1000 G12.5. Redeem in the cart →
💶 €5.95 voucher for new netcup customers: always valid · not for domains or VPS Lite
Step by step
Step 1: What the volume copy actually does
The setup: a PostgreSQL database under constant load, four processes committing individual transactions without pause. While that runs, we copy the volume the way people usually do:
docker run --rm -v YOUR_VOLUME:/from:ro -v copy:/to alpine:3.22 sh -c 'cp -a /from/. /to/'Then we start a second container on the copy. Four runs:
run 1 (cp -a) copy 1.8 s | container running | id in copy 1858 original 1959 lost 101
run 2 (cp -a) copy 1.3 s | container running | id in copy 2521 original 2595 lost 74
run 3 (cp -a) copy 1.3 s | container running | id in copy 3125 original 3202 lost 77
slow copy copy 70.2 s | container running | id in copy 3892 original 10856 lost 6964Every copy starts. Every one recovers cleanly. The base table holds exactly its two million
rows in all four cases, and bt_index_check reports no problem with the index. The log
shows nothing but what follows any power cut:
LOG: database system was not properly shut down; automatic recovery in progress
LOG: redo starts at 0/1BA1C50
LOG: redo done at 0/1668A1B8And yet committed transactions are missing: orders a customer received a confirmation for. The copy is a consistent state from the moment it started, not from the moment it finished.
The reason lies in cp itself: it reads the files one after another, not in a single
instant. PostgreSQL finds a write-ahead log state from the early phase of the copy and
replays exactly up to there. Everything committed afterwards sits in files that do not
match that state and gets discarded. The database does precisely the right thing. It just
cannot know that it is restoring the state from a minute ago rather than from just now.
The fourth line is the real warning. When we artificially stretched the same copy to 70
seconds, almost 7,000 transactions were gone. The loss grows with the duration, and a real
20 GB database does not copy itself in one and a half seconds. MariaDB behaves the same
way: InnoDB: Starting crash recovery, data complete, 106 transactions gone.
Why this is worse than a broken backup
Step 2: The dump as the counter-design
A dump is the opposite: a state from a single transaction, with a defined point in time, and it tells you when it fails. The PostgreSQL variants, measured against the same database:
pg_dumpall raw 1.3 s 108M
pg_dumpall | zstd 1.3 s 22M
pg_dump -Fc 2.8 s 21M
mariadb-dump | zstd 2.0 s 5.0MThe second line is remarkable: compression costs no extra time and saves 80 percent.
The dump is slower than zstd can compress anyway.
The choice between the two PostgreSQL tools comes down to a detail that gets expensive in
an emergency. pg_dump saves one database, pg_dumpall the whole cluster, including
roles. We put a readonly role into the test database, the kind every second application
creates for reports, and restored both dumps:
pg_dumpall: CREATE ROLE readonly → included
pg_dump -Fc: CREATE ROLE readonly → not includedRestoring from the -Fc dump then looks like this:
pg_restore: error: could not execute query: ERROR: role "readonly" does not exist
Command was: GRANT SELECT ON TABLE public.bestellungen TO readonly;
pg_restore: warning: errors ignored on restore: 2The data is there, the permissions are not: the app starts and is allowed to do nothing.
That is why the script below uses pg_dumpall. pg_dump -Fc is the better format
(smaller, selective, restorable in parallel), but then you need
pg_dumpall --globals-only alongside it.
Step 3: The script that finds your databases itself
The core is an idea worth remembering: you do not maintain a list of your databases, the script reads it from Docker, via the image name of the running container.
docker ps --filter status=running --format '{{.Names}}\t{{.Image}}'This has a side effect that eliminates an entire class of problem: because the dump tool
runs inside the container, client and server versions always match. The classic
annoyance of a host pg_dump being too old for the server cannot occur in the first place.
#!/bin/bash
# Backs up every running database container the script finds by itself.
set -euo pipefail
TARGET="${TARGET:-/var/backups/databases}"
KEEP_DAYS="${KEEP_DAYS:-14}"
EXCLUDE="${EXCLUDE:-^$}" # e.g. "old-testdb|zammad-backup"
MIN_BYTES="${MIN_BYTES:-1024}"
PING_URL="${PING_URL:-}"
POSTGRES_RE='(^|/)postgres(:|$)'
MARIADB_RE='(^|/)(mariadb|mysql)(:|$)'
failed=0
log() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; }
containers() {
docker ps --filter status=running --format '{{.Names}}\t{{.Image}}' \
| awk -F'\t' -v re="$1" '$2 ~ re {print $1}' \
| grep -Ev "$EXCLUDE" || true
}
back_up() {
local name=$1 ext=$2; shift 2
local dir="$TARGET/$name"; mkdir -p "$dir"
local out="$dir/$(date +%Y%m%d-%H%M).$ext.zst"
local tmp="$out.incomplete" size
if "$@" | zstd -q -o "$tmp"; then
size=$(stat -c%s "$tmp")
if [ "$size" -lt "$MIN_BYTES" ]; then
log "FAILED $name – dump is only $size bytes, discarded"
rm -f "$tmp"; failed=1; return
fi
mv "$tmp" "$out"
log "OK $name – $(numfmt --to=iec "$size")"
else
log "FAILED $name – dump failed"
rm -f "$tmp"; failed=1
fi
}
# A helper container reads SQLite straight from the app's data directory (step 5).
back_up_sqlite() {
local name=$1 dir=$2 file=$3
back_up "$name" db docker run --rm -v "$dir":/data alpine:3.22 sh -c \
"test -f /data/$file && apk add -q --no-cache sqlite >/dev/null \
&& sqlite3 /data/$file \"VACUUM INTO '/tmp/backup.db'\" && cat /tmp/backup.db"
}
for c in $(containers "$POSTGRES_RE"); do
back_up "$c" sql docker exec "$c" sh -c 'pg_dumpall -U "${POSTGRES_USER:-postgres}"'
done
for c in $(containers "$MARIADB_RE"); do
back_up "$c" sql docker exec "$c" sh -c \
'MYSQL_PWD="${MARIADB_ROOT_PASSWORD:-${MYSQL_ROOT_PASSWORD:-}}" \
exec mariadb-dump --all-databases --single-transaction --quick -uroot'
done
# One line per SQLite app: name, data directory, file (step 5)
# back_up_sqlite linkding /opt/linkding/data db.sqlite3
find "$TARGET" -type f -name '*.zst' -mtime +"$KEEP_DAYS" -delete
find "$TARGET" -type f -name '*.incomplete' -mtime +1 -delete
find "$TARGET" -mindepth 1 -type d -empty -delete
if [ "$failed" -ne 0 ]; then
log "At least one dump failed."
[ -n "$PING_URL" ] && curl -fsS -m 10 --retry 3 "$PING_URL/fail" >/dev/null || true
exit 1
fi
log "All dumps fine."
[ -n "$PING_URL" ] && curl -fsS -m 10 --retry 3 "$PING_URL" >/dev/null || trueSave the script as /usr/local/bin/db-backup.sh and make it executable:
chmod +x /usr/local/bin/db-backup.sh
db-backup.shOne run on the test server:
20:54:20 OK dbtest-shop-db-1 – 22M
20:54:22 OK dbtest-wiki-db-1 – 5.0M
20:54:22 All dumps fine.Two MariaDB flags deserve an explanation, because they are often missing.
--single-transaction takes the dump from a single read transaction. That is the
difference between “state as of 3 a.m.” and “somewhere between 3:00 and 3:02”, and it does
not lock the tables. The flag only applies to transactional engines, though; an old MyISAM
or Aria table lying around is not covered. --quick fetches rows one at a time instead of
loading a whole table into memory first. On a small server that is the difference between
a dump and an OOM kill.
Step 4: Three details the obvious version gets wrong
The version of this script you find everywhere looks almost identical, but it has three places that get expensive in daily use. We reproduced all three on our test server.
A failed dump looks exactly like a successful one. We ran a database container in which
the server is not reachable, precisely the situation shortly after a restart. Without
set -o pipefail this happens:
pg_dumpall: error: connection to server on socket … failed: No such file or directory
Pipeline exit status: 0
-rw-r----- 1 root root 13 20261004-2100.sql.zst
Decompressed content: 0 byteszstd writes a formally valid file with zero content, and because only the last command in
a pipeline counts, the shell reports success. Fourteen nights later the retention rule has
deleted the last real dump. The same scenario with the script above:
20:55:05 FAILED empty-db – dump failed
20:55:07 OK dbtest-shop-db-1 – 22M
20:55:09 OK dbtest-wiki-db-1 – 5.0M
20:55:09 At least one dump failed.
Exit status: 1The remaining databases are still backed up, because one broken container must not abort
the night. But the run ends with 1, and nothing half-finished is left in the target
directory. That
is what writing to .incomplete and renaming only after the size check is for.
Otherwise the password sits in the process list. The common variant passes it with
-p:
sh -c mariadb-dump --all-databases --single-transaction -uroot -p<THE-REAL-PASSWORD>That line is visible not only inside the container but on the host; ps is enough. The
fact that mariadb-dump overwrites its own arguments with -px xxxxxxxx afterwards does
not help, because the surrounding sh -c line keeps the plain text. The version above sets
MYSQL_PWD inside the container from its own environment variable; the command line
then contains nothing but variable names, and ps no longer finds the password:
Processes whose command line contains the password: noneMARIADB_PWD does not exist
MARIADB_PWD, matching MARIADB_ROOT_PASSWORD. That variable
does not exist, and the dump then runs into Access denied … (using password: NO). Even on
MariaDB 12 and 13 the environment variable is still called MYSQL_PWD.The retention rule deletes directories too. The usual line reads
find … -mtime +14 -delete -type f. The problem is the order: -delete is evaluated
before -type f is even tested.
-mtime +14 -delete -type f → the empty old directory is GONE
-type f -mtime +14 -delete → the directory survivesIn daily use this goes unnoticed for a long time, because a directory refreshes its modification time as soon as a file inside it disappears. But a container that has been gone for two weeks takes its backup directory with it.
Step 5: SQLite, where container discovery cannot work
Vaultwarden, Linkding, FreshRSS and many others need no database container at all: their database is a file inside the app container. A script searching by image name will never find it.
And simply copying the file is tricky for another reason. In WAL mode, which practically
all of these apps use, freshly written data initially lives only in the notes.db-wal
file next to it:
-rw-r--r-- 64786432 notes.db
-rw-r--r-- 32768 notes.db-shm
-rw-r--r-- 5805112 notes.db-walBack up only notes.db and you leave those 5.8 MB behind. The copy still passes
PRAGMA integrity_check with ok, so the check does not protect you here.
The documented route would be sqlite3 .backup. Under sustained load, however, we got a
surprise:
timeout 30 sqlite3 /data/notes.db ".backup /tmp/copy.db"Terminated
Exit status: 143 duration: 30 sNothing. SQLite’s backup interface starts over whenever somebody writes to the source database. With enough write traffic it never reaches the end. On a first attempt the same command hung for seventeen minutes before we aborted it.
VACUUM INTO is reliable instead. It reads in a single read transaction and therefore
completes even under load:
sqlite3 /data/notes.db "VACUUM INTO '/tmp/copy.db';"Exit status: 0 duration: 0 s
Rows in the copy: 595910
Integrity: okApp images rarely ship the sqlite3 for this, though. Vaultwarden, Linkding and FreshRSS
all come without it. That is why in the script above a short-lived helper container reads
the database straight from the app’s data directory while the app keeps running. The
function back_up_sqlite contains two details:
VACUUM INTOaborts withoutput file already existsif the target file is already there. So the copy is made in the/tmpof the helper container, which disappears afterwards. Otherwise every second night would fail.- The
test -fup front is needed because on a typo in the file namesqlite3silently creates a new, empty database in the app’s directory.
Each app gets one line at the marked spot in the script, right below the MariaDB loop, with
name, data directory and file. Not at the end: there it would sit behind the exit 1 of the
failure case.
back_up_sqlite linkding /opt/linkding/data db.sqlite3
back_up_sqlite vaultwarden /root/vaultwarden/vw-data db.sqlite3The helper container fetches sqlite from the Alpine package sources on every run. Without
network access the line fails loudly like any other dump.
What about Redis, Valkey, MongoDB?
Redis and Valkey run in almost every self-hosting recipe as a cache or session store.
Both may be lost; the application rebuilds them. A backup only pays off if you
deliberately use Redis as a database, for queues say; then you need persistence enabled and
back up the dump.rdb.
MongoDB fits the pattern: another loop over (^|/)mongo(:|$) with
mongodump --archive. Mongo does not appear anywhere in this site’s recipes, though, which
is why the block is not in the script above: we do not put untested code in a tutorial.
Step 6: The restore, timed
A dump nobody has ever restored is not a backup but a hope. All three routes played through once, each into a fresh, empty container:
| Route | Duration | Result |
|---|---|---|
pg_dumpall → psql | 6.1 s | 2,000,000 rows, role readonly back |
pg_restore -j4 from -Fc | 6.2 s | 2,000,000 rows, roles missing (exit 1) |
mariadb from mariadb-dump | 7.8 s | 1,000,000 rows |
PostgreSQL:
zstd -dc YOUR_DUMP.sql.zst | docker exec -i YOUR_CONTAINER psql -U YOUR_USER -d postgresMariaDB:
zstd -dc YOUR_DUMP.sql.zst | docker exec -i -e MYSQL_PWD="YOUR_PASSWORD" YOUR_CONTAINER mariadb -urootA dump made with --all-databases also contains the user table of the server it came from.
Until the container’s next restart the new container’s root password still applies, after
that the old one from the backup. So set MARIADB_ROOT_PASSWORD in the new container to the
old password right away, or you lock yourself out at the first restart.
Wait for real readiness, not for the ping
Our first restore attempt failed with ERROR 1045 (28000): Access denied for user 'root'@'localhost' even though the password was correct. During first-time initialisation
MariaDB starts a temporary server that already answers mariadb-admin ping; the final
one with your password is not running yet. So wait for a real query instead:
until docker exec -e MYSQL_PWD="$PW" YOUR_CONTAINER mariadb -uroot -e "SELECT 1;" >/dev/null 2>&1; do sleep 2; doneThat takes a few seconds, between 6 and 14 on our test server.
Step 7: Every night, and then off the server
A systemd timer starts the script, and PING_URL reports
the outcome to Healthchecks. A run that never
happens goes unnoticed otherwise. First the service:
systemctl edit --full --force db-backup.service[Unit]
Description=Database dumps
[Service]
Type=oneshot
Environment=PING_URL=https://YOUR_HEALTHCHECKS_URL/YOUR_UUID
ExecStart=/usr/local/bin/db-backup.shThen the timer. It runs at 2 a.m., before the 2:30 a.m. restic job from the restic tutorial, so the fresh dumps are included:
systemctl edit --full --force db-backup.timer[Unit]
Description=Database dumps every night before the restic job
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.targetPersistent=true catches up on a run the server missed while it was off. Enable and check:
systemctl enable --now db-backup.timer
systemctl list-timers db-backup.timerNEXT LEFT LAST PASSED UNIT ACTIVATES
Tue 2026-12-01 02:00:00 CET 8h - - db-backup.timer db-backup.serviceIf a dump fails, the service ends as failed and systemctl --failed lists it, on top of
the failure ping to Healthchecks.
That completes the division of labour: this script produces consistent dumps on the server, restic encrypts them and moves them elsewhere. Without the second half your backup sits on the same disk as the original and shares its fate.
When things go wrong
The dump is there, but all permissions are missing after the restore. You backed up
with pg_dump instead of pg_dumpall. Roles and passwords belong to the cluster, not to
the individual database, so they are not in a database dump. Either switch to pg_dumpall
or additionally back up pg_dumpall --globals-only and restore that first.
FAILED … dump is only 846 bytes, discarded for a new app. The database is still
empty, and its dump stays below the MIN_BYTES minimum of 1024 bytes the script uses to
catch empty dumps. Once the app has created its tables, the dump is larger. Until then,
exclude the container via EXCLUDE rather than lowering the threshold.
pg_dumpall: error: … role "root" does not exist. The container does not set
POSTGRES_USER, so the script passes an empty user name and the client falls back to the
Linux user. The ${POSTGRES_USER:-postgres} in the script above catches exactly this.
sqlite3 .backup never returns. The backup interface restarts whenever the source
database is written to, and under sustained load it never reaches the end. Use
VACUUM INTO instead – it reads in a single transaction and finishes in a fraction of a
second even under load.
ERROR 1045 (28000): Access denied when restoring into a fresh MariaDB container. The
container is still initialising, running a temporary server without your password. Do not
wait for mariadb-admin ping, wait for a real query to succeed.
The container with postgres:18 no longer starts after switching. As of PostgreSQL 18
the volume belongs at /var/lib/postgresql rather than /var/lib/postgresql/data – the
images store data per major version under 18/docker. With the old path startup aborts,
even with an empty volume. If you already have data in the old layout, move it via a dump
rather than just bending the mount – step by step in PostgreSQL major upgrade in a container (Tutorial expected in January 2027).
Your problem is not listed? Search all error messages →
Maintenance & backups
Once a quarter: a real restore. Not “the dump is 22 MB, it’ll be fine”, but a fresh container, the dump in, count the rows. Going by the numbers above that costs under ten seconds of compute and is the only proof there is.
With every new app: take one look. The script finds Postgres, MariaDB and MySQL by
itself, but not an app with SQLite or a more exotic database. A glance at docker ps
after setting it up is enough, and for SQLite you add a back_up_sqlite line.
Match retention to reality. Fourteen days is a good default as long as somebody notices within fourteen days that something is missing. For data that is rarely touched that is optimistic. Then add a monthly copy to the restic retention rule.
And the most uncomfortable habit last: after each night, do not check whether the backup ran, but whether it did not. That is what the exit status is for, and what the ping is for. A silent script is not a good sign, it is no sign at all.
Send feedback: feedback@serverkueche.de
You might also like

