Copying files in Docker is a pretty common tasks for any Docker user. However, when composing a Dockerfile, you might come across the
COPY commands both of which allow you to copy files from a source within the local fs into a Docker image.
Dockerfile Add vs Copy Commands
The following simply explains the difference between the
ADD and the
COPY command in in a Dockerfile allows you to copy new files or directories from
<src> to the filesystem of the container at the path specified in the
<dest> parameter. If the path provided in the
src parameter is a relative path, Docker will consider it as relative to the source of the context of the image build. Hence, no download or extraction is supported.
ADD command, on the other hand,, does what
COPY does but also provides the ability to:
- Download a file from a URL at the build time.
- Automatically extract a tarball at the destination.
To better understand how both of these commands work, let us look at some basic examples.
Example Copy Command Usage
The following shows a section of a Dockerfile using the
copy command to copy a file from source to destination.
COPY ./config.ini /config.ini
In this case, the Dockerfile will copy the local file
config.ini into the new image at location
Example Add Command Usage
Consider the example usage of the
ADD http://dl.geekbits.io/logs.tar.gz /opt/custom/logs
In this case, the Dockerfile will download
logs.tar.gz from the provided URL and it store it in
The command will also extract the tarball into that directory instead of storing it as an archive.
Point of Order
Although it may seem like the
add command is more favorable over the
copy command due to the added functionality, we recommend using the
copy command for file and directory operations. If you need to download or extract archive later in the Dockerfile, you can use other commands such as
RUN wget and
RUN tar as neccessary. This is because the more features of the
add command can lead to unexpected results or failure when downloading and extracting archives.
In this tutorial, we learned the main difference between the
COPY and the
ADD commands in the context of a Dockerfile. We also looked at examples of how we can use both commands and when one is more favorable over the other.