How to Understand the Volume Instruction in Docker

How to Understand the Volume Instruction in Docker

In Docker, we can create separate images, containers, and volumes. Volumes can be mounted whenever we start a container.

If we can do it manually in Docker, we can automate it through a build process that uses a file called a Dockerfile.

This article will discuss building, creating, and mounting volumes via the Dockerfile in Docker.

Understanding the VOLUME Instruction in Docker

When working with a Dockerfile, we use multiple instructions to automate the build of a single or multiple containers. One example of these instructions is the VOLUME instruction.

In a Dockerfile, it should look something like this:

FROM ubuntu
RUN mkdir /samplevol
VOLUME /samplevol

However, there is some confusion when we try to input the value for the VOLUME instruction inside our Dockerfile. When using the VOLUME instruction, we need to understand that this is not where we indicate the location of our Docker volume outside of the container.

Instead, the VOLUME instruction is where we tell the destination where inside a container we will mount our external Docker volume when the container is already running.

If we can recall, when we run a container, we can use the --volume or -v parameter to mount a specific volume. However, there are other purposes for this parameter.

For example, with the --volume parameter, we can specify in which location we should mount the Docker volume.

Example Command:

docker run --volume=/volumesd:/samplevol sushi_bake

In the above command, the /volumesd directory is the location of the unmounted Docker volume. The /samplevol directory is where we will mount the Docker volume inside the created and running container.

Furthermore, the /samplevol directory is the right value for the VOLUME instruction inside our Dockerfile.

Alternatively, we can avoid the confusion by not adding a VOLUME instruction in our Dockerfile. If we did not add a mount point in our VOLUME instruction, Docker assigns a default location for the volume to be mounted.

The location is usually under /var/lib/docker/volumes.

Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn