The COPY and ADD commands in a Dockerfile both copy files from the host into a Docker image, but they differ in functionality and use cases:
1. COPY
- Purpose: Copies files/directories from the host machine into the image.
- Features:
- Simple file/directory copying.
- Preserves file permissions and metadata.
- Requires explicit extraction of compressed files (e.g.,
.tar,.zip). - Best For:
- Local files or directories.
- Transparent and predictable file transfers.
- Example:
COPY ./src /app/src
2. ADD
- Purpose: Copies files/directories and:
- Automatically extracts compressed archives (e.g.,
.tar,.gz,.zip). - Can fetch files from URLs (but avoids this for remote URLs—use
RUN curl/wgetinstead). - Features:
- Extra functionality beyond copying (extraction, URL support).
- Less predictable behavior (e.g., unintended extraction of archives).
- Best For:
- Local compressed archives needing extraction.
- Rare edge cases requiring URL downloads (not recommended).
- Example:
ADD ./data.tar.gz /app/data # Extracts the archive into /app/data
Key Differences
| Aspect | COPY | ADD |
|---|---|---|
| Extraction | ❌ No auto-extraction. | ✅ Extracts .tar, .gz, .zip archives. |
| URL Support | ❌ Only local files. | ✅ Can fetch from URLs (use with caution). |
| Transparency | ✅ Predictable. | ❌ May unintentionally extract archives. |
| Best Practice | ✅ Preferred for most use cases. | ❗ Use only for extraction or edge cases. |
When to Use Which
- Use
COPY: - For most file/directory copying (simpler and safer).
COPY ./config /app/config
- Use
ADD: - To extract a local compressed archive into the image.
ADD ./package.tar.gz /app
- Avoid using
ADDfor URLs—preferRUN curl/wgetfor better control:
RUN curl -O https://example.com/file.txt
Example Workflow
# Prefer COPY for local files
COPY requirements.txt /app/
# Use ADD to extract a local .tar.gz
ADD ./dependencies.tar.gz /app/
# Avoid ADD for URLs; use RUN + curl instead
RUN curl -SL https://example.com/data.zip -o /app/data.zip \
&& unzip /app/data.zip \
&& rm /app/data.zip
Summary
COPY: Simple, secure, and recommended for most cases.ADD: Use sparingly for archive extraction, but avoid for URLs.
Always default toCOPYunless you specifically needADD‘s extra features.