dockerdockerfiledocker-volume

What is the purpose of VOLUME in Dockerfile?


What are the differences and use-cases between:

Specifically, I don't understand what happens if you combine the VOLUME entry with the -v flag.


Solution

  • A volume is a persistent data stored in /var/lib/docker/volumes/...

    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"

    volumes

    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.