COPY and ADD
COPY puts files from the build context (the folder you pass to docker build) into the image. ADD does the same and adds two extra powers: it can fetch remote URLs and it automatically unpacks local tar archives. Prefer COPY unless you need one of those powers.
COPY requirements.txt /app/
COPY src/ /app/src/
COPY --chown=app:app config.yaml /etc/shop/config.yaml
COPY --chmod=755 entrypoint.sh /usr/local/bin/
COPY --from=build /out/server /usr/local/bin/server
ADD vendor-libs.tar.gz /opt/libs/
ADD https://example.com/releases/tool-1.4.2.tar.gz /tmp/tool.tar.gzHow destinations are resolved
The rules are the source of many surprises:
| Source | Destination | Result |
|---|---|---|
| a file | ends with / |
the file is placed inside that directory |
| a file | no trailing / |
the destination is the new file name |
| a directory | any | the directory's contents are copied, not the directory itself |
| several sources | must end with / |
all go into that directory |
| relative destination | relative to the current WORKDIR |
The model below applies these rules to a small build context:
import posixpath
context = {
"app.py": "...", "requirements.txt": "...",
"src/models.py": "...", "src/views.py": "...",
}
def copy(sources, dest, workdir="/"):
if not dest.startswith("/"):
is_dir = dest.endswith("/") or dest == "."
dest = posixpath.normpath(posixpath.join(workdir, dest)) + ("/" if is_dir else "")
if len(sources) > 1 and not dest.endswith("/"):
return ["error: when using COPY with more than one source file, the destination must be a directory and end with a /"]
results = []
for src in sources:
if src.endswith("/") or any(p.startswith(src + "/") for p in context):
folder = src.rstrip("/") + "/"
for path in sorted(p for p in context if p.startswith(folder)):
results.append(posixpath.join(dest, path[len(folder):]))
elif dest.endswith("/"):
results.append(posixpath.join(dest, posixpath.basename(src)))
else:
results.append(dest)
return results
print(copy(["app.py"], "/app/"))
print(copy(["app.py"], "/app/main.py"))
print(copy(["src"], "/app/"))
print(copy(["src"], "/app/src/"))
print(copy(["requirements.txt"], ".", workdir="/srv"))
print(copy(["app.py", "requirements.txt"], "/app"))['/app/app.py']
['/app/main.py']
['/app/models.py', '/app/views.py']
['/app/src/models.py', '/app/src/views.py']
['/srv/requirements.txt']
['error: when using COPY with more than one source file, the destination must be a directory and end with a /']
The third line is the classic surprise: COPY src /app/ puts models.py straight into /app, not into /app/src. To keep the folder, name it in the destination (COPY src/ /app/src/).
Ownership and permissions
Files copied with COPY are owned by root (UID 0) unless you say otherwise. If the container later runs as a non-root user that must write to those files, use --chown:
RUN useradd --create-home --uid 10001 app
COPY --chown=app:app . /home/app/site
USER app--chown inside the COPY is much better than a separate RUN chown -R app:app /home/app/site: the separate step duplicates every file into a new layer just to change its owner.
files_mb = {"static/": 60, "templates/": 5, "app/": 3}
copy_layer = sum(files_mb.values())
print("COPY then RUN chown -R:")
print(f" COPY layer {copy_layer} MB")
print(f" chown layer {copy_layer} MB (every file copied up again)")
print(f" total {copy_layer * 2} MB")
print("COPY --chown:")
print(f" total {copy_layer} MB")COPY then RUN chown -R:
COPY layer 68 MB
chown layer 68 MB (every file copied up again)
total 136 MB
COPY --chown:
total 68 MB
When ADD is the right tool
ADD has two behaviours COPY lacks:
- Local tar archives are extracted.
ADD rootfs.tar.gz /unpacks the archive into/. Handy, but surprising if you only wanted to copy the.tar.gzfile. - Remote sources.
ADD https://...downloads a file;ADD git@github.com:org/repo.git /srcclones a Git repository. Use--checksum=sha256:...with URLs so a changed download fails the build.
def add_behaviour(src):
archive = src.endswith((".tar", ".tar.gz", ".tgz", ".tar.xz", ".tar.bz2"))
if src.endswith(".git") or src.startswith("git@"):
return "clone the Git repository"
if src.startswith(("http://", "https://")):
return "download the file (archives from URLs are NOT extracted)"
if archive:
return "extract the archive into the destination"
return "plain copy (same as COPY)"
for src in ["config.yaml", "vendor.tar.gz", "https://example.com/tool.tar.gz",
"https://github.com/acme/tools.git", "notes.zip"]:
print(f"ADD {src:<36} -> {add_behaviour(src)}")ADD config.yaml -> plain copy (same as COPY)
ADD vendor.tar.gz -> extract the archive into the destination
ADD https://example.com/tool.tar.gz -> download the file (archives from URLs are NOT extracted)
ADD https://github.com/acme/tools.git -> clone the Git repository
ADD notes.zip -> plain copy (same as COPY)
Note the last line: .zip files are not extracted. Only tar formats are.
Tip: the rule of thumb from Docker's own best-practice guide: use
COPYfor local files. UseADDonly for tar auto-extraction or for remote sources with--checksum.
Copy what you need, in the right order
COPY . . copies the whole context. Two habits make it safe and fast:
- add a
.dockerignoreso.git,node_modules, secrets and build output are not copied (a later lesson); - copy dependency manifests (
requirements.txt,package.json) before the source code, so editing code does not invalidate the dependency-install layer (see Building & the Build Cache).
Test yourself
Given a context folder src/ containing a.py, where does COPY src /app/ put a.py?
- /app/src/a.py
- /app/a.py
- /src/a.py
- It fails
What does ADD vendor.tar.gz /opt/ do?
- Copies the archive file into /opt/
- Extracts the archive's contents into /opt/
- Downloads vendor.tar.gz from Docker Hub
- Fails, ADD needs a URL
Why is COPY --chown=app:app better than COPY followed by RUN chown -R app:app ...?
- It is faster to type
- The separate chown step duplicates all the files into another layer
- chown is not available in containers
- There is no difference