Backup and restore MySQL Docker database
How to backup and restore a MySQL or MariaDB database that's running via Docker or Docker Compose.
Backing up Docker databases is straightforward using docker exec combined with mysqldump for backups and mysql for restores. You execute the standard MySQL commands inside the running container, redirecting output to or from your host filesystem.
Backup Command
To backup / make a dump of a MySQL or MariaDB database within a Docker container, just run:
docker exec DATABASECONTAINER mysqldump -u DATABASEUSER --password=DATABASEPASSWORD DATABASE > backup.sql
Restore Command
To restore a MySQL or MariaDB database from the mysqldump:
cat backup.sql | docker exec -i DATABASECONTAINER mysql -u DATABASEUSER --password=DATABASEPASSWORD DATABASE
Real-World Example
A complete backup and restore workflow might look like this:
docker exec wordpress-mysql mysqldump -u root --password=correcthorsebatterystaple wordpressdb > backup.sql
And restoring:
cat backup.sql | docker exec -i wordpress-mysql mysql -u root --password=correcthorsebatterystaple wordpressdb
Frequently Asked Questions
What if my container uses a different network?
The commands above work regardless of Docker network configuration because docker exec runs commands inside the container itself. The backup and restore operations don't require network access - they only need the container to be running. If you're having trouble accessing your database, ensure the container is running with docker ps.
How do I backup only specific tables?
To backup specific tables, add the table names after the database name in the mysqldump command. For example: docker exec CONTAINER mysqldump -u USER --password=PASS DATABASE table1 table2 > backup.sql. This creates a dump containing only the specified tables rather than the entire database.
Can I automate this backup?
Yes, you can automate backups using cron jobs on Linux or Task Scheduler on Windows. Create a shell script with your backup command and schedule it to run daily or hourly. For example, add a line like 0 2 * * * /path/to/backup-script.sh to your crontab to run backups daily at 2 AM. Remember to include timestamps in your backup filenames to prevent overwriting previous backups.