Skip to main content

Databases · Intermediate · 18 min

Back up and restore MySQL with mysqldump and binary logs

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 LTS · MySQL 9.7.4 LTS

You will take consistent, compressed dumps of a MySQL 9.7 database with a private backup account, prove they restore, recover from an accidental DELETE by replaying the binary log up to the moment before it, and leave a nightly backup script running.

On this page

A dump file only tells you what the database looked like when the dump ran. If someone runs DELETE FROM orders at 16:40 and your last dump is from 02:00, the dump alone loses fourteen hours of orders. MySQL's binary log closes that gap: it records every change since the dump, so you can restore the dump and then replay the log up to the second before the mistake.

In this tutorial you build that whole chain on a small shop database. You make a backup account whose password lives in a private option file, take a consistent compressed dump with mysqldump, restore it into a fresh database to prove it works, cause an accident on purpose, and then undo it with mysqlbinlog. It ends with a nightly script and a restore you have actually tested.

Every command runs on the database server. The tutorial assumes MySQL 9.7 LTS is installed as in /tutorials/install-mysql-9-7-lts-on-ubuntu-26-04.

Step 1 · Create a shop database worth protecting

Make a database with three tables, a stored procedure and a scheduled event, so you can see later that all of them come back from the backup. shop is a practice name: if a database called shop already exists on your server, pick another name and use it throughout.

Bash
sudo mysql <<'SQL'
CREATE DATABASE shop CHARACTER SET utf8mb4;
USE shop;
CREATE TABLE customers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
  id INT AUTO_INCREMENT PRIMARY KEY,
  customer_id INT NOT NULL,
  total_cents INT NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (customer_id) REFERENCES customers (id)
);
CREATE TABLE carts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  customer_id INT NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO customers (name) VALUES ('Amara'), ('Kwame'), ('Lindiwe');
INSERT INTO orders (customer_id, total_cents)
  WITH RECURSIVE seq (n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 500)
  SELECT (n % 3) + 1, 1000 + n FROM seq;
CREATE PROCEDURE customer_total (IN cid INT)
  SELECT SUM(total_cents) AS total_cents FROM orders WHERE customer_id = cid;
CREATE EVENT purge_old_carts
  ON SCHEDULE EVERY 1 DAY STARTS (CURRENT_DATE + INTERVAL 1 DAY + INTERVAL 3 HOUR)
  DO DELETE FROM carts WHERE created_at < NOW() - INTERVAL 30 DAY;
SQL

The event clears carts older than 30 days at 03:00 each night, starting tomorrow. All three tables use InnoDB, the default engine, which matters for the next steps.

Check it worked

Bash
sudo mysql -e "SELECT COUNT(*) AS orders, SUM(total_cents) AS total FROM shop.orders;"
sudo mysql -e "SELECT @@log_bin AS binary_log_on, @@binlog_expire_logs_seconds AS keep_seconds, @@gtid_mode AS gtid_mode;"

The first query shows 500 orders and a total of 625250. The second shows 1 and 2592000: binary logging is on by default in MySQL 9.7, and the server keeps log files for 30 days before deleting them. That window is how far back you can recover with the method below, so if you keep dumps for longer, raise it. The last column says whether the server tags each transaction with a global transaction ID (ON) or not (OFF). The commands below work either way.

Step 2 · Make a backup account with a private option file

Backups should not run as the database root user, and the password should never appear on a command line, where ps and your shell history can show it. Create an account that can read everything but change nothing, and keep its password in an option file that only root can read.

Generate a random password into a shell variable. Nothing is typed, so nothing lands in your history:

Bash
BACKUP_PW="$(openssl rand -base64 24 | tr -d '/+=')"

Create the file empty and private first, then write into it, so the password is never in a file anyone else could read, even for a moment:

Bash
sudo install -m 600 -o root -g root /dev/null /etc/mysql/backup.cnf
printf '[client]\nuser=backup\npassword="%s"\n' "$BACKUP_PW" | sudo tee /etc/mysql/backup.cnf > /dev/null

Now create the account with the same password. printf is built into the shell, so the password goes down the pipe without ever being a program argument:

Bash
printf "CREATE USER 'backup'@'localhost' IDENTIFIED BY '%s';\n" "$BACKUP_PW" | sudo mysql
unset BACKUP_PW
sudo mysql -e "GRANT SELECT, SHOW VIEW, TRIGGER, EVENT, PROCESS, RELOAD, REPLICATION CLIENT ON *.* TO 'backup'@'localhost';"

Each privilege has a job. SELECT (granted globally, which --routines needs) reads tables and stored procedures, SHOW VIEW, TRIGGER and EVENT read those objects, PROCESS lets mysqldump read tablespace details, and RELOAD with REPLICATION CLIENT let it note the binary log position at the moment of the dump. None of them lets the account change data. If CREATE USER fails with ERROR 1819, your server has a password policy turned on. Run the first command again with a symbol appended, for example BACKUP_PW="$(openssl rand -base64 24 | tr -d '/+=')-x", then rewrite the file.

Check it worked

Bash
sudo ls -l /etc/mysql/backup.cnf
sudo mysql --defaults-extra-file=/etc/mysql/backup.cnf -e "SELECT CURRENT_USER();"

The file shows -rw------- and root root. The query signs in from the option file and prints backup@localhost. --defaults-extra-file must be the first option on the line: put it later and the client stops with an unknown variable error instead of reading the file.

Step 3 · Take a consistent, compressed dump

Make a private folder for backups, then dump shop into it through gzip:

Bash
sudo install -d -m 700 /var/backups/mysql
sudo bash -o pipefail -c 'umask 077; mysqldump --defaults-extra-file=/etc/mysql/backup.cnf --single-transaction --routines --events --triggers --source-data=2 --set-gtid-purged=OFF shop | gzip > /var/backups/mysql/shop-first.sql.gz'

The whole pipeline runs inside sudo bash, because the folder belongs to root and your own shell could not write the file. -o pipefail makes the command fail if mysqldump fails, rather than reporting the success of gzip. What the options do:

  • --single-transaction reads every table inside one transaction, so the dump is a single consistent moment and the shop keeps taking orders while it runs. This only holds for InnoDB tables. MyISAM tables can still change mid-dump. Avoid ALTER TABLE, DROP TABLE, RENAME TABLE and TRUNCATE TABLE on the dumped tables until it finishes.
  • --routines and --events add stored procedures, functions and scheduled events, which mysqldump leaves out by default. --triggers is on by default. It is written out here so the intent is plain.
  • --source-data=2 writes the binary log file name and position of that consistent moment into the dump as a comment. This is where replaying the log will start. It takes a global read lock for an instant at the start, not for the whole dump.
  • --set-gtid-purged=OFF leaves out the SET @@GLOBAL.GTID_PURGED line that mysqldump adds when the server uses global transaction IDs (GTIDs). That line marks the dumped transactions as already applied, and loading it back into the same server fails with ERROR 3546 because the server has applied them already. Without it, the dump restores into a scratch database on this server, which is what this tutorial does. On a server without GTIDs the option changes nothing.

The dump names one database and no --databases option, so it contains no CREATE DATABASE or USE lines. That lets you restore it into a database with any name.

Check it worked

A dump that stopped halfway still unzips, so check both the compression and the last line:

Bash
sudo gzip -t /var/backups/mysql/shop-first.sql.gz && echo "gzip OK"
sudo zcat /var/backups/mysql/shop-first.sql.gz | tail -n 1
sudo zcat /var/backups/mysql/shop-first.sql.gz | grep -oE 'CHANGE REPLICATION SOURCE TO[^;]*|PROCEDURE `customer_total`|EVENT `purge_old_carts`'

You see gzip OK, then -- Dump completed on with a date, which mysqldump writes only when it finishes. The last command prints a line such as CHANGE REPLICATION SOURCE TO SOURCE_LOG_FILE='binlog.000002', SOURCE_LOG_POS=12345, with your own file and number, followed by matches for the procedure and the event.

Step 4 · Restore into a fresh database and compare

Never test a backup by restoring over the live database. Restore into a new, empty one:

Bash
sudo mysql -e "CREATE DATABASE shop_check CHARACTER SET utf8mb4;"
sudo zcat /var/backups/mysql/shop-first.sql.gz | sudo mysql shop_check

The mysql client stops at the first error and exits with a non-zero code, so a broken dump fails loudly here.

Check it worked

Compare the live and restored data side by side, then list the procedure and event that came back:

Bash
sudo mysql -e "SELECT
  (SELECT COUNT(*) FROM shop.orders) AS live_orders,
  (SELECT COUNT(*) FROM shop_check.orders) AS restored_orders,
  (SELECT SUM(total_cents) FROM shop.orders) AS live_total,
  (SELECT SUM(total_cents) FROM shop_check.orders) AS restored_total;"
sudo mysql -e "SELECT ROUTINE_NAME FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = 'shop_check';
  SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA = 'shop_check';"

Both counts are 500 and both totals are 625250. The second command lists customer_total and purge_old_carts. Restored events are live, so a scratch copy would start purging its own carts at 03:00. Drop it now that it has done its job:

Bash
sudo mysql -e "DROP DATABASE shop_check;"

Step 5 · Make some changes, then cause an accident

Real databases keep changing after the backup. Add three orders, which exist only in the binary log, not in the dump:

Bash
sudo mysql shop -e "INSERT INTO orders (customer_id, total_cents) VALUES (1, 4200), (2, 1999), (3, 7350);"

Now make the classic mistake: a DELETE with no WHERE. Run this only against the practice shop database, never one that holds data you care about:

Bash
sudo mysql shop -e "DELETE FROM orders;"

Check it worked

Bash
sudo mysql -e "SELECT COUNT(*) AS orders FROM shop.orders;"

The count is 0. Restoring the dump alone would bring back 500 orders and lose the three you just added. The next two steps recover all 503.

Step 6 · Find the DELETE in the binary log

Start with the coordinates the dump recorded. These commands read them back into shell variables:

Bash
START_FILE="$(sudo zcat /var/backups/mysql/shop-first.sql.gz | grep -o "SOURCE_LOG_FILE='[^']*'" | cut -d"'" -f2)"
START_POS="$(sudo zcat /var/backups/mysql/shop-first.sql.gz | grep -o 'SOURCE_LOG_POS=[0-9]*' | cut -d= -f2)"
BINLOG_DIR="$(dirname "$(sudo mysql -N -e 'SELECT @@log_bin_basename;')")"
echo "Replay starts in $BINLOG_DIR/$START_FILE at position $START_POS"
sudo mysql -e "SHOW BINARY LOGS;"

BINLOG_DIR is the folder the server writes its binary logs to, read from @@log_bin_basename. It is /var/lib/mysql unless log_bin points somewhere else in your configuration, so the commands below work either way. SHOW BINARY LOGS lists the log files and their sizes. Here every change since the dump sits in START_FILE. If the list shows later files too, because the server restarted or a file filled up, pass all of them to mysqlbinlog in order, starting with START_FILE. The start position applies to the first file you name and the stop position to the last.

Get a readable summary of every row change since the dump. --base64-output=decode-rows --verbose turns the binary row events into commented SQL that starts with ###:

Bash
sudo mysqlbinlog --base64-output=decode-rows --verbose --start-position="$START_POS" "$BINLOG_DIR/$START_FILE" \
  | grep -E '^### (INSERT INTO|UPDATE|DELETE FROM)' | uniq -c

You see a few lines, each with a count in front. Something like this, in order: 3 inserts and 500 inserts into tables in shop_check, then 3 inserts into the shop orders table, and last 503 deletes from it. Two things stand out. The binary log covers the whole server, so your test restore into shop_check is in there too, and the accident is one line from the end.

To replay up to the DELETE but not include it, you need the position where its transaction begins. In the decoded output each event starts with a # at <position> line, and each transaction opens with a GTID event. This awk remembers the position of the latest transaction start and prints it when it reaches the first deleted row:

Bash
STOP_POS="$(sudo mysqlbinlog --base64-output=decode-rows --verbose --start-position="$START_POS" "$BINLOG_DIR/$START_FILE" \
  | awk '/^# at /{pos=$3} /GTID/ && /last_committed/{txn=pos} /^### DELETE FROM `shop`.`orders`/ && !found {print txn; found=1}')"
echo "The DELETE transaction starts at position $STOP_POS"

Check it worked

The last line prints a position larger than START_POS. If it is empty, the DELETE is in a later file: run the command on that file instead. On a busy server, look at the lines around a candidate position before trusting it, for example with sudo mysqlbinlog --base64-output=decode-rows --verbose --start-position=<position> "$BINLOG_DIR/<file>" | less, and confirm the first ### line under it is the statement you want to skip.

Step 7 · Replay the log into a recovery copy

Rebuild the database as it was just before the accident, in a new database called shop_pitr, while the live shop stays untouched. First restore the dump:

Bash
sudo mysql -e "CREATE DATABASE shop_pitr CHARACTER SET utf8mb4;"
sudo zcat /var/backups/mysql/shop-first.sql.gz | sudo mysql shop_pitr

Then replay the binary log from the dump's position to the start of the DELETE:

Bash
sudo mysqlbinlog --start-position="$START_POS" --stop-position="$STOP_POS" --skip-gtids \
  --rewrite-db='shop->shop_pitr' --database=shop_pitr \
  "$BINLOG_DIR/$START_FILE" | sudo mysql

--rewrite-db sends changes recorded against shop into shop_pitr instead. --database keeps only changes to that one database, which drops the shop_check restore from the output. mysqlbinlog applies the rewrite first and the filter second, which is why the filter names shop_pitr, not shop. Without the filter, the replay would re-run every change any database on the server made since the dump. Here that means creating, filling and dropping shop_check again; on a live server it means writing every other database's changes a second time. --skip-gtids drops the original transaction IDs from the output. With GTIDs on, the server has already applied those IDs and would silently skip every replayed transaction; without them it gives the replayed changes new IDs. Leave out --base64-output here: the default output is the only form that is safe to run back into a server.

Check it worked

Bash
if [ "$(sudo mysql -N -e 'SELECT COUNT(*) FROM shop_pitr.orders')" = 503 ]; then
  echo "shop_pitr has all 503 orders"
else
  echo "shop_pitr does not have 503 orders"; false
fi

It prints shop_pitr has all 503 orders: the 500 from the dump plus the three from the log.

Put the rows back

The accident only emptied orders, so copy that table's rows back into the live database:

Bash
sudo mysql -e "INSERT INTO shop.orders SELECT * FROM shop_pitr.orders;"
sudo mysql -e "SELECT COUNT(*) AS orders, SUM(total_cents) AS total FROM shop.orders;"

The live shop shows 503 orders and a total of 638799. If legitimate writes happened after the DELETE, you can replay those too: start a second mysqlbinlog run at the position of the transaction that follows the DELETE. When a whole database is damaged, stop the application, then swap tables in one statement with RENAME TABLE shop.orders TO shop_pitr.orders_broken, shop_pitr.orders TO shop.orders; and do the same for each table.

Step 8 · Run a nightly dump and test the restore

Put the dump into a script. It writes to a .partial name first, checks the file, and only then gives it its final name, so a half-written dump is never mistaken for a good one. It also deletes backups older than 14 days:

Bash
sudo tee /usr/local/bin/mysql-backup.sh > /dev/null <<'SCRIPT'
#!/bin/bash
set -euo pipefail
umask 077

DB="${1:?usage: mysql-backup.sh <database>}"
DIR=/var/backups/mysql
OUT="$DIR/$DB-$(date +%F-%H%M).sql.gz"

mysqldump --defaults-extra-file=/etc/mysql/backup.cnf \
  --single-transaction --routines --events --triggers --source-data=2 --set-gtid-purged=OFF \
  "$DB" | gzip > "$OUT.partial"

gzip -t "$OUT.partial"
zcat "$OUT.partial" | tail -n 1 | grep -q 'Dump completed'
mv "$OUT.partial" "$OUT"

find "$DIR" -name "$DB-*.sql.gz*" -mtime +14 -delete
SCRIPT
sudo chmod 755 /usr/local/bin/mysql-backup.sh

Run it once by hand so you see it work before cron does:

Bash
sudo /usr/local/bin/mysql-backup.sh shop
sudo ls -l /var/backups/mysql

A file named shop-<date>-<time>.sql.gz is listed next to shop-first.sql.gz, both readable by root alone. Schedule it for 02:15 every night. A file in /etc/cron.d names the user it runs as, and adding one leaves everyone's crontab alone:

Bash
echo '15 2 * * * root /usr/local/bin/mysql-backup.sh shop' | sudo tee /etc/cron.d/mysql-backup

Cron ignores files in /etc/cron.d whose names contain a dot, so keep mysql-backup without an extension. Cron is covered in /tutorials/schedule-jobs-with-cron.

Check it worked

A backup is only proven by a restore. Restore the newest nightly file into a scratch database and compare it with the live one:

Bash
LATEST="$(sudo find /var/backups/mysql -name 'shop-2*.sql.gz' | sort | tail -n 1)"
echo "Testing $LATEST"
sudo mysql -e "CREATE DATABASE shop_check CHARACTER SET utf8mb4;"
sudo zcat "$LATEST" | sudo mysql shop_check
sudo mysql -e "SELECT
  (SELECT COUNT(*) FROM shop.orders) AS live_orders,
  (SELECT COUNT(*) FROM shop_check.orders) AS restored_orders;"

Both columns show 503. Drop the scratch copy so its restored event does not run:

Bash
sudo mysql -e "DROP DATABASE shop_check;"

Repeat this test every month or so, and after any change to the script.

A dump on the same disk as the database is lost with the server, and so are the binary logs you need for the hours after it. Copy /var/backups/mysql and the binlog.* files to another machine or to object storage, for example with /tutorials/back-up-a-server-with-restic. Compressed dumps of text-heavy tables are often a fraction of their raw size, which helps when the copy goes over a metered or prepaid mobile data connection. Restic skips files and chunks it already holds, so old dumps and finished binary logs are not sent twice, but each new compressed dump is mostly new data and goes up in full.

For databases of tens of gigabytes or more, mysqldump gets slow because it writes and restores in a single thread. MySQL Shell's dump utilities (util.dumpInstance() and util.dumpSchemas(), restored with util.loadDump()) split the work across several threads and compress the output, which cuts both the backup and the restore time.

Step 9 · Clean up the practice pieces

Remove the recovery copy, which you no longer need:

Bash
sudo mysql -e "DROP DATABASE shop_pitr;"

If you set all of this up only to practise, also remove the practice database, the backup account, its option file, the script, the schedule and the dumps. These commands delete them for good, so skip any you want to keep for a real database:

Bash
sudo mysql -e "DROP DATABASE shop; DROP USER 'backup'@'localhost';"
sudo rm -f /etc/mysql/backup.cnf /usr/local/bin/mysql-backup.sh /etc/cron.d/mysql-backup
sudo rm -rf /var/backups/mysql

Check it worked

Bash
sudo mysql -e "SHOW DATABASES LIKE 'shop%'; SELECT user FROM mysql.user WHERE user = 'backup';"

Both queries return nothing: no shop databases and no backup account are left.

Next steps

  • Make the queries in your restored database fast: /tutorials/read-mysql-query-plans-and-add-the-right-index.
  • See how the same backup and restore discipline works in PostgreSQL: /tutorials/back-up-and-restore-postgresql-with-pg-dump.
  • Get the dumps and binary logs off the server: /tutorials/back-up-a-server-with-restic.
  • The reference for every option is the MySQL 9.7 manual pages for mysqldump and mysqlbinlog, at dev.mysql.com/doc/refman/9.7/en/.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.