Skip to main content

MariaDB mySQL backup and restore in Docker

As soon as you use Docker to set up a MariaDB / mySQL database, you will notice that it becomes a bit more complicated to import an existing database here.
Since the containers are separate from your operating system, there is a trick to getting the functionality here.
On the one hand you can use the docker-compose.yml to share a path to the Docker container, then connect to the database container and import it with the mysql command. Or you can use the following one-liner to import/export your database.

Backup using mysqldump.

docker exec db_container_name mysqldump [--user username] [--password=password] database_name > /your/backup/path/db.sql

Note:
The mysqldump command works for MariaDB, as well as for mySQL databases, no matter which one you are using. This function is installed by default on the containers of MariaDB and mySQL.

Restore the database

docker exec -i db_container_name mysql [--user username] [--password=password] database_name < /your/backup/path/db.sql

Backup and restore in one command

If you ever come to the case where you want to export the database from one database container and import it into a new one, the following command will help you:

docker exec db_container_name mysqldump [--user username] [--password=password] database_name | docker exec -i second_db_container_name mysql [--user username] [--password=password] -C database_name

Cheers!

By submitting your data, you agree that all entered data may be saved and displayed as a comment.

🤖 Cookies

We use cookies to improve your experience. Find out more in our privacy page.