Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13797

docker volume and VOLUME inside Dockerfile

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?

Upvotes: 2

Views: 4428

Answers (2)

David Maze
David Maze

Reputation: 158848

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.

Upvotes: 4

Seifeddine Barhoumi
Seifeddine Barhoumi

Reputation: 9

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.

Upvotes: 0

Related Questions