I am learning Docker and I have doubts about when and where to use ADD
and VOLUME
. Here is what I think both of these do:
Copy fi
The fundamental difference between these two is that ADD
makes whatever you're adding, be it a folder or just a file actually part of your image. Anyone who uses the image you've built afterwards will have access to whatever you ADD
. This is true even if you afterwards remove it because Docker works in layers and the ADD
layer will still exist as part of the image. To be clear, you only ADD
something at build time and cannot ever ADD
at run-time.
A few examples of cases where you'd want to use ADD
:
ADD ./requirements.txt /requirements.txt
followed by RUN pip install -r /requirements.txt
You want to use your app code as context in your Dockerfile, for example, if you want to set your app directory as the working dir in your image and to have the default command in a container run from your image actually run your app, you can do:
ADD ./ /usr/local/git/my_app
WORKDIR /usr/local/git/my_app
CMD python ./main.py
Volume, on the other hand, just lets a container run from your image have access to some path on whatever local machine the container is being run on. You cannot use files from your VOLUME
directory in your Dockerfile. Anything in your volume directory will not be accessible at build-time but will be accessible at run-time.
A few examples of cases where you'd want to use VOLUME
:
/var/log/my_app
. You want those logs to be accessible on the host machine and not to be deleted when the container is removed. You can do this by creating a mount point at /var/log/my_app
by adding VOLUME /var/log/my_app
to your Dockerfile and then running your container with docker run -v /host/log/dir/my_app:/var/log/my_app some_repo/some_image:some_tag
VOLUME /etc/settings/my_app_settings
to your Dockerfile, run your container with docker run -v /host/settings/dir:/etc/settings/my_app_settings some_repo/some_image:some_tag
, and make sure the /host/settings/dir exists in all environments you expect your app to be run.