In Dockerfile, the COPY and ADD instructions are used to copy files from the build context to the image. While their functionalities are similar, there are key differences that make it more appropriate to choose one over the other depending on the scenario.
COPY Instruction
The COPY instruction is straightforward, with its basic form being:
dockerfileCOPY <source path> <destination path>
This instruction copies files from the <source path> in the build context to the <destination path> within the image filesystem. For example:
dockerfileCOPY ./hello.txt /app/hello.txt
This instruction copies the hello.txt file from the build context to /app/hello.txt in the image.
ADD Instruction
The ADD instruction is similar to COPY but provides additional features:
dockerfileADD <source path> <destination path>
In addition to copying files, ADD can:
- Automatically unpack archive files: If the source file is an archive (e.g., a
.tarfile),ADDwill automatically unpack it to the<destination path>. - Download files from URLs: If
<source path>is a URL,ADDcan download the content to the<destination path>.
For example:
dockerfileADD https://example.com/example.tar.gz /app/
This instruction downloads the example.tar.gz file from the specified URL and automatically unpacks it to the /app/ directory.
Choosing Between COPY and ADD
Although ADD provides additional features, Docker officially recommends using COPY as much as possible because its behavior is more direct and predictable. If you don't need the additional features of ADD (such as automatic unpacking or downloading from URLs), it's better to choose COPY to keep the Dockerfile concise and clear.
In summary, while both COPY and ADD can be used to copy files from the build context to the image, COPY is a simpler and recommended choice unless you need the special features of ADD. This choice helps improve the maintainability of Docker image builds.