Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between VOLUME and RUN mkdir in Dockerfile

Tags:

docker

After reading What is the purpose of VOLUME in Dockerfile , I'm still clueless on what is VOLUME?

My observation is that, adding the following in Dockerfile

VOLUME /my_directory1

is having same behavior as

RUN mkdir /my_directory2

When I docker exec -it xxxxxx sh, I observe 2 directories /my_directory1 and /my_directory2 are created.

I believe VOLUME are more meaningful than mkdir. Just that, I can't understand it after reading What is the purpose of VOLUME in Dockerfile

Can someone explain to me in simpler term, with some hands-on example? Thank you very much

like image 639
Cheok Yan Cheng Avatar asked Feb 05 '18 21:02

Cheok Yan Cheng


1 Answers

First thing is you could not be able to compare VOLUMES with the RUN command even in your scenario you are getting those as directories. So, when you use this command in Dockerfile, as,

VOLUME /my_directory1

This will become the location for your volume. And, the image your included will program in a way that it tells when you start a new container from it, to actually create a new volume location and assign it to this directory in the container. Which means any file that you put in there, in the container will outlive the container until we manually delete the volume. So, that is one difference that volumes need manual deletion. You can't clean them up just by removing the container. The whole point of volume command is to say that this data is particularly important, at-least much more important than the container itself.

You can verify that by inspecting the container under mounts.

"Mounts": [
        {
            ....
            "Source": "/var/lib/docker/volumes/bdc5772c2e1e0575d3e2125a15eb46fd7d1690d251568919f0a599a2c53a1044/_data",
            "Destination": "/my_directory1",
            ....
        }
]

This is actually the running container getting it's own unique location on the host, to store that data, and, then it's in background, mapped or mounted to that location in the container, so that location in the container thinks that it's writing at /my_directory1 location, but, it's actually living in the location on the host.

On the other hand, RUN command executes the instruction you specify inside the container and as each commands that create a new layer on top of image.

RUN mkdir /my_directory2

So, it creates the directory inside your container. But, if you delete the container, this directory also gets deleted as the ephemeral in nature.

Hope this clears the concept. Thank you.

like image 195
mohan08p Avatar answered Sep 24 '22 14:09

mohan08p