PREP WITH PROOF
Menu
CYBERSECURITY / PRACTICAL GUIDE

Docker Build Secrets vs ARG: Keep Tokens Out of Images

Use BuildKit secret mounts instead of ARG, ENV or copied credentials. Review image layers, build context, cache rotation and a disposable dummy-secret fixture.

THE QUICK ANSWER

Use BuildKit secret mounts for credentials consumed during a build. ARG, ENV and copied files can expose credentials through metadata, settings or layers. A secret mount is temporary, but the command reading it can still leak the value into logs, files or artifacts.

A successful build can publish the wrong thing

A build downloads a private dependency using an API token. The application works, the image starts, and a scan of its final filesystem finds no token. That is useful evidence, but it does not prove that the credential stayed out of image metadata, earlier layers, intermediate artifacts or build logs.

Build secrets solve a narrower problem: supplying a credential to a build step without deliberately recording it as an image setting or ordinary copied file. Docker recommends secret mounts or SSH mounts for this purpose. ARG is a build parameter, not a secret store. ENV creates an environment setting in the image configuration and can also affect later build steps.

Choose the exposure boundary before writing the Dockerfile. A package installer needs access during one instruction; your runtime application may need a different credential supplied at deployment. Keeping those two needs separate reduces the number of artifacts that can carry the build credential.

ChannelSuitable useSecret concern
ARGPublic build options or revision identifiersValues can appear in build metadata, history or provenance
ENVNon-secret defaults needed by later instructions or the runtimeSetting is recorded in image configuration
COPYFiles intended to be part of a build filesystemCopied credential can enter a layer or another artifact
Secret mountA credential needed during one RUN instructionCommand can still copy, print or transmit its contents
Runtime secret injectionApplication credentials needed after deploymentSeparate lifecycle from build credentials

Source: Docker: build secret sources and mounts ↗

Pass the secret and consume it in the same step

There are two sides to a BuildKit secret mount: the build command supplies the source, and the Dockerfile requests the matching ID. With the default file target, id=repo_token is available at /run/secrets/repo_token during that RUN instruction. The mount is not automatically available to a later RUN or to the final container.

Keep the secret file outside the build context, or deliberately exclude it from the context. The --secret option can read a file on the build client without requiring COPY. Use required=true when a step cannot do useful work without the secret. If a matching step is served from cache, however, that step does not execute; a successful cached build is not proof that the credential still works.

In the example below, the command only verifies that a dummy secret is non-empty and writes a fixed public marker. It does not authenticate to a package service. For a real installer, use its supported credential-file mechanism and check whether it writes credentials into configuration, caches or logs. A secret mount cannot stop the program that reads it from persisting it elsewhere.

# syntax=docker/dockerfile:1
FROM alpine:3.21 AS build
RUN --mount=type=secret,id=repo_token,required=true \
    test -s /run/secrets/repo_token && \
    printf 'secret input was available\n' > /proof.txt

FROM scratch
COPY --from=build /proof.txt /proof.txt

Source: Dockerfile reference: RUN secret mounts, ownership and required option ↗

Exercise the mount with a disposable dummy value

Use a recent Docker installation with Buildx and BuildKit support. Create a fresh directory and save the preceding file there as Dockerfile. Run the Bash block below from that directory. It uses a dummy value, stores its source in a separate temporary directory, and exports only the final-stage filesystem. The output directory is outside the context as well.

The assertions are checks to run on your builder: proof.txt should contain the fixed marker, and the dummy secret should not appear as file content in the exported tree. This command sequence has been checked for shell syntax, but a Docker build was not executed for this guide. Run the checks in your own environment before adapting the pattern to a private dependency.

A passing content search is limited evidence. It examines the exported final filesystem for a literal value; it does not inspect every cache entry, encoded variant, remote log or metadata record. Use a unique disposable marker when testing a possible leak path so a diagnostic cannot itself disclose a real credential.

set -eu
fixture=$(mktemp -d)
trap 'rm -rf "$fixture"' EXIT
secret_file="$fixture/repo-token"
output="$fixture/output"
printf '%s' 'DUMMY_BUILD_SECRET_6b2f' > "$secret_file"

docker buildx build \
  --secret id=repo_token,src="$secret_file" \
  --output type=local,dest="$output" .

test "$(cat "$output/proof.txt")" = 'secret input was available'
python3 - "$output" <<'CHECK'
from pathlib import Path
import sys
marker = b"DUMMY_BUILD_SECRET_6b2f"
files = [p for p in Path(sys.argv[1]).rglob("*") if p.is_file()]
assert files, "No output files found"
assert all(marker not in p.read_bytes() for p in files)
print("Final exported files contain no literal dummy marker")
CHECK

Source: Docker: build secret sources and mounts ↗

Deleting a copied file later does not erase its old layer

A Dockerfile that copies a credential into the filesystem and deletes it in a later instruction can leave the earlier layer containing the file. The merged filesystem may hide it, while a recipient of the relevant image layers can still obtain the old content. Removing the path from a running container or a later layer does not rewrite the earlier layer.

Multi-stage builds let you select which artifacts reach the final image, which is useful for keeping compilers and temporary files out. They do not justify placing secrets in intermediate stages. Intermediate images, exported caches and logs may have different recipients or retention policies, and a broad COPY --from can copy credential-bearing output into the final stage.

For incident analysis, inspect the actual artifact that was shared, not just a freshly started container. For locally loaded test images, docker image inspect and docker history --no-trunc can help examine settings and build history. Image archives and layer inspection provide another view. Keep those diagnostics restricted: their output may contain the very data you are investigating. Absence from history alone is not proof that no file or artifact contains the value.

Source: Docker: build secret sources and mounts ↗

Keep private inputs out of ordinary build context paths

A secret can still enter the image through COPY . . even when one step also uses a secret mount correctly. Review the context directory and .dockerignore together. Exclude local credential files and avoid broad assumptions such as “the file is ignored by Git, therefore Docker cannot see it.” Git ignore rules and Docker context rules serve different tools.

Adapt the patterns below to the actual paths in your project. Do not exclude every configuration file blindly: the build may need non-secret configuration. If you use a Dockerfile-specific ignore file, review that file too; Docker documents its precedence over the root ignore file for the corresponding build. Inspect which context and Dockerfile CI actually selects.

Treat the builder as a recipient of the secret. A remote BuildKit builder runs instructions that can read it. Only send secrets to a builder and build definition you trust. In CI, keep credentials away from untrusted changes that can alter a Dockerfile or dependency script, and use narrowly scoped, short-lived credentials where the service supports them.

# Example .dockerignore entries; adapt to your project's paths.
.env
.env.*
secrets/
credentials/
.npmrc
.pypirc

Source: Docker: build contexts and .dockerignore ↗

Secret rotation and cache invalidation are separate events

Changing a secret value does not, by itself, invalidate the build cache. Secret IDs and mount paths participate in cache checks, but the secret contents are excluded. This protects the cache mechanism from treating the credential bytes like an ordinary build input, and it means rotation does not guarantee that an authentication step runs again.

When you need to test a replacement credential, force the relevant step to execute. A targeted --no-cache-filter build can invalidate the named build stage, or a deliberately changed non-secret build argument can participate in the cache decision. Never use the actual token as the cache-busting argument. Distinguish testing access from fetching a particular dependency version; a successful fresh authentication does not make an unpinned dependency reproducible.

The command below refers to the build stage named in this guide's Dockerfile. It tests the mount path with the dummy source again; it does not prove access to a real package repository. For that, the step must perform the intended authenticated operation and verify its expected artifact. Run it in the same prepared shell before its cleanup trap executes, or recreate the dummy secret and output paths first.

docker buildx build \
  --no-cache-filter build \
  --secret id=repo_token,src="$secret_file" \
  --output type=local,dest="$output" .

Source: Docker: secret contents and cache invalidation ↗

Debug the missing boundary without printing the value

If the step reports a missing secret, compare the CLI ID with the Dockerfile ID and check that the client-side source exists. Do not print the file contents to diagnose an ID mismatch. Check whether the Dockerfile uses the default path or a custom target. For a non-root build user, review the mount's ownership and mode options instead of copying the credential into a more permissive location.

If the build succeeds but a runtime command cannot find /run/secrets/repo_token, that is expected for a build-only mount. Supply any required runtime credential using the deployment platform's supported secret mechanism. Do not promote the build credential into ENV to make the error disappear.

If a credential appeared in a log, image, cache or artifact shared with an unintended recipient, treat it as exposed. Revoke or rotate it at its issuer and investigate the affected artifacts and recipients. Rebuilding a clean image does not invalidate a token copied from an old one. Remove retained exposed artifacts through the appropriate operational process and fix the input path that caused the leak before publishing another build.

Source: Docker: build secret sources and mounts ↗

Verify the intended artifact and its build path

Before release, review the context exclusions, secret ID mapping, command behavior and final COPY paths together. Exercise missing-secret and rotated-secret cases with a fresh execution of the relevant stage. Inspect final files and image settings with disposable markers, and check that the real installer does not persist credentials through a cache or generated configuration.

Keep the verification scope explicit. A secret mount is the right transport for a build-time credential, but its protection ends where the receiving command chooses to write or send that data. The release is ready when the required artifact is correct and the credential's journey is accounted for across the build, logs, caches and final output.

Source: Docker: build secret sources and mounts ↗

KEEP THESE THREE THINGS

Your next steps

  1. Pass the secret through the CLI and request its matching ID only in the step that needs it.
  2. Inspect build context, installer output, caches and logs in addition to the final filesystem.
  3. Force a relevant step to execute when testing rotated credentials; rotation alone does not invalidate its cache.

Sources & official resources

Linked resources checked on 2026-11-12. 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 →