If you spin a MySQL Docker container, you’ll notice that once the container is stopped, all the information is lost! In order not to lose any information from your MySQL Docker database, a volume will need to be attached to the container. Let’s do that!
Let’s create a new volume – this will be used to store all your database informaton
docker volume create mysql
Once the volume is created, it can be attached to a newly spun MySQL container
docker run --name mysql -e MYSQL_ROOT_PASSWORD=albert --mount source=mysql,target=/var/lib/mysql -d mysql
Any datatabses created on this MySQL instance is now preserved! Let’s test it out. Let’s connect to the container and create a new database:
docker exec -it mysql mysql -uroot -p
Supply your password (in this example, the password would be the value that we’ve supplied for the MYSQL_ROOT_PASSWORD – albert
Once you’re connected, let’s see the current databases. The default installation will have 4 default databases
SHOW DATABASES;
+--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | +--------------------+
Let’s go ahead and create a new database!
CREATE DATABASE test;
If you get all the databases now, you should get the following
SHOW DATABASES;
+--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | test | +--------------------+
De-attach from MySQL – type exit. Let’s now remove the current container and re-create a new container; re-attach the previously created volume.
docker container rm mysql -f docker run --name mysql -e MYSQL_ROOT_PASSWORD=albert --mount source=mysql,target=/var/lib/mysql -d mysql
Let’s re-attach and get the list of databases (don’t forget to supply the password):
docker exec -it mysql mysql -uroot -p SHOW DATABASES;
The output should now read as follows – the database test still exists, even after deleting and re-creating the container
+--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | test | +--------------------+