The goal of this tutorial is to understand how to create and use Docker Volumes. Docker Volumes offer a way to store data that originates from and is used by Docker containers, making it easier to manage data persistence and sharing data among multiple containers.
By the end of this tutorial, you will be able to:
Docker volumes are stored in a part of the host filesystem which is managed by Docker (/var/lib/docker/volumes/
on Linux). Unlike bind mounts, they are not dependent on the directory structure of the host machine.
To create a Docker volume, we use the docker volume create
command. To attach it to a container, we use the -v
option followed by the volume name when running docker run
.
docker volume create my_volume
This command creates a Docker volume named my_volume. You can verify this by running the docker volume ls
command, which lists all the Docker volumes.
docker run -d --name devtest -v my_volume:/app nginx:latest
This command runs a Docker container named devtest using the nginx:latest image, and attaches the my_volume to the /app directory in the container. The -d
option runs the container in the background.
# Create a Docker volume
docker volume create my_volume
# List Docker volumes
docker volume ls
This code snippet first creates a Docker volume named my_volume, then lists all Docker volumes. You should see my_volume in the output.
# Run a container with a volume attached
docker run -d --name devtest -v my_volume:/app nginx:latest
This command runs a Docker container named devtest using the nginx:latest image, and attaches the my_volume to the /app directory in the container. You should see the container running in the output of docker ps
.
This tutorial covered how to create and use Docker volumes. We learned how to create a Docker volume using docker volume create
, and how to attach it to a container using the -v
option in docker run
.
For further learning, you can explore how to share Docker volumes between containers, and how to backup, restore, or migrate data volumes.
Exercise 1: Create a Docker volume named "vol1" and list all Docker volumes to verify its creation.
Exercise 2: Run a container named "my_container" using the alpine image, and attach "vol1" to the /data directory in the container. Verify by running docker ps
.
# Create a Docker volume
docker volume create vol1
# List Docker volumes
docker volume ls
# Run a container with a volume attached
docker run -d --name my_container -v vol1:/data alpine