Dockerfile
FROM nginx:1.7
# Deliberately declaring VOLUME before RUN
VOLUME /var/tmp
RUN touch /var/tmp/test.txt
Observation
Now I believe I understand the implications of declaring the VOLUME
statement before
creating test.txt
- the volume /var/tmp
exposed at runtime will be based on the intermediary container prior to the test.txt
file is created so it will be empty (hope this observation is correct)
So as expected the following docker run
does not show test.txt
:
docker run kz/test-volume:0.1
But then I tried supplying the volume at runtime as below:
docker run -v /var/tmp kz/test-volume:0.1
Question
The outcome was the same. So what does this mean? does the -v /var/tmp
in the docker run command map to the empty /var/tmp
dir exposed by the VOLUME
command in the Dockerfile and not the /var/tmp
directory with the test.txt
in the latest image?
Feeling a tad bit confused.
There is no image which contains /var/tmp/test.txt
. The effect of declaring the volume before creating the file is that the RUN
instruction runs in a temporary container which has its own volume. Volumes bypass the Union File System so when the build saves that intermediate container, the contents of the volume are not saved, so they don't get persisted in the image layer.
Every container you create from that image will have its own volume, the -v
option doesn't change that, unless you use it to map the volume to a host path.
Using your Dockerfile, you can see that by inspecting two containers. The first without the -v
option:
> docker run -d temp
c3c4f7de411f166b3a67397ff1221552fe5b94c46bc100725a50a57231da427b
> docker inspect -f '{{ .Mounts }}' c3c
[
{67267d2eeb57373f76a9dd50c25f744b7d99d0a75647bf06aa0d17b70807cf71/var/lib/docker/volumes/67267d2eeb57373f76a9dd50c25f744b7d99d0a75647bf06aa0d17b70807cf71/_data /var/cache/nginx local true }
{91490ea73e3a9d42df9f00e32a91fe571d2143f54248071959765d5d55c23d46/var/lib/docker/volumes/91490ea73e3a9d42df9f00e32a91fe571d2143f54248071959765d5d55c23d46/_data /var/tmp local true }
]
Here there are two volumes, mounted from /var/lib/docker
on the host. One is from the nginx
base image, and one from your image. With the explicit -v
:
> docker run -d -v /var/tmp temp
6fa1a8713b2d6638675a3d048669943419bc7a3924ed98371771100bcfde3954
> docker inspect -f '{{ .Mounts }}' 6fa
[
{9adf6954ed3e826f23a914cbbd768753e6dec1f176eed10e03c2d5503287d101/var/lib/docker/volumes/9adf6954ed3e826f23a914cbbd768753e6dec1f176eed10e03c2d5503287d101/_data /var/cache/nginx local true }
{7dd8be71ce88017ffbeef249837bdd1c96c071b802a2f43b18fd406983e1076a/var/lib/docker/volumes/7dd8be71ce88017ffbeef249837bdd1c96c071b802a2f43b18fd406983e1076a/_data /var/tmp local true }
]
Same outcome, but different host paths, because each container has its own volume.
来源:https://stackoverflow.com/questions/39741636/does-docker-run-v-or-dockerfile-volume-take-precedence