1.5. Working with volumes
🤔 I have a container with a database server running. What happens to my data when I remove the container?
It’s gone. The docker instance has no persistence layer to store data permanently, let us address that problem in this chapter.
Mounting a volume in a container
The MariaDB container is a good example for using a persistent volume. We’ll create a Docker-managed volume for persistent MariaDB data:
docker volume create volume-mariadb
Inspect your volume with:
docker volume inspect volume-mariadb
Now we create a new container named mariadb-container-with-external-volume
and we mount the volume in it using the -v
parameter.
docker run --name mariadb-container-with-external-volume -v volume-mariadb:/var/lib/mysql -e MARIADB_ROOT_PASSWORD=my-secret-pw -d mariadb
We test our newly gained permanent storage by adding a user to the database. First, let’t connect to the database or our new container instance:
docker exec -it mariadb-container-with-external-volume mariadb -uroot -pmy-secret-pw
Inside MariaDB run a sql statement adding the user:
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-existing-external-volume \
-v volume-mariadb:/var/lib/mysql \
-e MARIADB_ROOT_PASSWORD=my-secret-pw \
-d mariadb
The moment of truth… Connect to the database server using Peter’s credentials:
docker exec -it mariadb-container-with-existing-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
.