COPY vs ADD in Dockerfile: Key Differences and When to Use Each
COPY copies files or directories from the build context into the image, while ADD does the same but also supports extracting local tar archives and fetching files from URLs. Use COPY for simple file transfers and ADD only when you need its extra features.Quick Comparison
Here is a quick side-by-side comparison of COPY and ADD instructions in Dockerfiles.
| Feature | COPY | ADD |
|---|---|---|
| Basic function | Copies files/directories from build context | Copies files/directories from build context |
| Supports URL sources | No | Yes, can fetch remote URLs |
| Extracts local archives | No | Yes, automatically extracts local tar files |
| Use case complexity | Simple and explicit | More complex with extra features |
| Recommended for | Most file copy needs | When archive extraction or URL fetch is needed |
| Caching behavior | Better caching predictability | Can cause unexpected cache invalidation |
Key Differences
The COPY instruction is straightforward: it copies files and folders from your local build context into the Docker image. It does not perform any extra processing. This makes it predictable and efficient for most use cases where you just want to add files.
On the other hand, ADD can do everything COPY does but adds two special features: it can fetch files from remote URLs and it can automatically extract compressed tar archives (like .tar, .tar.gz) when copying local files. This can be convenient but also introduces complexity and potential surprises.
Because ADD can fetch remote files, it can cause your build cache to invalidate more often if the remote content changes. Also, automatic extraction might not always be desired. For these reasons, Docker best practices recommend using COPY unless you specifically need ADD's extra features.
COPY Example
FROM alpine:3.18 WORKDIR /app COPY hello.txt /app/hello.txt CMD ["cat", "/app/hello.txt"]
ADD Equivalent
FROM alpine:3.18 WORKDIR /app ADD hello.txt /app/hello.txt CMD ["cat", "/app/hello.txt"]
When to Use Which
Choose COPY when you only need to copy files or directories from your local build context into the image. It is simple, clear, and has predictable caching behavior.
Choose ADD only if you need to automatically extract a local tar archive into the image or fetch files from a remote URL during build. Otherwise, avoid ADD to keep builds simple and reliable.
Key Takeaways
COPY is best for straightforward file copying from local context.ADD supports extra features like URL fetch and archive extraction but adds complexity.COPY by default for better caching and predictability.ADD only when you need its special features.COPY.