Docker RUN v ADD v COPY

December 7, 2024 note-to-self docker

I was wondering why we needed specific commands like COPY, instead of just RUN cp file1 file2. Research, and a colleague, says there are two reasons:

  1. Basically, COPY knows that it can only do that one thing, so it can check the file contents to see if it changed, and if it didn't, when rebuilding the image Docker can use the cached version. If you use RUN cp file1 file2 and file1 changed, Docker wouldn't know to re-run that command during the build and instead would just use the cached version of the layer because the actual text of that line/command didn't change. That would be unhelpful.

  2. COPY can bring files from outside the image, into the image. RUN cp file1 file2 couldn't do that, it could only copy files within the image.

Also: ADD is like COPY but extracts files with an extractable extension like .gz or .zip automatically. It also allows you to copy a file from a URL into the image.


As always: This is for my own understanding. Please don't assume it is 100% correct.