Docker

Automated MariaDB Backups in Docker

Consistent dumps with --single-transaction, restoring, scheduling with cron, and three rules that make a backup something you can rely on.

Automated MariaDB Backups in Docker
Table of contents
  1. The basic command: a logical dump
  2. Restoring
  3. Automating it with cron on the host
  4. Three rules that make a backup real
  5. Dumps versus snapshots

A database in a volume survives the container being removed, but it is not protected against a failed disk or a human mistake (down -v, a dropped table). Regular backups are the only real insurance.

The basic command: a logical dump

Run it from inside the same Compose network, without exposing the database port:

docker compose exec -T db sh -c \
'exec mysqldump -u root -p"$MARIADB_ROOT_PASSWORD" --single-transaction wordpress' \
| gzip > backup-db.sql.gz

Notes: -T detaches the command from a terminal so the output reaches the file intact; --single-transaction takes a consistent snapshot without locking writes (for InnoDB tables); and the password is read from the container’s own environment variable, so it never ends up in your shell history. On recent MariaDB images the same tool is also available as mariadb-dump.

Restoring

gunzip < backup-db.sql.gz | docker compose exec -T db sh -c \
'exec mysql -u root -p"$MARIADB_ROOT_PASSWORD" wordpress'

Automating it with cron on the host

Manual backups get forgotten. One cron line on the server is enough:

30 3 * * *  cd /opt/wordpress-demo && ./backup.sh >> /var/log/wp-backup.log 2>&1

Here backup.sh does exactly what is described above: a compressed database dump plus a full archive of the WordPress files, timestamped, in a backup/ folder. If you prefer systemd, the same job works as a timer; see systemd services and timers.

Three rules that make a backup real

  1. An untested backup is not a backup. Restore it onto a test server once a month.
  2. Keep a copy off the server. A backup on the same disk as the database dies with it; move it to object storage or another server.
  3. Rotate. A simple scheme: keep 7 daily and 4 weekly copies and delete the rest, so the disk never fills up.

Dumps versus snapshots

A snapshot copies the whole volume, including half-written InnoDB files; a dump gives you logical output that can move between versions. For small stacks, a daily dump plus a copy of the files is the standard, sufficient combination.

About the author

Omid Nikpour

Linux systems administrator focused on Docker, databases and backups. Writes about keeping services running reliably in production.

All articles by Omid Nikpour

Comments

No comments yet. For technical questions, include the details (OS version, the exact error and the command you ran) to get a precise answer.

Leave a comment