NewCode CLOUD — 20% off your first month on all cloud VPSClaim

How to Back Up MySQL and MariaDB Automatically (mysqldump, mariabackup and Cron)

Your database holds the part of your site that cannot be re-downloaded: orders, customers, posts, settings. Copying database files while the server is running produces corrupt backups, and a backup script that silently fails for months is worse than none. This guide sets up consistent, automated, rotated database backups for MySQL and MariaDB, and shows how to restore them.

Logical vs physical backups

Logical (mysqldump, mariadb-dump) Physical (mariabackup, Percona XtraBackup)
Output SQL text Copy of data files
Speed Slower for large databases Fast, scales to hundreds of GB
Restore Import SQL (slow for large DBs) Copy files back (fast)
Portability Works across versions and servers Same major version
Best for Up to a few GB, most websites Large databases, fast recovery

Most websites should start with logical dumps.

Step 1: A dedicated backup user

Do not put the root password in scripts. Create a user with only the privileges a dump needs:

CREATE USER 'backup'@'localhost' IDENTIFIED BY 'long-random-password';
GRANT SELECT, SHOW VIEW, TRIGGER, LOCK TABLES, EVENT, RELOAD, PROCESS ON *.* TO 'backup'@'localhost';
FLUSH PRIVILEGES;

Store the credentials in a protected option file so they never appear in the process list:

sudo nano /root/.my-backup.cnf
[client]
user = backup
password = long-random-password
sudo chmod 600 /root/.my-backup.cnf

Step 2: A consistent dump

mariadb-dump --defaults-extra-file=/root/.my-backup.cnf \
  --single-transaction --quick --routines --triggers --events \
  --databases shop | gzip > /var/backups/mysql/shop.sql.gz

(mysqldump takes the same options on MySQL.)

Option Why
--single-transaction Consistent snapshot of InnoDB tables without locking them — the site stays online
--quick Stream rows instead of loading whole tables into memory
--routines --triggers --events Include stored procedures, triggers and scheduled events
--databases Include CREATE DATABASE so restore recreates it

--single-transaction is only consistent for InnoDB. Old MyISAM tables need locking; convert them to InnoDB if you can.

Step 3: The backup script

/usr/local/bin/mysql-backup.sh:

#!/usr/bin/env bash
set -euo pipefail

DEST=/var/backups/mysql
KEEP_DAYS=14
STAMP=$(date +%F_%H%M)
OPTS="--defaults-extra-file=/root/.my-backup.cnf"

mkdir -p "$DEST/$STAMP"
chmod 700 "$DEST"

# One file per database (excluding system schemas)
for db in $(mariadb $OPTS -N -e "SHOW DATABASES" | grep -Ev '^(information_schema|performance_schema|mysql|sys)$'); do
  mariadb-dump $OPTS --single-transaction --quick --routines --triggers --events \
    --databases "$db" | gzip > "$DEST/$STAMP/$db.sql.gz"
done

# Users and grants (MariaDB 10.11+ supports --system=users; skipped silently on older versions)
mariadb-dump $OPTS --system=users 2>/dev/null | gzip > "$DEST/$STAMP/_users.sql.gz" || true

# Verify every file is valid gzip and not empty
for f in "$DEST/$STAMP"/*.sql.gz; do
  gzip -t "$f"
  [ "$(zcat "$f" | head -c 100 | wc -c)" -gt 0 ]
done

# Rotate
find "$DEST" -mindepth 1 -maxdepth 1 -type d -mtime +$KEEP_DAYS -exec rm -rf {} +

echo "$(date -Is) mysql backup ok: $STAMP"
sudo chmod 700 /usr/local/bin/mysql-backup.sh
sudo /usr/local/bin/mysql-backup.sh
ls -lh /var/backups/mysql/*/

One file per database means you can restore a single site without touching the others.

Step 4: Schedule

sudo crontab -e
20 2 * * * /usr/local/bin/mysql-backup.sh >> /var/log/mysql-backup.log 2>&1

Run at a quiet hour; dumps add read load. See cron jobs on Linux for pitfalls, and add a heartbeat so you know when it fails (Uptime Kuma push monitors).

Step 5: Copy off the server

Local dumps protect against mistakes, not against losing the server. Send them elsewhere every day — restic (encrypted, deduplicated) or rsync to another server in a different location.

Restoring

Restore one database:

zcat /var/backups/mysql/2026-11-19_0220/shop.sql.gz | sudo mariadb

Because the dump was made with --databases, it recreates and selects the database itself. To restore into a different database name (for testing), dump without --databases or edit the CREATE DATABASE/USE lines.

For large imports, speed things up:

( echo "SET autocommit=0; SET unique_checks=0; SET foreign_key_checks=0;"; zcat shop.sql.gz; echo "COMMIT;" ) | sudo mariadb shop

Restore a single table: extract its section from the dump, or restore the whole database to a temporary name and copy the table across.

Test restores regularly on another server or a temporary database. Check that the application actually works with the restored data.

Physical backups with mariabackup

For databases over a few gigabytes, or when restore time matters:

sudo apt install mariadb-backup
sudo mariabackup --backup --target-dir=/var/backups/mariabackup/full --user=backup --password='...'
sudo mariabackup --prepare --target-dir=/var/backups/mariabackup/full

--prepare makes the copy consistent. To restore: stop MariaDB, empty the data directory, run mariabackup --copy-back --target-dir=…, fix ownership (chown -R mysql:mysql /var/lib/mysql) and start MariaDB. Incremental backups are supported with --incremental-basedir.

For MySQL, Percona XtraBackup provides the equivalent.

Point-in-time recovery

A nightly dump loses everything since the last dump. If that is too much, enable binary logs and keep them with your backups. You can then restore the last dump and replay binlogs up to just before the mistake:

[mysqld]
log_bin = /var/lib/mysql/binlog
binlog_expire_logs_seconds = 604800
mariadb-binlog --stop-datetime="2026-11-19 14:29:00" binlog.000042 | sudo mariadb

Binlogs use disk space — set an expiry (see fixing a full disk).

Control panels and Docker

  • aaPanel, 1Panel and BT panel include database backup schedules — make sure they also copy backups off the server.
  • Docker: run the dump inside the container: docker compose exec -T db mariadb-dump -u root -p"$PW" --single-transaction --all-databases | gzip > all.sql.gz.

Checklist

  • Dedicated backup user and protected credentials file
  • --single-transaction dumps, one file per database
  • Integrity check and rotation in the script
  • Scheduled, logged and monitored with a heartbeat
  • Copied off-site daily
  • Restore tested within the last three months