Before you begin
In this tutorial will learn how to use and the difference between
COPY Docker build commands. A Linux 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 to your image. Example:
# Dockerfile COPY script.sh /tmp ADD script.sh /tmp
Previous commands are copying script.sh to the temp directory on the 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.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.
Differences between ADD and COPY
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
When to use COPY as a best practice
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
Finally, make sure to use a .dockerignore file to define a better build context.