Docker volumes: What is a volume?
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.
What problem do volumes solve?
1. Volumes let you persist data to an external storage
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.
(Not sure about how the data is persisted) 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 automatically created on a directory on the host file system. Now, when you restart a container, the container will use the data on the host filesystem when booting up its own virtual filesystem.
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 container directory
docker run -v <container-directory> docker run -v /var/lib/mysql/data
Docker will automatically create a volume under
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.
- List all Docker volume commands with
docker volume --help