0
0
DockerComparisonBeginner · 3 min read

COPY vs ADD in Dockerfile: Key Differences and When to Use Each

In a Dockerfile, 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.

FeatureCOPYADD
Basic functionCopies files/directories from build contextCopies files/directories from build context
Supports URL sourcesNoYes, can fetch remote URLs
Extracts local archivesNoYes, automatically extracts local tar files
Use case complexitySimple and explicitMore complex with extra features
Recommended forMost file copy needsWhen archive extraction or URL fetch is needed
Caching behaviorBetter caching predictabilityCan 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

dockerfile
FROM alpine:3.18
WORKDIR /app
COPY hello.txt /app/hello.txt
CMD ["cat", "/app/hello.txt"]
Output
Hello from COPY!
↔️

ADD Equivalent

dockerfile
FROM alpine:3.18
WORKDIR /app
ADD hello.txt /app/hello.txt
CMD ["cat", "/app/hello.txt"]
Output
Hello from COPY!
🎯

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.
Use COPY by default for better caching and predictability.
Use ADD only when you need its special features.
Avoid unexpected cache invalidation by preferring COPY.