Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 111 ยท Dockerfiles

COPY and ADD

Learn Dockerfile COPY and ADD in depth: destination paths, trailing slashes, --chown, --chmod, --from, archives and remote URLs, and why COPY is the better default.

An image is useless until your own files are inside it: the source code, the config, the compiled program. Two Dockerfile instructions put files there, COPY and ADD. They look almost identical, and for many years people used them interchangeably. Today the guidance is simple: use COPY unless you specifically need one of the extra powers of ADD.

In this lesson you will learn how paths are interpreted (including the trailing-slash rules that confuse everybody once), how to set the owner and permissions of copied files in the same layer, how COPY --from pulls files out of another stage or image, and what ADD adds: automatic archive extraction and remote URLs, with a checksum to keep it safe. Every example was built and inspected with the real tools.

COPY basics

DOCKERFILE
COPY <source>... <destination>

Sources are paths inside the build context, relative to its root. The destination is a path inside the image. If it is relative, it is relative to the current WORKDIR. Files that match your .dockerignore are not available to copy.

Let us use a small project to see exactly what each form does:

TEXT
site/
  index.html
  css/app.css
notes.txt
run.sh

Directories copy their contents

DOCKERFILE
FROM alpine:3.22
COPY site /one
COPY site/ /two/
COPY site/index.html /three
COPY site/index.html /four/
COPY site/index.html /five/new.html
CMD ["find", "/one", "/two", "/three", "/four", "/five", "-type", "f"]
CONSOLE
$ docker run --rm copydemo | sort
/five/new.html
/four/index.html
/one/css/app.css
/one/index.html
/three
/two/css/app.css
/two/index.html

Read the results line by line:

  • When the source is a directory, COPY copies its contents, not the directory itself. COPY site /one produced /one/index.html, not /one/site/index.html. The trailing slash on the source makes no difference.
  • When the source is a single file and the destination ends with a slash, the file is placed inside that directory with its own name: /four/index.html.
  • When the source is a single file and the destination has no trailing slash, Docker treats the destination as the new file name: COPY site/index.html /three created a file called /three, not a directory. This is the classic surprise. If you meant a directory, end the destination with /.
  • A destination with a different file name renames on the way in: /five/new.html.

Missing parent directories are created for you. That helps, and it hides a trap that we will meet below with --chmod.

Several sources and wildcards

You can list several sources, and the destination must then be a directory ending in /. Go-style wildcards work in the source:

DOCKERFILE
COPY package.json package-lock.json ./
COPY site/*.html /srv/pages/

Wildcards are expanded by the builder, not a shell, and they match against the context. If a source pattern matches nothing, the build fails (in our test with ERROR: lstat /site: no such file or directory). Anything in .dockerignore is treated as not existing.

Copying only what changed

Order your COPY lines from least to most frequently changed, because a changed source invalidates the cache for that step and every step after it. The standard example is dependency manifests first, then the rest of the code (the full technique is in The Build Cache):

DOCKERFILE
COPY package.json package-lock.json ./
RUN npm ci
COPY . .

Setting owner and permissions with --chown and --chmod

Files copied into an image belong to root by default. If your program runs as an unprivileged user (it should; see WORKDIR, USER, EXPOSE and LABEL), it often needs to own or at least read its files. The naive approach is COPY followed by RUN chown -R ..., which stores the files twice: once in the COPY layer and again, changed, in the chown layer. Use the flags instead, so ownership is set while copying, in one layer:

DOCKERFILE
FROM alpine:3.22
RUN adduser -D -u 1000 dev
WORKDIR /home/dev/app
COPY --chown=dev:dev site/ .
CONSOLE
$ docker run --rm chowndemo ls -ld /home/dev/app /home/dev/app/index.html
drwxr-sr-x    1 root     dev           4096 Oct 23 14:20 /home/dev/app
-rwxr-xr-x    1 dev      dev             12 Oct 23 14:20 /home/dev/app/index.html

The copied file belongs to dev:dev. The directory itself (/home/dev/app) was created earlier by WORKDIR, so --chown did not touch it. --chown accepts names (which must exist in the image's /etc/passwd), numeric IDs (--chown=1000:1000), and just a user (--chown=dev).

--chmod sets the file mode. It accepts octal numbers and, in recent BuildKit versions, symbolic modes too:

DOCKERFILE
COPY --chmod=755 run.sh /usr/local/bin/run.sh
COPY --chmod=a+x run.sh /bin/r1
COPY --chmod=u=rwx,go=rx run.sh /bin/r2
CONSOLE
$ docker run --rm chmoddemo ls -l /bin/r1 /bin/r2
-rwxr-xr-x    1 root     root             4 Oct 23 14:20 /bin/r1
-rwxr-xr-x    1 root     root             4 Oct 23 14:20 /bin/r2

This replaces the COPY then RUN chmod +x pair that older Dockerfiles use, and avoids an extra layer.

If you build on Windows, files from your folder arrive in the image with executable bits (-rwxr-xr-x), because Windows has no Unix permission bits for Docker to copy. Do not rely on the host's modes: set them explicitly with --chmod.

The --chmod trap: implicit directories

--chmod applies to every path that the instruction creates, including parent directories that COPY makes on the way. We copied one file with mode 640 into a directory that did not exist yet:

DOCKERFILE
COPY --chown=app:app --chmod=640 notes.txt ./private/notes.txt
CONSOLE
drw-r----- app app /srv/private
-rw-r----- app app /srv/private/notes.txt

The new directory /srv/private also received mode 640: no execute bit, so nobody can enter it, not even its owner. The fix is to create the directory first, so COPY only has to place the file:

DOCKERFILE
RUN mkdir -p /srv/x
COPY --chmod=0640 notes.txt /srv/x/
CONSOLE
drwxr-xr-x    1 root     root          4096 Oct 23 14:21 /srv/x
-rw-r-----    1 root     root             7 Oct 23 14:20 /srv/x/notes.txt

Now the directory keeps normal permissions and only the file is restricted. Whenever you use --chmod with a non-trivial mode, create the destination directory beforehand or use a destination that already exists.

COPY --from: files from another stage or image

COPY --from=<stage|image> takes its sources not from your build context but from another build stage or even another image. This is the engine behind multi-stage builds: compile in one stage, copy only the result into a small final stage.

DOCKERFILE
FROM alpine:3.22 AS tools
RUN echo '#!/bin/sh' > /hello && echo 'echo hello from the tools stage' >> /hello && chmod +x /hello

FROM alpine:3.22
COPY --from=tools /hello /usr/local/bin/hello
COPY --from=nginx:1.27-alpine /etc/nginx/nginx.conf /etc/nginx-copy.conf
CMD ["sh", "-c", "hello; head -3 /etc/nginx-copy.conf"]
CONSOLE
$ docker run --rm fromdemo
hello from the tools stage

user  nginx;
worker_processes  auto;

The first --from names an earlier stage (AS tools). The second names a published image, nginx:1.27-alpine: Docker pulls it during the build and copies one file out of it, without making it part of your image. This is handy for grabbing a single binary or config file from an official image. Pin the tag, as always.

ADD: the extra powers

ADD has the same syntax as COPY, plus two extra behaviours.

1. Local archives are extracted

If the source is a local tar archive (plain, gzip, bzip2 or xz), ADD unpacks it into the destination. COPY just copies the file as it is. We created bundle.tar.gz containing b.txt and inner/a.txt, and bundle.tar with the same content:

DOCKERFILE
ADD bundle.tar.gz /srv/unpacked/
COPY bundle.tar /srv/raw/bundle.tar
CONSOLE
/srv/unpacked/b.txt
/srv/unpacked/inner/a.txt
/srv/raw/bundle.tar

ADD created the extracted files; COPY kept the archive intact.

File ownership inside the archive is preserved. Our archive had been created on a Windows machine and carried the owner IDs of that machine, so the extracted files showed up as owned by the number 197609, a user that does not exist in the image. Compare three variants:

DOCKERFILE
ADD bundle.tar.gz /a/                       # archive made with the creator's own IDs
ADD bundle0.tar.gz /b/                      # archive made with --owner=0 --group=0
ADD --chown=app:app bundle0.tar.gz /c/      # force an owner at extraction time
CONSOLE
197609 197121 /a/b.txt
197609 197121 /a/inner/a.txt
root root /b/b.txt
root root /b/inner/a.txt
app app /c/b.txt
app app /c/inner/a.txt

If you create archives yourself, normalise ownership when packing (tar --owner=0 --group=0), or fix it with --chown as in the third line.

2. Remote URLs

ADD can download a file from an HTTP(S) URL:

DOCKERFILE
# illustrative example: the URL is a placeholder
ADD https://downloads.example.com/tool-1.4.2-linux-amd64.tar.gz /tmp/tool.tar.gz

We tested this against a small web server on our own machine. The downloaded file is created with mode 600, owned by root:

CONSOLE
$ docker run --rm --entrypoint ls urldemo -l /data/remote.txt
-rw-------    1 root     root            15 Oct 23 14:20 /data/remote.txt

Note that a remote tar archive is not extracted: we pointed ADD at a URL ending in .tar.gz and the image contained the archive file itself (/r/b.tar.gz). Unpacking it would need a separate RUN tar, which keeps the download inside the image. Prefer RUN curl ... | tar -x in one layer (with pipefail, see FROM and RUN) to avoid storing the archive.

If you do use ADD <url>, add --checksum so the build fails when the content is not what you expect. A wrong value fails like this (we used all zeros):

DOCKERFILE
ADD --checksum=sha256:0000000000000000000000000000000000000000000000000000000000000000 \
    http://host.example/remote.txt /data/remote.txt
CONSOLE
ERROR: failed to build: failed to solve: digest mismatch sha256:92e78d0b0329...: sha256:0000000000000000000000000000000000000000000000000000000000000000

The first digest in the message is what the server actually delivered. With a correct checksum, the build succeeds and the result is cached by the checksum: changing the file on the server later did not change a build that already had the right digest cached. That is good for reproducibility, and a reason to treat the checksum as your source of truth rather than the URL.

COPY or ADD?

The official guidance is to prefer COPY. The reasons are practical:

  • COPY is predictable. It does exactly what it says. ADD may unpack an archive you only wanted to copy, which is a nasty surprise when a file name ends in .tar.gz.
  • Remote ADD is hard to cache and verify. Without --checksum, a URL fetch gives you whatever the server sends today. Using curl or wget in a RUN, with an explicit checksum check, is equally easy and keeps everything visible in one layer.
  • Reviewers understand COPY at a glance.

Use ADD when you really want to extract a local tarball into the image (a root filesystem, a bundle of assets), or when you use ADD --checksum for a pinned download.

Need Use
Copy files or folders from the context COPY
Set owner or mode while copying COPY --chown --chmod
Take a file from another stage or image COPY --from
Unpack a local .tar.gz into the image ADD
Download a pinned file ADD --checksum or RUN curl with a verified checksum

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does COPY site/index.html /three create when /three does not exist?

    Without a trailing slash, a single-file destination is treated as the new file name. Write /three/ to place the file inside a directory.
  2. 2. Why is COPY --chown=app:app src/ . better than COPY src/ . followed by RUN chown -R app:app .?

    A chown in a separate RUN rewrites the files in a new layer, so their data is stored twice. The flag sets the owner as part of the copy.
  3. 3. A tar archive app.tar.gz is in your build context. What does COPY app.tar.gz /srv/ do, compared with ADD app.tar.gz /srv/?

    ADD auto-extracts local tar archives, while COPY always copies the file itself.
  4. 4. You copy one file with COPY --chmod=640 notes.txt ./private/notes.txt, and ./private does not exist. What can go wrong?

    The mode applies to the paths the instruction creates, including parent directories. Create the directory first with RUN mkdir and copy into it.
  5. 5. How do you copy a file from an earlier stage called builder into the final image?

    COPY --from=<stage or image> reads sources from that stage's filesystem instead of from the build context.

Summary

  • COPY src dest copies from the build context. A directory source copies its contents; a destination ending in / is a directory, otherwise it is the file name.
  • Use --chown and --chmod to set owner and mode in the same layer. --chmod also affects directories it creates, so create the target directory first.
  • COPY --from=<stage|image> takes files from an earlier stage or any image, the basis of multi-stage builds.
  • ADD additionally extracts local tar archives and can download URLs. Remote files are saved with mode 600 and are not extracted.
  • Always add --checksum=sha256:... to a remote ADD; a mismatch fails the build.
  • Prefer COPY by default; reach for ADD only for archive extraction or pinned downloads.
  • Order COPY lines so rarely changing files come first, to keep the build cache effective.

Next: CMD and ENTRYPOINT