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!