sajad torkamani

TLDR: A volume is a directory inside Docker that can be used to store data that needs to persisted between container starts or between multiple containers.

In a nutshell

A volume is a directory inside Docker that’s used to store data that needs to be persisted between container starts or shared between multiple containers.

Where are the volumes stored?

Volumes are stored in the host filesystem under /var/lib/docker/volumes on Linux and are managed by Docker.

What problem do volumes solve?

1. Persist data & files even if the container is stopped or removed (e.g., file uploads or MySQL data)

Unlike host machines, containers use a virtual file system that’s ephemeral / non-persistent. This means that when you restart a container, any data it stored previously in its virtual file system is gone.

Volumes let you mount a folder in the host filesystem into the virtual file system of Docker so that any data created within a directory inside the container is also created on a directory on the host file system. This means that when you restart a container, the container will use the data on the host filesystem when booting up its own virtual filesystem.

2. Share data between multiple containers (e.g., between your Rails application and a Flask microservice)

If you have persistent data like a MySQL database, you often want to use this data in multiple containers (e.g., a REST API, some cron job service).

Three types of volumes

Host volumes: Specify which host directory is mounted where on the container

docker run -v <host-directory>:<container-directory>
docker run -v /home/sajad/db-data:/var/lib/mysql/data

Anonymous volumes: Specify only the container directory

docker run -v <container-directory>
docker run -v /var/lib/mysql/data

Docker will automatically create a volume under /var/lib/docker/volumes/<random-hash>/_data.

Named volumes: Specify a named volume and the container directory

docker run -v <name>:<container-directory>
docker run -v db-data:/var/lib/mysql/data

You let Docker manage the volume, but you can give it a name for easier reference.

Other notes

  • List all Docker volume commands with docker volume --help

Sources

Tagged: Docker