1.4. Mounting a volume in a container
🤔 What happens to my data when I remove the container?
It’s deleted. Containers don’t store data permanently without a persistence layer, so let’s address that.
The MariaDB container is a good example for using a persistent volume. We’ll create a Docker-managed volume for persistent MariaDB data, then we start a new container with this volume:
docker volume create volume-mariadb
docker run --name mariadb-container-with-external-volume -v volume-mariadb:/var/lib/mysql -e MARIADB_ROOT_PASSWORD=my-secret-pw -d mariadb:12.0
Inspect your volume with:
docker volume inspect volume-mariadb
To add a new user to MariaDB, connect and run:
docker exec -it mariadb-container-with-external-volume mariadb -uroot -pmy-secret-pw
Inside MariaDB:
use mysql;
CREATE USER 'peter'@'%' IDENTIFIED BY 'venkman';
GRANT SELECT ON mysql.user TO 'peter'@'%';
Now quit MariaDB and the container:
exit
By using volumes, we have persisted the data in our database!
We can verify this by stopping our current container and starting a new instance.
Stop and remove the mariadb-container-with-external-volume container:
docker stop mariadb-container-with-external-volume
and then
docker rm mariadb-container-with-external-volume
Next, check if the data is still available. Create a new MariaDB container with the previous volume:
docker run --name mariadb-container-with-external-volume \
-v volume-mariadb:/var/lib/mysql \
-e MARIADB_ROOT_PASSWORD=my-secret-pw \
-d mariadb:12.0
The moment of truth… Connect to the database server using Peter’s credentials:
docker exec -it mariadb-container-with-external-volume mariadb -upeter -pvenkman
You should now be connected to your database instance as peter. You can test this by listing the users with the sql client:
SELECT User FROM mysql.user;
You should see peter in the list. You can exit the container now:
exit
Docker storage driver
When running a lot of Docker containers on a machine you usually need a lot of storage. Docker volumes and container storage are provided on a filesystem. The following link provides additional information on how to choose the correct storage setup:
At the moment, overlay2 is the recommended storage driver
.