Howto import a database into a Docker container
Congrats! you’re migrating your works/development environments into Docker containers. This is a new start for you as a system/devops engineer, as docker will solve many issues you faced before due to packages conflicts and package’s releases conflicts.
Here’s the issue I face and made my write the mini post, After I created my devops image and started a docker container from it, I needed to import a populated database into my container for my apps to work, I’ve a backup on my docker host and need away to import it into the container, So
How can I import a database backup into empty database in a docker container?
The answer is very simple by using
mysql command for MySQL database or
psql for PostgreSQL database, but How?
We have two options, I’ll list them here:
Hints: 1. In this post I'll use MySQL databases, for more details on Backup and restore MySQL/MariaDB database, check this post Backup and Restore MySQL/MariaDB Databases 2. If you are using PostgreSQL database instead, there are no big differences, only use
psqlcommand to restore the PostgreSQL database. 3. For more details on Backup and restore PostgreSQL database, check this post Backup and Restore PostgreSQL Databases
- Option 1: By using docker exec command on the docker host
This is the fastest and simplest option we’ve. A one line command will solve your issue. Just run the following command on you docker host:
$ docker exec -i <Container_ID or Container_Name > mysql -u[mysql_user] -p[mysql_user_password] [database] < [database_backup_file.sql]
In the above command, you should replace items between <> with your configuration. Here’s a simple example
$ docker exec -i db mysql -uroot -pexample wordpress < mydump.sql
Here’s some details:
- db –> The container name also you can use a container_id instead.
- root –> The database user.
- example –> The database user’s password.
- wordpress –> The database inside the container.
- mydump.sql –> The database dump file.
Now, let’s see option 2
- Option 2: By copying the database dump file into the container itself
Here’s we will copy the database’s dump file into the container using “
docker cp” command, then attach to the container, then from the container use “
mysql” command to restore our database’s dump file. The following commands explain this method:
First, copy the database into the container:
$ docker cp mydump.sql db:/root
Second, Connect to your container:
$ docker exec -it db /bin/bash
Finally, restore the database dump file into your database “After creating it first”:
# mysql -uroot -pexample wordpress < /root/mydump.sql
If You Appreciate What We Do Here On Mimastech, You Should Consider:
- Stay Connected to: Facebook | Twitter | Google+
- Support us via PayPal Donation
- Subscribe to our email newsletters.
- Tell other sysadmins / friends about Us - Share and Like our posts and services
We are thankful for your never ending support.