COPY and ADD directives in a Dockerfile, highlight their differences, and share best practices for keeping your images predictable and lean.
Why It Matters
BothCOPY and ADD bring files and directories from your build context into the container’s filesystem. However, ADD has two extra behaviors that can be surprising:
- Automatic extraction of local archives
- Remote URL download at build time
Feature Comparison
| Directive | Copies Local Files/Dirs | Extracts Local Archives | Downloads Remote URLs |
|---|---|---|---|
COPY | ✔️ | ❌ | ❌ |
ADD | ✔️ | ✔️ | ✔️ |
Overusing
ADD can introduce unexpected files or extra layers. If you only need to transfer files, prefer COPY.Simple Usage Examples
1. Using COPY
A straightforward copy oftestdir from your context into the image:
2. Using ADD for a Local Directory
Functionally identical toCOPY when the source is a directory:
3. ADD to Extract a Local Archive
Automatically unpackapp.tar.xz into /testdir:
Consolidating Steps with RUN
MultipleRUN instructions add layers. Combine download, extraction, build, and cleanup in one RUN to keep images small:
When You Need ADD for Remote Files
If you preferADD to fetch a URL, then extract manually:
For clarity and layer reduction, consider using a single
RUN with curl and tar instead of ADD.Best Practices
- Use
COPYfor straightforward file and directory transfers. - Reserve
ADDfor:- Local archive auto-extraction (
.tar,.tar.gz, etc.). - Quick remote downloads without further processing.
- Local archive auto-extraction (
- Combine commands in a single
RUNto minimize image layers and overall size.