乐闻世界logo
搜索文章和话题

What is the difference between COPY and ADD instructions in a Dockerfile?

1个答案

1

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:

dockerfile
COPY <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:

dockerfile
COPY ./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:

dockerfile
ADD <source path> <destination path>

In addition to copying files, ADD can:

  1. Automatically unpack archive files: If the source file is an archive (e.g., a .tar file), ADD will automatically unpack it to the <destination path>.
  2. Download files from URLs: If <source path> is a URL, ADD can download the content to the <destination path>.

For example:

dockerfile
ADD 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.

2024年7月19日 17:18 回复

你的答案