Difference Between ADD and COPY in Dockerfile

Ravindra Kumar
2 min readJan 12, 2025

--

The `ADD` and `COPY` commands in Dockerfiles are both used to copy files and directories into Docker images, but they have distinct differences in terms of functionality and use cases. Here’s a breakdown of the differences.

1. Basic Purpose

COPY

  • Simple and straightforward.
  • Used to copy files or directories from the source on the host system to the destination path in the image.
    Syntax:
COPY <source> <destination>

ADD

  • More versatile but slightly more complex.
  • In addition to copying files or directories, it supports extra functionalities like:
    - Extracting tar archives.
    - Fetching remote files via URL.

2. Handling Remote URLs

COPY

  • Does not support copying files from a URL. It only works with local files and directories.

ADD

  • Can download files from a URL directly into the image.
    - Example:
ADD https://example.com/file.tar.gz /path/in/container/

3. Extracting Archives

COPY

  • Does not handle extraction of compressed files. Files are copied as-is.

ADD

  • Automatically extracts files from `.tar` archives.
    - Example:
ADD file.tar.gz /path/in/container/

If `file.tar.gz` is a tar archive, Docker will extract its contents to `/path/in/container/`.

4. Best Practices and Recommendations

Use `COPY` whenever possible

Since `COPY` is simpler and does exactly what its name implies, it is preferred for copying files from the local build context into the image. It avoids the unintended side effects of `ADD` (like extracting archives or downloading files).

Use `ADD` only when necessary

If you need the specific features of `ADD`, such as downloading a file from a URL or extracting a tarball during the build, then `ADD` is appropriate.

5. Example Comparison

Using `COPY`:

COPY ./localfile /path/in/container/
COPY ./mydir/ /path/in/container/

Using `ADD` for tar extraction or remote file:

ADD ./localfile.tar.gz /path/in/container/ # Extracts the tar file
ADD https://example.com/script.sh /path/in/container/ # Downloads a script

Summary Table

When in doubt, follow the principle of least privilege and use `COPY` unless you specifically need the additional features of `ADD`.

--

--

Ravindra Kumar
Ravindra Kumar

Written by Ravindra Kumar

Hi, This is Ravi. I am Senior DevOps Engineer.. I love to write technical blogs.

No responses yet