Overview

In this post, we will review how to instruct Docker to persist data. You can find the official documentation at https://docs.docker.com/storage/volumes/.

Introduction to volumes

When deleting a Docker container, all the data is lost. This is true even if the container is running a data base server like MySQL. Certainly, this is not always desirable. We need therefore to instruct Docker to persist the data for us.

The way to do so, is to instruct Docker to persist the data outside the, possibly, ephemeral container. Let's see how we can do this.

One way is to navigate to /var/lib/docker/volumes/ (you may need root privileges to do so) and execute

docker volume create your_volume_name

Let's run a container from image image_name that maps to this volume

docker  run -itd -v your_volume_name:/www image_name

We can also specify the volume locations to be used in our docker-compose file using the volumes key.

Bind volumes

If we follow the procedure above, the data persistence will be in the /var/lib/docker/volumes/ directory on the Docker host. This is not what we always want. Docker allows us to specify the mount point of the volume we want to use.

docker  run -itd -v your_dedicated_mount_point_name:/www image_name

We can also use the following command

docker  run -itd --mount type=bind, source=your_dedicated_mount_point_name, target=/www image_name

References