What is the purpose of VOLUME in Dockerfile

后端 未结 2 2010
旧巷少年郎
旧巷少年郎 2020-12-04 07:57

I\'m trying to go deeper in my understanding of Docker\'s volume, and I\'m having an hard time to figure out the differences / use-case of:

  • The docker
相关标签:
2条回答
  • 2020-12-04 08:47

    VOLUME instruction becomes interesting when you combine it with volumes-from runtime parameter.

    Given the following Dockerfile:

    FROM busybox
    VOLUME /myvolume
    

    Build an image with:

    docker build -t my-bb .
    

    And spin up a container with:

    docker run --rm -it --name my-first-bb my-bb
    

    The first thing to notice is you will have a folder in this image named myvolume. But it is not particularly interesting since when we exit the container the volume will be removed as well.

    Create an empty file in this folder, so run the following in the container:

    cd myvolume
    touch hello.txt
    

    Now spin up a new container, but share the same volume with my-first-bb:

    docker run --rm -it --volumes-from my-first-bb --name my-second-bb my-bb
    

    You will see that my-second-bb contains the file hello.txt in myvolume folder.

    Once you exit both containers, your volume will be removed as well.

    0 讨论(0)
  • 2020-12-04 08:51

    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 deleted 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 reattached 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!
    
    0 讨论(0)
提交回复
热议问题