Backup & Restore
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A backup is only as good as the restore you have tried. This page covers the tools that ship with MySQL, the
approaches that need other software, and a complete point-in-time recovery (restore a full backup, then replay the binary
log up to just before a mistake) executed against real servers. Verified on the mysql:latest Docker image, which
reported 26.10.0; the shop example (see Getting Started) is the data, plus a
stored procedure customer_orders, a trigger orders_audit and an audit_log table added so that routines and
triggers have something to dump. Passwords on command lines are for the demo only.
Choosing an approach
| Logical (dump) | Physical (files) | |
|---|---|---|
What it stores |
SQL statements or delimited rows |
the InnoDB data files themselves |
Portable across versions and platforms |
yes, within limits |
no, same major version and architecture |
Speed on a large dataset |
slow to dump and much slower to load (indexes rebuilt) |
fast, limited by disk throughput |
Selective restore (one table) |
easy |
hard, needs tablespace tricks or a restored copy |
Tools |
|
file copy, snapshots, clone, XtraBackup, Enterprise Backup |
Small and medium databases do well with dumps; very large ones need physical backups. Either way, keep the binary log so that you can recover to a point after the backup.
mysqldump
mysqldump reads the data over a normal connection and writes SQL. The options that matter for a consistent dump of
InnoDB tables:
-
--single-transactionstarts one consistent-read transaction for the whole dump (REPEATABLE READ snapshot), so writers are not blocked. It is correct for InnoDB only; with other engines use--lock-all-tables. -
--routines,--triggersand--eventsinclude stored programs. Triggers are on by default; routines and events are not. -
--source-data=2writes a commentedCHANGE REPLICATION SOURCE TOline with the binary log file and position of the snapshot (=1writes it uncommented, for building a replica). It was called--master-databefore. -
--databases(instead of a bare database name) addsCREATE DATABASEandUSE;--all-databasesalso dumps themysqlsystem schema, with accounts. -
--set-gtid-purged=OFFomits the GTID state line; see the restore notes below.
mysqldump -uroot -psecret --single-transaction --routines --triggers --events \
--source-data=2 --databases shop > /backup/shop-full.sql
Warning: A partial dump from a server that has GTIDs will by default include the GTIDs of all transactions, even those that changed suppressed parts of the database. If you don't want to restore GTIDs, pass --set-gtid-purged=OFF. To make a complete dump, pass --all-databases --triggers --routines --events.
The warning appears because this server runs with gtid_mode=ON (the default in this image) and the dump is of one
schema. The start of the file shows the coordinates the dump is consistent with:
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '588dcf63-dd39-11f1-b1a5-565d5198c4ce:1-75'; -- Position to start replication or point-in-time recovery from -- CHANGE REPLICATION SOURCE TO SOURCE_LOG_FILE='binlog.000004', SOURCE_LOG_POS=1795;
The file has CREATE TABLE, INSERT and trigger/routine definitions (9,975 bytes here). Routine and trigger
definitions in a dump keep their DEFINER; the account has to exist on the target, or restore with the right privileges
(SET_ANY_DEFINER) or strip the clause.
Useful variants: --no-data (schema only), --no-create-info (data only), --where="..." to dump a subset,
--tab (server-side SELECT ... INTO OUTFILE files for LOAD DATA), --hex-blob, --compress and --column-statistics=0.
A dump taken without --single-transaction on a busy server is not consistent; one with it on a MyISAM table is not
either.
Restoring a dump
A dump is restored by feeding it to the mysql client. The statements recreate everything, so the target schema is
replaced. Restoring into a different server, as a disaster recovery would:
docker exec my-b cat /backup/shop-full.sql | docker exec -i my-b2 mysql -uroot -psecret
docker exec my-b2 mysql -uroot -psecret -e "SELECT COUNT(*) FROM shop.orders; SELECT COUNT(*) FROM shop.order_items"
orders 8 items 11
The fresh server was empty, so GTID_PURGED could be applied, and afterwards its gtid_executed held the source’s
transactions 1-75 plus the target’s own five from initialisation. If the target is not empty,
SET @@GLOBAL.GTID_PURGED fails: reset the target (RESET BINARY LOGS AND GTIDS, destructive, only on a server you are
rebuilding) or dump with --set-gtid-purged=OFF, and accept that the restored data has no GTID history.
Selective restore
A full SQL dump is plain text laid out table by table, so one table can be pulled out with sed using the markers
mysqldump writes (-- Table structure for table ...). Restoring only products into a scratch database:
sed -n '/^-- Table structure for table `products`/,/^-- Dumping routines/p' shop-full.sql \
| head -n -3 > products-only.sql
mysql -uroot -psecret -e "CREATE DATABASE scratch"
mysql -uroot -psecret scratch < products-only.sql
mysql -uroot -psecret -e "SELECT sku, name, tags FROM scratch.products"
+-----+---------------+---------------------------------+ | sku | name | tags | +-----+---------------+---------------------------------+ | A-1 | Standing Desk | ["office", "ergonomic"] | | A-2 | Office Chair | ["office", "ergonomic", "sale"] | | B-7 | Desk Lamp | ["office", "led"] | | C-3 | USB-C Hub | ["usb", "sale"] | | C-9 | Monitor 27in | ["display", "office"] | +-----+---------------+---------------------------------+
Restoring into a scratch schema first and then copying the rows you need back (INSERT ... SELECT) is safer than
restoring over the live table. For one table at dump time simply name it: mysqldump shop products > products.sql.
MySQL Shell dump utilities
MySQL Shell (mysqlsh) provides parallel, compressed, chunked dumps that are much faster than mysqldump for large
data and can be loaded with util.loadDump. mysqlsh is included in the mysql:latest image used here (version
26.10.0), so no extra image was needed. The utilities are util.dumpInstance(), util.dumpSchemas() and
util.dumpTables(); this example dumps the shop schema with util.dumpSchemas, the same call shape as the
instance-level one. Selected output (progress lines trimmed):
mysqlsh --js --uri root:secret@localhost -e "util.dumpSchemas(['shop'], '/backup/shell-dump', {threads: 2})"
1 schemas will be dumped and within them 5 tables, 0 views, 1 routine, 1 trigger. Running data dump using 2 threads. Dump duration: 00:00:00s Schemas dumped: 1 Tables dumped: 5 Uncompressed data size: 1.20 KB Compressed data size: 762 bytes Rows written: 21
The dump directory holds one DDL file and one compressed data chunk per table (shop@orders.sql,
shop@orders@@0.tsv.zst) plus metadata (@.json, shop.json) and the triggers file shop@orders.triggers.sql. The tool
takes a short global read lock only to start its consistent transactions, then releases it. The dump was
copied to a second server and loaded there (the load needs local_infile enabled on the target):
mysql -uroot -psecret -e "SET GLOBAL local_infile=1"
mysqlsh --js --uri root:secret@localhost -e "util.loadDump('/backup-shell', {threads: 2})"
Target is MySQL 26.10.0. Dump was produced from MySQL 26.10.0 ... 5 chunks (21 rows, 1.20 KB) for 5 tables in 1 schemas were loaded in 0 sec (avg throughput 1.20 KB/s, 21.00 rows/s) 0 warnings were reported during the load.
The restored shop.orders held 10 rows: the eight original orders plus orders 1009 and 1010 added later in the
recovery demonstration below. util.dumpInstance also dumps accounts (unless users: false) and supports dryRun, filters
(excludeSchemas, includeTables), cloud object-storage targets and a resumable loadDump that can recover from an
interrupted load by its progress file.
Physical backups
A physical backup copies the data files. The server has to be in a state where the files are consistent.
Cold copy and volume snapshots
The simplest physical backup is to stop the server cleanly and copy the data directory. In Docker the data lives in a volume, so a helper container with the same volume can archive it; restoring is extracting into a fresh volume:
docker stop my-b3
docker run --rm --volumes-from my-b3 -v "$PWD/cold":/out --entrypoint tar mysql:latest \
czf /out/datadir.tgz -C /var/lib/mysql .
docker volume create my-b3-restore
docker run --rm -v my-b3-restore:/var/lib/mysql -v "$PWD/cold":/in --entrypoint tar mysql:latest \
xzf /in/datadir.tgz -C /var/lib/mysql
docker run -d --name my-b3 -p 33064:3306 -v my-b3-restore:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=secret mysql:latest
The archive was about 6 MB (the data directory of a small, freshly initialised server) and the new container answered
SELECT COUNT(*) FROM shop.orders with 10, the same value as the source. As a check that the copy is identical,
CHECKSUM TABLE returns the same numbers on source and copy (here orders 3814633486, customers 138535711,
products 3751971953, and 0 for the empty order_items).
The same idea works while the server is running only if the storage layer can take an atomic snapshot of the whole
data directory (LVM, ZFS, EBS or similar): an InnoDB crash-consistent snapshot is recovered at the next start like after
a power failure, provided data, redo log and undo are in the same snapshot. Snapshotting only part of them is not safe. A
file copy of a running server with cp or rsync is never safe.
The clone plugin
The clone plugin copies the InnoDB data of a running server, locally or to another server over the network, and is the
building block for provisioning replicas. It must be installed first, and the destination directory must not exist and
must be writable by the mysql user:
INSTALL PLUGIN clone SONAME 'mysql_clone.so';
CLONE LOCAL DATA DIRECTORY = '/var/lib/mysql-files/clone1';
SELECT STATE, ERROR_NO FROM performance_schema.clone_status;
+-----------+----------+ | STATE | ERROR_NO | +-----------+----------+ | Completed | 0 | +-----------+----------+
The result was a 94 MB directory (ibdata1, mysql, shop, sys, #innodb_redo) that can be started as a server.
A first attempt to clone into /backup, which mysql could not write, failed with error 1006 (permission denied), so
the target directory permission is the first thing to check. Remote cloning uses CLONE INSTANCE FROM ..., which needs
the BACKUP_ADMIN privilege on the donor.
XtraBackup and MySQL Enterprise Backup
Two tools do hot physical backups of a running server without stopping it, copying data files while recording redo log so the copy can be made consistent afterwards (a "prepare" step):
-
Percona XtraBackup is open source and works with MySQL and Percona Server. It supports full and incremental backups, compression, encryption and streaming, and a typical flow is
xtrabackup --backup, thenxtrabackup --prepare, then copy back into an empty data directory. -
MySQL Enterprise Backup (
mysqlbackup) is part of the commercial MySQL Enterprise Edition, with similar full, incremental, compressed and encrypted backups.
Neither is part of the community server image, and neither was run for this page; the commands in this paragraph are described, not executed here. Both fit well with binary-log recovery (below): the backup records the log position it corresponds to.
Point-in-time recovery with mysqlbinlog
A backup restores the state at the moment it was taken. The binary log records every change after that, so replaying it
rebuilds the state up to any later point, for example just before a bad DELETE. Requirements: binary logging on (it is
by default here), the logs since the backup still present, and the position the backup corresponds to (the
--source-data line, or the GTID_PURGED value).
The tool is mysqlbinlog. In this image it is installed with MySQL Shell at /usr/libexec/mysqlsh/mysqlbinlog rather than
on the PATH. The scenario, run end to end:
-
The full dump
shop-full.sqlabove was taken atbinlog.000004, position 1795 (GTID:75). -
After it, a valid order 1009 was inserted, a customer was updated, and then someone ran
DELETE FROM order_items;with theWHEREclause forgotten, followed by one more valid order, 1010.
START TRANSACTION;
INSERT INTO orders VALUES (1009,'c-4','open','2026-04-01 10:00:00');
INSERT INTO order_items VALUES (1009,'C-3',2,39.00);
COMMIT;
UPDATE customers SET tier='pro' WHERE id='c-4';
DELETE FROM order_items;
INSERT INTO orders VALUES (1010,'c-2','open','2026-04-02 11:00:00');
SHOW BINLOG EVENTS identifies the transaction to avoid (trimmed to the transaction boundaries):
SHOW BINLOG EVENTS IN 'binlog.000004' FROM 1795; Pos Event_type Info 1795 Gtid SET @@SESSION.GTID_NEXT= '588dcf63-...:76' <- order 1009 2357 Gtid SET @@SESSION.GTID_NEXT= '588dcf63-...:77' <- customer update 2781 Gtid SET @@SESSION.GTID_NEXT= '588dcf63-...:78' <- the accidental DELETE (ends at 3286) 3286 Gtid SET @@SESSION.GTID_NEXT= '588dcf63-...:79' <- order 1010 3695 Xid COMMIT
mysqlbinlog can also show what a row event did. With -vv --base64-output=DECODE-ROWS the accidental transaction is
visible as one row image per deleted line:
### DELETE FROM `shop`.`order_items` ### WHERE ### @1=1001 /* INT meta=0 nullable=0 is_null=0 */ ### @2='A-1' /* VARSTRING(40) meta=40 nullable=0 is_null=0 */
Recovery on a fresh server (my-b2, already holding the dump restored as above): replay from the dump position to the
position just before the bad transaction, piping the SQL into the client.
mysqlbinlog --start-position=1795 --stop-position=2781 /var/lib/mysql/binlog.000004 \
| mysql -uroot -psecret
mysql -uroot -psecret -e "SELECT COUNT(*) orders FROM shop.orders; SELECT COUNT(*) items FROM shop.order_items;
SELECT id, tier FROM shop.customers WHERE id='c-4'; SELECT * FROM shop.audit_log"
orders 9 items 12 c-4 pro audit_log: 1 new order 1009 2026-11-10 19:12:10
Order 1009 and its line (12 items), the tier change and the trigger’s audit row are back, and the DELETE is gone. The
trade-off of a stop position is that order 1010, committed after the accident, is lost with it. With GTIDs there is a
better option: replay everything except the bad transaction.
mysqlbinlog --start-position=1795 \
--exclude-gtids=588dcf63-dd39-11f1-b1a5-565d5198c4ce:78 /var/lib/mysql/binlog.000004 \
| mysql -uroot -psecret
orders: 1010 1009 1008 (latest three ids) items: 12
This second recovery, done on yet another fresh server, kept order 1010 and still skipped the DELETE. Excluding a
transaction is only safe when nothing later depended on it. Other selection options: --start-datetime/--stop-datetime
(coarse, to the second), --include-gtids, --database (row events of one schema), and --read-from-remote-source to
read from a live server instead of files. Decoded output (-vv) is for reading, not for replaying.
Testing backups and good practice
-
Restore regularly into a scratch server and compare: row counts,
CHECKSUM TABLEon important tables, a smoke-test query. A backup that has never been restored is a hope. -
Time the restore. The recovery time objective depends on it, and a logical restore of a large database can take hours (index builds dominate).
-
Keep the binary logs for at least as long as the oldest backup you may restore, and copy them off the server (for example continuously with
mysqlbinlog --read-from-remote-source --raw --stop-never). Purging the logs, covered in Administration, destroys the point-in-time window. -
Store backups elsewhere and protect them: dumps contain data and (with
--all-databases) password hashes. -
Back up the configuration (option files, the
mysqld-auto.cnffile with persisted settings) and the account definitions alongside the data. -
Automate verification, not only the backup: a job that restores last night’s dump and runs a few checks is the difference between a backup and a tested backup.
For running the engine in containers see Docker. The next topic is keeping a live copy of the data: Replication & High Availability. Back to the MySQL Reference.