dockermountdocker-volumemounted-volumes

Files inside a docker image disappear when mounting a volume


Inside of docker image has several files in /tmp directory.

Example

/tmp # ls -al
total 4684
drwxrwxrwt    1 root     root          4096 May 19 07:09 .
drwxr-xr-x    1 root     root          4096 May 19 08:13 ..
-rw-r--r--    1 root     root        156396 Apr 24 07:12 6359688847463040695.jpg
-rw-r--r--    1 root     root        150856 Apr 24 06:46 63596888545973599910.jpg
-rw-r--r--    1 root     root        142208 Apr 24 07:07 63596888658550828124.jpg
-rw-r--r--    1 root     root        168716 Apr 24 07:12 63596888674472576435.jpg
-rw-r--r--    1 root     root        182211 Apr 24 06:51 63596888734768961426.jpg
-rw-r--r--    1 root     root        322126 Apr 24 06:47 6359692693565384673.jpg
-rw-r--r--    1 root     root          4819 Apr 24 06:50 635974329998579791105.png

When I type the command to run this image -> container.

sudo docker run -v /home/media/simple_dir2:/tmp -d simple_backup

Expected behavior is if I run ls -al /home/media/simple_dir2 then the files show up.

But actual behavior is nothing exists in /home/media/simple_dir2.

On the other hand, if I run the same image without the volume option such as:

sudo docker run -d simple_backup

And enter that container using:

sudo docker exec -it <simple_backup container id> /bin/sh

ls -al /tmp

Then the files exist.

TL;DR

I want to mount a volume (directory) on the host, and have it filled with the files which are inside of the docker image.

My env


Solution

  • From: https://docs.docker.com/storage/bind-mounts/

    Mount into a non-empty directory on the container If you bind-mount into a non-empty directory on the container, the directory’s existing contents are obscured by the bind mount. This can be beneficial, such as when you want to test a new version of your application without building a new image. However, it can also be surprising and this behavior differs from that of docker volumes.

    So, if host os's directory is empty, then container's directory will override is that right?

    Nope, it doesn't compare them for which one has files; it just overrides the directory inside the container with the directory on the host, no matter what.