COPY vs. ADD in Dockerfile: What's the Difference?

If you've worked with Dockerfiles, you've probably come across the COPY and ADD instructions. They seem to do the same thing i.e. copy files into your Docker image. So, why are there two? And when should you use one over the other?

Let's break it down in the simplest way possible!


What is COPY?

The COPY instruction does exactly what it says: it copies files or directories from your local system into the image. That's it---nothing fancy!

Here's an example:

COPY myfile.txt /app/

  • Source: myfile.txt (in your local directory)

  • Destination: /app/ (inside the container)

Key Features:

  • Only works with local files and directories.

  • Doesn't do anything extra---just copies (simple).


What is ADD?

The ADD instruction is similar to COPY, but it's more powerful. It can do everything COPY does plus a few extra features.

Example:

ADD myfile.txt /app/

It looks the same as COPY, right? But here's what ADD can do that COPY cannot:

  1. Extract Archives:
    If you use ADD with a .tar, .gz, or .zip file, it automatically extracts the contents into the destination.

    ADD archive.tar.gz /app/

    This unpacks the archive into /app/.

  2. Remote URLs:
    ADD can download files from URLs directly into your image.

    ADD https://example.com/file.txt /app/

    This downloads file.txt from the internet.


When Should You Use COPY?

  • Use COPY when you just want to copy local files or directories into the image.

  • It's simpler and doesn't have unexpected behaviors like extracting archives.

  • Best Practice: Stick to COPY unless you specifically need ADD.


When Should You Use ADD?

  • Use ADD only if you need one of its extra features:

    1. Automatically extracting compressed files.

    2. Downloading files from a remote URL.
      (However, using tools like curl or wget in your Dockerfile is often more explicit and preferred over ADD for URLs.)


Summary of Differences

FeatureCOPYADD
Copy local files✅ Yes✅ Yes
Extract archives❌ No✅ Yes
Download from URL❌ No✅ Yes
Preferred for...Local file copying (simple)Archives or remote downloads

Best Practice Tip

Use COPY by default(mostly use this normally ).
Switch to ADD only if you specifically need to extract archives or download files from the internet.