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

 

In a Dockerfile, both the COPY and ADD commands are used to copy files and directories from your local system into a Docker image. However, they have some key differences in terms of their behavior:

  1. COPY Command:
    • COPY is a straightforward command used for copying files and directories from your local file system into the image.
    • It only performs a basic copy operation and doesn't attempt to extract or manipulate the content in any way.
    • COPY is recommended when you want to copy files or directories that don't require any special handling, such as code files or configuration files.

Here's an example of using the COPY command in a Dockerfile:

Dockerfile
# Use a base image FROM ubuntu:latest # Copy a file from the local system to the image COPY index.html /var/www/html/ # Copy a directory and its contents COPY src/ /app/src/

In this example, COPY is used to copy the index.html file into the /var/www/html/ directory and the src/ directory and its contents into the /app/src/ directory in the Docker image.

  1. ADD Command:
    • ADD is a more versatile command that can not only copy files and directories but can also extract compressed files and fetch remote URLs.
    • It has additional features like automatically unpacking compressed archives (e.g., .tar, .tar.gz, .zip) and fetching files from remote URLs and placing them in the image.
    • While ADD is more powerful, it's recommended to use COPY when you only need to copy local files into the image, as it's more explicit and easier to understand.

Here's an example of using the ADD command in a Dockerfile:

Dockerfile
# Use a base image FROM ubuntu:latest # Copy a file from the local system to the image (equivalent to COPY) ADD index.html /var/www/html/ # Fetch a file from a remote URL and place it in the image ADD https://example.com/myfile.txt /app/data/ # Extract a compressed archive (e.g., .tar.gz) into the image ADD myfiles.tar.gz /app/files/

In this example, ADD is used to copy the index.html file into the /var/www/html/ directory, fetch a file from a remote URL and place it in /app/data/, and extract the contents of myfiles.tar.gz into /app/files/.

While ADD can be powerful, it's recommended to use COPY when you only need basic file copying operations to make your Dockerfile more transparent and easier to maintain. Reserve ADD for cases where you specifically require its additional functionality.

Comments