PREP WITH PROOF
Menu
DOCKER & CONTAINER BUILDS / PRACTICAL GUIDE

Docker COPY vs ADD: Tar Extraction, URLs, and Build Context

Choose Docker COPY or ADD for local files, tar extraction, and remote artifacts. Verify expected paths and exact bytes with a small Buildx lab.

THE QUICK ANSWER

Use COPY to transfer local files or build-stage artifacts without unpacking them. ADD can unpack a recognized local tar and fetch remote sources; remote HTTP tar files stay packaged by default. Decide which paths and bytes the image should contain, then verify the result.

Start with the file you expect to find in the image

A Dockerfile review changes COPY to ADD, and the application can no longer find the bundle it expects. The build can still succeed: one instruction stores the archive file, while the other can place the archive members into the image instead. The useful question is what exact paths and bytes the next build step or process should receive.

Use COPY as the default when the input already exists in your context or another build stage and should arrive as a file or directory tree. Choose ADD when you need its additional behavior and can name the reason in the Dockerfile review. A small exported filesystem makes the distinction visible without involving an entrypoint, a bind mount, or a running application.

This guide is about materializing build inputs. The related build-cache guide covers a different question: when a builder repeats a step. First prove that your instruction produces the right filesystem, then investigate how often it runs.

Predict the output for each kind of input

For a local gzip-compressed tar, COPY preserves the archive bytes. ADD normally extracts its members into the destination. Archive detection uses content, so a valid tar with a .blob name can expand, while an ordinary text file named .tar.gz remains a file. An extension is useful to people reviewing a repository; it is not an extraction policy.

When extracted files share a destination with existing files, think of extraction as adding to that tree. An unrelated file already there can survive, while an incoming member can replace a same-path file. Use a dedicated destination for unfamiliar packages. Review the member paths before overlaying a directory that already contains configuration, binaries or runtime state.

Remote HTTP inputs are a separate case: ADD ordinarily downloads a remote tar as a file. Current Dockerfile documentation also describes the explicit --unpack flag, which can request extraction for a remote tar or disable default local extraction. Check the frontend your builders actually use before relying on the flag; copying a local tar unchanged needs no such option.

InputInstructionExpected effect
Local archive needed at runtimeCOPYKeep archive bytes and filename
Local tar whose members are neededADDExtract into the destination by default
Artifact produced in a prior stageCOPY --from=stageTransfer selected files from that stage
Public HTTP archive needed as a fileADD with an independently verified checksumDownload and verify; keep the archive by default

Source: Dockerfile reference: ADD, COPY, checksum and unpack ↗

Create a tiny archive whose filename cannot explain the result

Run the next three blocks in the same shell with Python 3, tar and a working Docker Buildx builder. The first block creates a disposable directory and two inputs. One is a real gzip-compressed tar named payload.blob; the other is plain text named plain.tar.gz. The tar listing should show pkg/message.txt and pkg/settings.ini.

The output folder lives beside the context rather than inside it. This keeps a second build from accidentally sending the previous export as an input. The fixture contains only two small text members, and the archive records their intended relative paths directly. Real release archives may include a top-level version directory, symbolic links or additional metadata; inspect them before assuming the same layout.

lab=$(mktemp -d)
mkdir "$lab/context"
python3 - "$lab/context" <<'PYLAB'
import gzip
import io
import sys
import tarfile
from pathlib import Path

context = Path(sys.argv[1])
payload = {
    "pkg/message.txt": b"hello from the archive\n",
    "pkg/settings.ini": b"mode=demo\n",
}
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w", format=tarfile.USTAR_FORMAT) as tar:
    for name, data in payload.items():
        entry = tarfile.TarInfo(name)
        entry.size = len(data)
        entry.mode = 0o644
        tar.addfile(entry, io.BytesIO(data))
(context / "payload.blob").write_bytes(gzip.compress(buffer.getvalue(), mtime=0))
(context / "plain.tar.gz").write_bytes(b"this is ordinary text\n")
PYLAB
tar -tzf "$lab/context/payload.blob"
printf 'Lab directory: %s\n' "$lab"

Compare both instructions in one exported filesystem

The Dockerfile starts from scratch and has no RUN command. The local exporter writes the resulting filesystem to a directory, so there is no need to invent an executable for this image or start a container. Use a single target platform to keep the inspected paths directly under out.

The COPY into stored should leave one archive. The ADD into unpacked should produce the two archive members beside kept.txt, which was placed there earlier. The ADD into names should leave the misleadingly named text file unchanged. The experiment isolates instruction choice, source contents and destination paths.

The fixture generation, archive listing and output checker were exercised locally. The Buildx invocation is a reproduction step for a Docker-enabled environment; the exported paths described here are expected results based on Docker’s reference, not a claimed Docker run.

cat > "$lab/context/Dockerfile" <<'DOCKERFILE'
FROM scratch
COPY ["payload.blob", "/stored/"]
COPY ["plain.tar.gz", "/unpacked/kept.txt"]
ADD ["payload.blob", "/unpacked/"]
ADD ["plain.tar.gz", "/names/"]
DOCKERFILE

docker buildx build --platform linux/amd64 \
  --output "type=local,dest=$lab/out" "$lab/context"

Source: Docker Buildx local filesystem exporter ↗

Check names and bytes, including paths that should be absent

After a successful Buildx command, run this checker. It compares the exact set of exported file paths and checks the content of each. A passing exit means the archive was retained at the COPY destination, expanded at the ADD destination, and the sentinel and plain-text files survived.

A check that only searches for message.txt would miss an unwanted archive alongside the extracted files. A directory listing alone would miss an incorrect payload with the correct name. Combine both kinds of evidence when moving a build step between Dockerfiles or testing changes to your release package.

python3 - "$lab/context" "$lab/out" <<'PYLAB'
import sys
from pathlib import Path

context, output = map(Path, sys.argv[1:])
expected = {
    "stored/payload.blob": (context / "payload.blob").read_bytes(),
    "unpacked/pkg/message.txt": b"hello from the archive\n",
    "unpacked/pkg/settings.ini": b"mode=demo\n",
    "unpacked/kept.txt": b"this is ordinary text\n",
    "names/plain.tar.gz": b"this is ordinary text\n",
}
actual = {
    path.relative_to(output).as_posix()
    for path in output.rglob("*")
    if not path.is_dir() or path.is_symlink()
}
if actual != set(expected):
    raise SystemExit(f"unexpected paths: {sorted(actual ^ set(expected))}")
for name, data in expected.items():
    path = output / name
    if path.is_symlink() or not path.is_file() or path.read_bytes() != data:
        raise SystemExit(f"unexpected file or bytes: {name}")
print("PASS: five expected paths with exact bytes")
PYLAB

If the source cannot be found, inspect the context first

The local source is selected from the build context, not from the directory of a Dockerfile passed through -f. For example, docker buildx build -f deploy/Dockerfile . uses the final dot as its context. A file stored at deploy/payload.blob needs that context-relative path, unless you intentionally change the context.

Check the exact context and Dockerfile used in CI, then check the matching ignore rules. A Dockerfile-specific ignore file can take precedence over the root .dockerignore. If the archive is excluded, changing COPY to ADD does not recover it. If it is included, .dockerignore does not selectively remove members inside its compressed payload; review the archive itself.

Distinguish missing input from an unexpected output location. For a single ordinary file, a trailing slash makes the destination a directory path; without it the last component can name the resulting file. If an archive expands under pkg/ instead of placing files at the destination root, inspect its member names and change the packaging or the consumer’s path deliberately.

Source: Docker build context and ignore file rules ↗

Decide who fetches and verifies remote artifacts

For a public artifact retrieved directly by the builder, current Dockerfile syntax provides ADD --checksum for verifying a known digest. For an HTTP source, supply a SHA-256 digest from a trusted release channel, not a value computed after blindly accepting whatever the server returned. A matching checksum checks bytes; it does not establish that you chose the right publisher, release or CPU architecture.

When an artifact needs credentials, use an authenticated acquisition step with your supported build secret mechanism or prepare the verified input in CI. Do not put credentials in a URL, Dockerfile argument or committed context. Keep extraction, validation and placement explicit when you need to reject unwanted paths or inspect metadata before copying files into a final stage.

A versioned URL can be convenient, but pinning the expected content turns silent replacement into a verification failure. Plan how reviewers will update the URL and digest together. Record the artifact and expected file layout in the same change so later debugging starts from known inputs.

Source: Docker build secrets and secret mounts ↗

Separate packaging work from the final image layout

When the final image needs only one executable from a larger package, use a preparation stage with the tools needed to inspect or unpack it. Copy the selected output from that stage into the final image. This gives the final stage a simple input contract and keeps intermediate archives and preparation tools out of its filesystem.

Use an explicit source path for the transfer. For example, COPY --from=prepare /out/tool /usr/local/bin/tool reads from the root filesystem of the named stage. It does not look for out/tool in the local context or resolve the source against the preparation stage’s WORKDIR. If the file is missing, check the producing stage and its actual output path before editing the final stage.

An archive might contain optional examples, a nested directory or files for several platforms. Decide what to retain while preparing it, rather than adding everything to the final image and trying to remove unwanted files later. Keep the final path, permissions and architecture checks alongside the transfer. A successful COPY proves the source could be copied; it does not prove that the target environment can execute it.

Source: Dockerfile reference: ADD, COPY, checksum and unpack ↗

Review the filesystem contract before merging

For each build input, write down where it comes from, whether it should stay packaged, what it should create, and how its integrity is checked. A later stage that expects /stored/payload.blob and a program that expects /unpacked/pkg/message.txt are asking for different contracts. The correct instruction is the one that meets the consumer’s contract with the fewest implicit behaviors.

If files look right in an exported image but wrong in a running container, check mounts and runtime paths separately. A bind mount can obscure files already in the image. If the build input is correct but the deployed image is stale, follow the related guides on cache troubleshooting and image digests rather than changing a working COPY or ADD instruction.

The smallest useful regression check is an exact expected path plus a content assertion on the exported result. For a package expected to unpack, also check that the original archive is absent if retaining it would violate your image layout. That gives the next Dockerfile change a concrete acceptance criterion.

  • Expected archive missing? Check the instruction and actual input format; use COPY when the package itself is the deliverable.
  • Expected member missing? List the tar before building and check the prefix it records. Confirm the build used the intended context.
  • File present with incorrect bytes? Check whether a later instruction replaced it. Inspect an export of the stage where the discrepancy first appears.
  • Export correct but container wrong? Compare the running image reference, the target path and mounts before rebuilding.
KEEP THESE THREE THINGS

Your next steps

  1. Use COPY when a local archive should remain an archive; use ADD when local extraction is intentional.
  2. Check the context, ignore rules and archive member paths separately.
  3. Verify remote artifact bytes against a trusted digest and inspect the exported filesystem.

Sources & official resources

Linked resources checked on 2026-11-07. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →