2

I'm confused with what is different between creating docker volume create my-vol and VOLUME ["/var/www"].

My understanding is:

1) docker volume create my-vol creates a persistent volume on our machine and each container could be linked to my-vol.

2) VOLUME ["/var/www"] creates a volume inside its container.

And when I create another container, I could link my-vol as follows: when running a container

$ docker run -d --name devtest --mount source=myvol2,target=/app nginx:latest

At that time, if I added VOLUME ["/var/www"] in my Dockerfile, all data of this docker file will be stored in both myvol2 and /var/www?

ErikMD
  • 13,377
  • 3
  • 35
  • 71
PPShein
  • 13,309
  • 42
  • 142
  • 227

2 Answers2

4

The Dockerfile VOLUME command says two things:

  1. If the operator doesn't explicitly mount a volume on the specific container directory, create an anonymous one there anyways.

  2. No Dockerfile step will ever be able to make further changes to that directory tree.

As an operator, you can mount a volume (either a named volume or a host directory) into a container with the docker run -v option. You can mount it over any directory in the container, regardless of whether or not there was a VOLUME declared for it in the Dockerfile.

(Since you can use docker run -v regardless of whether or not you declare a VOLUME, and it has confusing side effects, I would generally avoid declaring VOLUME in Dockerfiles.)

Just like in ordinary Linux, only one thing can be (usefully) mounted on any given directory. With the setup you describe, data will be stored in the myvol2 you create and mount, and it will be visible in /var/www in the container, but the data will only actually be stored in one place. If you deleted and recreated the container without the volume mount the data would not be there any more.

David Maze
  • 130,717
  • 29
  • 175
  • 215
0

There are two types of persistent storage used in Docker,the first one is Docker Volumes and the second one is bind mounts. The differebce between them is that volumes are internal to Docker and stored in the Docker store (which is usually all under /var/lib/docker) and bind mounts use a physical location on your machine to store persistent data.

If you want to use a Docker Volume for nginx:

docker volume create nginx-vol

docker run -d --name devtest -v nginx-vol:/usr/share/nginx/html nginx

If you want to use a bind mount:

docker run -d --name devtest -v [path]:/usr/share/nginx/html nginx

[path] is the location in which you want to store the container's data.

  • kinda useful, but please describe more detail related to my question next time, then so your answer will be correct one. Thanks much. – PPShein Dec 23 '18 at 12:33
  • 1
    Actually it was my first day and answer on stackoverflow, i'll make sure to put more efforts on answers next time, always welcome. – Seifeddine Barhoumi Dec 23 '18 at 16:25