Skip to content
SumGuy's Ramblings
Go back

Dockerfile: Differences Between COPY and ADD

When building Docker images, the Dockerfile serves as a blueprint for constructing the image. It contains a set of instructions that Docker follows to build the image. Among these instructions, the COPY and ADD commands are often used to include files from the local file system into the Docker image. Although they seem similar, there are distinct differences in their functionality and use cases.

What is a Dockerfile?

Before diving into the specifics of COPY and ADD, it’s important to understand what a Dockerfile is. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using docker build users can create an automated build that executes several command-line instructions in succession.

The COPY Command

The COPY command in a Dockerfile copies new files or directories from a source and adds them to the filesystem of the container at the specified destination. It is straightforward and explicitly designed to copy local files.

Syntax:

COPY [--chown=<user>:<group>] <source>... <destination>

Example:

COPY ./app /usr/src/app

This line in a Dockerfile would copy the local directory ./app into the /usr/src/app directory inside the Docker container.

Key Points for COPY:

The ADD Command

The ADD command is more complex and powerful. It copies files and directories like COPY, but it also has the capability to handle URL sources and automatically extract compressed files.

Syntax:

ADD [--chown=<user>:<group>] <source>... <destination>

Example:

ADD https://example.com/example.tar.gz /var/www/html

This command would download the example.tar.gz file from the specified URL and extract it into /var/www/html inside the container.

Key Points for ADD:

When to Use COPY vs. ADD

Best Practices

Conclusion

Understanding the differences between COPY and ADD in Dockerfiles helps in making better decisions when writing Dockerfiles. While both commands have their place, choosing the right command based on the requirement can simplify Docker image creation and make your Dockerfiles more efficient and secure.


Share this post on:

Previous Post
Copying Files Between Docker Containers and Host Machines
Next Post
Docker Strategies for Load Balancing and Failover