What is the difference between the ‘COPY’ and ‘ADD’ commands in a Dockerfile?

When building Docker images, you’ll often need to include files from your host system into your image. Two Dockerfile instructions can handle this: COPY and ADD.

While they may seem interchangeable, there are important differences between them. Knowing when to use which can help you write clearer, more maintainable, and more secure Dockerfiles.


🔄 COPY – Simple and Straightforward

COPY is the preferred command when you simply want to copy files or directories from your build context (the local directory) into the Docker image.

Syntax:

COPY <src> <dest>

Example:

COPY ./app /usr/src/app

This will copy everything inside the ./app folder into /usr/src/app inside the image.

Key Features:

  • Only copies files and directories
  • Does not support URLs or unpack archives
  • Easier to read and reason about

ADD – More Powerful but Less Predictable

ADD does everything COPY does, plus more.

Syntax:

ADD <src> <dest>

Additional Features:

  • Automatically extracts local .tar, .tar.gz, .tar.bz2, .tar.xz archives
  • Can fetch files from remote URLs

Example 1: Auto-extracting archive

ADD archive.tar.gz /usr/src/app/

The contents of archive.tar.gz will be extracted into /usr/src/app.

Example 2: Adding a remote file

ADD https://example.com/config.json /app/config.json

This downloads the file from the internet and adds it to your image.

⚠️ Note: Docker doesn’t cache external URLs well, which may lead to inconsistent builds.


🚫 Why Prefer COPY Over ADD?

According to Docker’s official best practices, you should prefer COPY unless you need the extra features ADD provides.

Why?

  • COPY is explicit, making Dockerfiles easier to read
  • ADD has side effects (like archive extraction), which can lead to unexpected behavior
  • Security-conscious builds benefit from predictability

✅ When to Use Which?

Use CaseRecommended Command
Copying files and foldersCOPY
Extracting local .tar archivesADD
Fetching files from a remote URLADD (use with caution)

🧠 Summary

  • Use COPY when you just need to move files from your context into the image.
  • Use ADDonly if you need to:
    • Automatically extract a local tar archive, or
    • Download a file from a URL during the build.

By defaulting to COPY, your Dockerfiles will be clearer, more secure, and less error-prone.

Sharing Is Caring:

Leave a Comment