Back up PostgreSQL and MariaDB
Updated 27 Nov 2026 backup database
Take consistent database dumps on a schedule and restore them.
PostgreSQL
sudo -u postgres pg_dump -Fc appdb > appdb.dump
sudo -u postgres pg_dumpall --globals-only > globals.sql
Restore into a new database:
sudo -u postgres createdb appdb_restore
sudo -u postgres pg_restore -d appdb_restore < appdb.dump
MariaDB and MySQL
sudo mariadb-dump --single-transaction --routines --triggers appdb | gzip > appdb.sql.gz
sudo mariadb -e 'CREATE DATABASE appdb_restore'
gunzip -c appdb.sql.gz | sudo mariadb appdb_restore
--single-transaction gives a consistent copy of InnoDB tables without locking them.
Schedule it
#!/usr/bin/env bash
set -euo pipefail
umask 077
dir=/var/backups/db
mkdir -p "$dir"
file="$dir/appdb-$(date +%F).dump"
runuser -u postgres -- pg_dump -Fc appdb > "$file.part"
mv "$file.part" "$file"
find "$dir" -name 'appdb-*.dump' -mtime +14 -delete
Run it daily with cron or a timer, then copy the files off the server.