A volume is a persistent data stored in /var/lib/docker/volumes/...
You can either declare it in a Dockerfile, which means each time a container is started from the image, the volume is created (empty), even if you don't have any -v
option.
You can declare it on runtime docker run -v [host-dir:]container-dir
.
Combining the two (VOLUME
+ docker run -v
) means that you can mount the content of a host folder into your volume persisted by the container in /var/lib/docker/volumes/...
docker volume create creates a volume without having to define a Dockerfile and build an image and run a container. It is used to quickly allow other containers to mount said volume.
If you had persisted some content in a volume, but since then, deleted the container (which by default does not delete its associated volume, unless you are using docker rm -v), you can re-attach said volume to a new container (declaring the same volume).
See "Docker - How to access a volume not attached to a container?".
With docker volume create, this is easy to reattach a named volume to a container.
docker volume create --name aname
docker run -v aname:/apath --name acontainer
...
# modify data in /apath
...
docker rm acontainer
# let's mount aname volume again
docker run -v aname:/apath --name acontainer
ls /apath
# you find your data back!
Why volumes were introduced in the first place?
Docker volumes were introduced primarily to solve the challenge of data persistence and data sharing in containerized environments.
In the world of Docker, containers are ephemeral and lightweight, meaning they can be created, started, stopped, and destroyed with ease, and they are designed to be stateless.
However, applications often need to store data permanently, access configuration files, or share data between different containers or between containers and the host system. That is where Docker volumes come into play.
Volumes provide a mechanism to persist data generated by and used by Docker containers.
Unlike the container's writable layer, which is tightly coupled to the container's lifecycle and gets destroyed when the container is removed, volumes are managed by Docker and are designed to exist independently of containers.
That means data in volumes survives container restarts and can be securely shared among multiple containers. And volumes are platform-independent, which simplifies data migration and backup processes.
See "Docker Engine / Storage / Manage data in Docker"
Additionally, volumes address performance and security concerns. Since they are stored outside the container's filesystem, they offer improved I/O performance, especially important for database storage or heavy read/write operations. They also provide a safer way to handle sensitive data, as volumes can be more securely isolated from the core container filesystem.