This tutorial aims to guide you through the process of mounting Docker Volumes in containers for persistent storage. By the end of this tutorial, you will gain a firm understanding of Docker Volumes, how they can be used to implement persistent storage, and how to mount these volumes in Docker containers.
Prerequisites:
- Basic understanding of Docker and Docker containers
- Docker installed on your machine
Docker Volumes are the preferred mechanism for persisting data generated by and used by Docker containers. While bind mounts are dependent on the directory structure of the host machine, volumes are completely managed by Docker.
To mount a volume, we can use the -v
or --mount
flag when starting a container. Let's start a new container and mount a volume named myvol2
:
Example:
docker run -d \
--name devtest \
--mount source=myvol2,target=/app \
nginx:latest
In this command, --mount source=myvol2,target=/app
tells Docker to bind the volume myvol2
to /app
inside the container.
Example 1: Creating a new Docker volume
docker volume create myvol
This command creates a new volume named myvol
. The volume will be created in the docker volume directory.
Example 2: Listing Docker volumes
docker volume ls
This command lists all the Docker volumes in your system.
Example 3: Mounting a Docker volume
docker run -d \
--name mycontainer \
--mount source=myvol,target=/app \
nginx:latest
This command starts a new container named mycontainer
and mounts the volume myvol
to /app
inside the container.
Expected output
<container_id>
The output will be the ID of the newly created container.
In this tutorial, we learned what Docker Volumes are, how to create a Docker Volume, and how to mount these volumes into Docker containers for persistent storage. You can further your understanding by exploring different aspects of Docker Volumes, such as volume drivers and backing up Docker Volumes.
Additional Resources:
- Docker Volumes Documentation
Exercise 1:
Create a Docker Volume named "testvol" and list all the volumes to verify its creation.
Solution:
docker volume create testvol
docker volume ls
Exercise 2:
Create a new Docker container named "testcontainer" and mount the volume "testvol" to the path "/data" inside the container.
Solution:
docker run -d \
--name testcontainer \
--mount source=testvol,target=/data \
nginx:latest
Exercise 3:
Inspect the "testvol" volume to find its mount point.
Solution:
docker volume inspect testvol
This command gives you detailed information about the volume, including its mount point.
Keep practicing with different volume and container names, and try mounting multiple volumes to a container.