Docker volume, what I learned

Fei Yao
2 min readFeb 23, 2018

--

For those who start working with docker volumes it could be confusing that sometimes container copies down the data to volume, while other times volume shadows container. I hope this article can address those for you.

  1. Create a volume before the creation of the container
$ docker volume create --name dv1$ docker volume ls
DRIVER VOLUME NAME
local dv1
$ docker run -dit --rm --mount type=volume,src=dv1,dst=/usr/share/nginx/html --name nginx nginx bash$ docker stop nginx

dv1 volume is independent of the life cycle of nginx container, so the content of dv1 can persist even if container died.

$ docker run -it --rm --mount type=volume,src=dv1,dst=/datavolume nginx ls /datavolume
50x.html index.html

2. Create a volume while creating the container

$ docker volume ls
DRIVER VOLUME NAME
local dv1
$ docker run -dit --rm --mount type=volume,src=dv2,dst=/usr/share/nginx/html --name nginx nginx bash$ docker volume ls
DRIVER VOLUME NAME
local dv1
local dv2
$ docker stop nginx$ docker volume ls
DRIVER VOLUME NAME
local dv1
local dv2
$ docker run -it --rm --mount type=volume,src=dv2,dst=/datavolume nginx ls /datavolume
50x.html index.html

So, there is no difference for an empty volume either preexisting or created with container. If there are files or directories in the container they will be copied into the volume.

What if preexisting volume has files or directories already, and how does it interact with container?

3. Create volume with existing data before the creation of the container

$ docker volume ls
DRIVER VOLUME NAME
local dv1
local dv2
local dv3
$ docker run -dit --rm --mount type=volume,src=dv3,dst=/usr/share/nginx/html --name nginx nginx bash$ docker attach nginxroot@d495a6baffab:/# ls /usr/share/nginx/html
404.html

As you can see the preexisting volume dv3 has 404.html file. When it mounts as volume on nginx container it complelely overshadows nginx files, aka. 50x.html and index.html.

So, if there are data in the volume it will shadow all the data in the container, instead of copying all the container’s data into the volume.

In conclusion, when you mount a volume into container:

if volume is empty, then
container will copy down it's data to the volume
else
volume data will shadow container directory

--

--