How to dump & restore a MariaDB/MySQL database from a docker container

In the same vein as my previous post on dumping and restoring your PostgreSQL database, here are mostly copy/paste-able commands for when you're using a MariaDB or MySQL database.


While the following commands have "mysql" in their name, they're actually called the same even for MariaDB, something they haven't (yet?) changed since forking off of MySQL. It seems that for the foreseeable future they'll continue to use the same command names, though they did recently add a MariaDB-named symlink, at least.
Dump using mysqldump
docker exec db_container_name mysqldump [--user yourusername] [--password=yourpassword] databasename > /desired/path/to/db.dump
Note: Even though this command is called mysqldump
, it exists and works with both MariaDB and MySQL. This should be preinstalled in most common containers such as the official MariaDB and MySQL ones.
Restoring
docker exec -i db_container_name mysql [--user yourusername] [--password=yourpassword] databasename < /path/to/db.dump
Dump and restore in one command
Just like in my other post on PostgreSQL, here's one command that you can run to effectively clone a database from one container to another. I am not sure if or when you might want to do this as in those cases you're probably able to re-use the same docker volume, but just in case your setup might require this, here it is:
docker exec db_container_name mysqldump [--user yourusername] [--password=yourpassword] database_name | docker exec -i 2nd_db_container_name mysql [--user yourusername] [--password=yourpassword] -C database_name
Conclusions
I hope these commands might be of use to you. In most normal production use-cases you probably don't need to use any of these, but for debugging, or pulling (part of) a production database for local testing, or testing a major upgrade with a snapshot of live data for example, these might come in handy.
Thank you.