Before you begin
In this tutorial will learn how to use and the difference between
COPY Docker build commands. A GNU Linux/Mac OS machine and Docker will be required to follow this tutorial.
Common ADD and COPY capability
These commands allow you to copy files from your host directly to your Docker images. Example:
# Dockerfile COPY script_copy.sh /tmp ADD script_add.sh /tmp
Previous commands are copying script_copy.sh and script_add.sh to the /tmp directory on the Docker image:
$ docker run -it testing_add_copy ls -la /tmp > total 12 drwxrwxrwt 2 root root 4096 Oct 3 09:53 . drwxr-xr-x 35 root root 4096 Oct 3 09:53 .. -rwxrwxr-x 1 root root 415 Oct 3 09:53 script_copy.sh -rwxrwxr-x 1 root root 415 Oct 3 09:53 script_add.sh
If you need to copy files from your host to a container rather than to an image you can read the following post: How to copy files to or from a Docker container.
Docker ADD vs COPY
Basically Docker ADD command has two extra capabilities:
- Automatic TAR extraction.
# Dockerfile ADD scripts.tar.gz /tmp
tar file will only be unpacked if its compression is a recognized compression format (identity, gzip, bzip2 or xz).
- Fetch files from remote URLs.
# Dockerfile ADD http://www.example.com/script.sh /tmp
Docker COPY vs ADD
Following Best practices for writing Dockerfiles we should use ADD only when TAR extraction capability is needed otherwise is better to use COPY for the following reasons:
- Wording is more clear.
- TAR extraction and remote URL support sometimes are not obvious.
- Fetching files and delete them needs an extra layer. To prevent that is recommended to use GNU Wget or CURL instead.
- Having said all that, COPY is simpler than ADD resulting in a more controlled behaviour.
Finally, make sure to use a .dockerignore file to define a better build context.