Master MySQL Backups: Commands for Single DB, Multiple DBs, Compression & Restoration
This guide explains how to use mysqldump to back up individual databases, multiple databases, all databases, specific tables, and how to compress backups, include drop statements, export only schema, and restore data using both interactive and non‑interactive MySQL commands, plus an automated backup script.
MySQL Backup Database
Backup a single database
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --database DBNAME > filename.sqlBackup multiple databases
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --database DB1 DB2 DB3 > filename.sqlBackup all databases
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --all-databases > filename.sqlBackup specific tables
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" DBNAME TABLE1 > filename.sqlBackup specific multiple tables
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" DBNAME TABLE1 TABLE2 > filename.sqlThe -B parameter
Adding
-Bmakes the dump file contain
CREATE DATABASEand
USEstatements, so you do not need to create the target database manually before restoring.
Compressing backups with gzip
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --database DBNAME | gzip > filename.sql.gzIncluding drop statements
Use
--add-drop-databaseto include
DROP DATABASEstatements and
--add-drop-tableto include
DROP TABLEstatements in the dump.
Exporting only schema
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --no-data DB1 DB2 > filename.sqlRestoring a dump
Interactive method:
mysql -uUSER -p"PASSWORD" DBNAME < dumpfile.sqlUsing the
sourcecommand inside the MySQL console:
mysql> source dumpfile.sqlNon‑interactive method with
-e:
mysql -uUSER -p"PASSWORD" -e "use DBNAME; source dumpfile.sql"Automatic backup script (bash)
#!/bin/bash
backupdir=/data/mysqlbak
time=$(date +%Y%m%d-%H%M)
mysqldump -hHOST -PPORT -uroot -p"PASSWORD" --all-databases --single-transaction --default-character-set=utf8 | gzip > $backupdir/mysql$time.sql.gz
find $backupdir -name "mysql*.sql.gz" -type f -mtime +7 -exec rm {} \; > /dev/null 2>&1Create the backup directory, make the script executable, and add a cron job (e.g.,
00 3 * * * /data/mysqlbak/mysqlbak.sh) to run it daily.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.