The reliable way to keep tokens, keys and passwords out of container images is to never hand them to the build as files, build arguments or environment variables, and instead mount them only for the single BuildKit step that needs them. This guide shows how to do that with RUN --mount=type=secret, how to forward SSH agents for private Git access, how to authenticate remote build contexts, and how to check images and build settings so a secret cannot slip into a layer.
Finding and cleaning up secrets that are already in published images is a different job, covered in the Secrets in Container Images and Build Artefacts Guide and How to find hard-coded secrets in container images. This page is about prevention at source: the Dockerfile, the build command and the CI job that runs it.
Key takeaways
- Docker's documentation is explicit: build arguments and environment variables are unsuitable for secrets because they persist in the final image. Use secret mounts or SSH mounts instead.
- A secret mount exposes a value to one
RUNinstruction, as a file under/run/secrets/<id>by default or as an environment variable, and does not persist in the image or its metadata. - Set
required=trueon secret mounts so a build fails loudly when the secret is missing instead of producing a broken or unauthenticated image. - Use
--sshandRUN --mount=type=sshfor private Git dependencies, so the private key never enters the build container. - Turn on build checks with
# check=error=true. TheSecretsUsedInArgOrEnvcheck flags ARG and ENV keys that look like secrets. - The credentials used at build time are non-human identities. Prefer short-lived, narrowly scoped tokens issued to the CI job over long-lived personal tokens.
How secrets leak into images during a build
Every instruction in a Dockerfile can leave something behind. Understanding where values persist explains why the secret mount design exists.
| Pattern | Where the value ends up |
|---|---|
ARG NPM_TOKEN passed with --build-arg | Not in the final container environment, but Docker warns that build arguments can be visible in docker history and in max mode provenance attestations |
ENV API_KEY=... | Persisted in the image configuration, set in every running container and visible through docker inspect |
ENV --unset after use | Removed from the image configuration, but values set by earlier instructions remain in image history |
COPY .npmrc . then RUN rm .npmrc | The file is still present in the earlier layer, so anyone who pulls the image can extract it |
A RUN step that writes a token to a config file | Persisted in that step's layer unless the file is on a mount |
Secrets in the build context (for example .env, cloud credential files) | Sent to the builder and copied in by any broad COPY . . |
The common thread is that layers are immutable and additive. Deleting a file in a later step hides it from the running container but not from the image. A secret that is never written into a layer is the only safe secret, which is what BuildKit mounts provide.
Passing secrets to the build
Secret mounts need BuildKit, which is the default builder in current Docker releases and the engine behind docker buildx. Start Dockerfiles with the syntax directive so you get current Dockerfile features without upgrading the engine:
# syntax=docker/dockerfile:1
Docker's documentation says this causes BuildKit to pull the latest stable version of the Dockerfile syntax before the build.
On the client side, the --secret flag names a secret and its source, which can be either a file or an environment variable:
- From a file:
docker build --secret id=aws,src=$HOME/.aws/credentials . - From an environment variable:
docker build --secret id=kube,env=KUBECONFIG . - Explicit type: the type is detected automatically, but you can set
type=fileortype=env. If the source is an environment variable you can omitenv, and the secret is bound to a file named after the variable. - Bake: declare
secret = ["id=aws,src=${HOME}/.aws/credentials"]under a target.
In CI, prefer the environment variable source and populate it from the platform's secret store or, better, from a short-lived token minted for the job. That avoids writing a credentials file to the runner's disk at all.
Using secret mounts in the Dockerfile
Inside the Dockerfile, a RUN instruction requests the secret by id. The documented options are:
| Option | Purpose | Default |
|---|---|---|
id | Which secret to mount | Basename of the target path |
target (also dst, destination) | File path for the secret | /run/secrets/<id> if neither target nor env is set |
env | Expose the secret as an environment variable (Dockerfile v1.10.0 and later) | None |
required | Fail the instruction if the secret is not provided | false |
mode | Octal file mode | 0400 |
uid, gid | Owner of the secret file | 0 |
Typical patterns
- Tool that reads a file:
RUN --mount=type=secret,id=aws,target=/root/.aws/credentials,required=true aws s3 cp s3://bucket/artefact . - Tool that reads an environment variable:
RUN --mount=type=secret,id=aws-key-id,env=AWS_ACCESS_KEY_ID,required=true .... Docker's build check documentation gives this as the correct replacement forARG AWS_ACCESS_KEY_ID. - Package registry token: mount the token as a file, and point the package manager at it with a config that references the mounted path or an environment variable, so the token itself is never written into a config file inside a layer.
- Non-root builds: if the step runs as a non-root user, set
uidandgidso that user can read the file while keepingmode=0400.
target and env can be combined if a tool needs both. Keep the secret scoped to the one instruction that uses it. A secret mounted on a step that also runs unrelated scripts is exposed to everything those scripts pull in.
Rules that keep mounts safe
- Never
cat,echoor copy the mounted file into the image filesystem. That defeats the mount. - Do not write the secret into a generated config file outside the mount path. If a tool insists on a config file, point the config at the mounted secret path so the value itself is never written into the layer.
- Watch for tools that log credentials or embed them in lock files and metadata. Review the output of dependency installers for tokens in URLs.
- Avoid shell tracing (
set -x) in steps that use secrets, because build logs are often retained and widely readable in CI.
SSH forwarding for private repositories
When the credential is an SSH key or agent, commonly for cloning private Git repositories, use an SSH mount instead of copying a key into the build. Pass the agent socket from the client:
docker buildx build --ssh default .
and request it in the step that needs it:
RUN --mount=type=ssh,required=true git clone [email protected]:org/private-lib.git
The SSH mount options are:
| Option | Purpose | Default |
|---|---|---|
id | SSH agent socket or key to use | default |
target | Path of the agent socket in the container | /run/buildkit/ssh_agent.${N} |
required | Fail if the key is unavailable | false |
mode | Octal mode for the socket | 0600 |
uid, gid | Socket owner | 0 |
The private key stays in the agent on the client or runner. The build step can ask the agent to sign authentication challenges while the mount is active, but cannot read the key. Identity hygiene still matters:
- Use a dedicated deploy key or machine identity with read-only access to the specific repositories the build needs, not an engineer's personal key.
- Load only that key into the agent used for the build.
- Add known host keys for your Git server to the image or the step, rather than disabling host key checking.
- Prefer HTTPS with a short-lived token where your Git platform supports it, because tokens are easier to scope and expire than SSH keys.
Authenticating private build contexts and remote sources
When the build context itself is a private Git repository, or a Dockerfile uses ADD to fetch from one, BuildKit provides two predefined secrets for HTTP authentication: GIT_AUTH_TOKEN and GIT_AUTH_HEADER. Docker describes these as pre-flight secrets: the builder uses them to fetch the context, and they are not consumed inside a build instruction.
That means you can build from a private repository without putting a token in the URL, which would otherwise appear in shell history, CI logs and possibly provenance. Supply the token with --secret id=GIT_AUTH_TOKEN,env=GIT_AUTH_TOKEN using a token scoped to read the one repository.
For other remote downloads inside the build, use a secret mount on the RUN step that performs the download rather than embedding credentials in an ADD URL.
Layer and configuration checks
Prevention needs verification. Combine static checks on the Dockerfile with inspection of the built image.
Build checks
BuildKit build checks run automatically during a build. By default, violations are reported as warnings with exit code 0. To make them blocking, add the directive below the syntax line:
# syntax=docker/dockerfile:1# check=error=true
With that directive, the build stops after the checks run and before the build executes. You can also run docker build --check . to evaluate checks without building; it exits non-zero when violations are found. Docker documents support in Buildx 0.15.0 and later, docker/build-push-action 6.6.0 and later and docker/bake-action 5.6.0 and later, and in GitHub Actions the results appear in the pull request diff view.
The check most relevant here is SecretsUsedInArgOrEnv. It reports ENV and ARG keys that indicate sensitive data, with the message "Potentially sensitive data should not be used in the ARG or ENV commands." It is name-based, so treat it as a safety net, not a guarantee: a secret in a variable called CONFIG will pass.
Image inspection
- History: run
docker history --no-trunc <image>and look for build arguments, tokens in URLs or commands that write credential files. - Configuration: run
docker inspect <image>and reviewEnvand labels. - Layers: scan every layer, not just the final filesystem, with a secret scanner in the pipeline before push. The scanning approach is covered in the Secrets in Container Images and Build Artefacts Guide.
- Provenance: if you publish
maxmode provenance attestations, remember Docker notes that build arguments can appear there. Check that no secret was ever passed as an argument.
Context hygiene
Keep a .dockerignore that excludes .env files, cloud credential directories, SSH directories and package manager configs, and avoid COPY . . in final stages. Multi-stage builds help: do authenticated work in a builder stage using mounts, then copy only built artefacts into a minimal final stage. Note that multi-stage builds do not make ARG or COPY of secrets safe in the builder stage, because cached builder layers and history can still be exported or reused.
Running secret-safe builds in CI
The build secret is only as safe as the identity behind it. In CI:
- Mint short-lived credentials for the job. Use OIDC federation from your CI platform to the cloud or registry so the job receives a token valid for minutes, not a stored long-lived key. See the GitHub Actions OIDC Federation Hardening Guide and the CI/CD Pipeline Identity Security Guide.
- Scope tightly. A token used to download dependencies needs read on one package feed, not write on the organisation.
- Pass by environment, not by file. Use
--secret id=...,env=...so nothing is written to the runner disk. - Protect the builder. Remote or shared BuildKit builders see secrets during builds. Restrict who can use them and isolate builders per trust level. Self-hosted runner risks are covered in Self-hosted CI/CD Runners and Build Agents.
- Do not rely on cache mounts for secrets. Cache mounts are kept in the builder's local storage, are not exported with
--cache-toand should be used only for performance. Never put credential files in a cache mount, because they would be shared with later builds on that builder. - Mask logs. Make sure your CI platform masks the secret values and that build output is not published to public logs for public repositories.
Migrating existing Dockerfiles
- Find candidates. Run
docker build --checkacross repositories and grep Dockerfiles forARGandENVnames containing TOKEN, KEY, PASSWORD, SECRET or CREDENTIAL, and forCOPYof dotfiles. - Replace each with a mount. Change
ARG NPM_TOKENplus--build-argtoRUN --mount=type=secret,id=npm_token,env=NPM_TOKEN,required=trueon the install step, and update the build command. - Rotate the old secret. Any secret that was ever passed as an argument or copied into a layer must be treated as exposed in every image and cache built with it. Rotate it before or alongside the migration.
- Rebuild and republish. Rebuild affected images without cache, re-scan them and remove old tags from registries where possible.
- Enforce. Add
# check=error=trueand a layer secret scan as required CI steps so regressions fail.
Common failure patterns
- Build arguments for tokens.
--build-arg NPM_TOKEN=...survives in history and provenance. - Copy then delete. A credential file copied and removed in a later step remains in the earlier layer.
- Secret written to config inside the mount step. The mount is used correctly but the step writes the value into a persistent config file.
- Missing
required=true. The secret silently fails to mount, the build succeeds and an engineer "fixes" it by switching to a build argument. - Personal SSH keys forwarded. A developer's agent with access to every repository is forwarded into a build.
- Tokens in context URLs. A private Git context URL with an embedded token, logged by CI.
- Checks left as warnings. Build checks run but never fail the build.
- Long-lived CI secrets. Mounts are correct, but the secret is a non-expiring token shared by every pipeline.
Practitioner checklist
- Every Dockerfile starts with
# syntax=docker/dockerfile:1and# check=error=true. - No secret is passed through
ARG,ENV,--build-argorCOPY. - All credentials reach the build through
RUN --mount=type=secretorRUN --mount=type=ssh, withrequired=true. - Secret mounts are scoped to the single step that needs them, with
mode=0400and the correctuid. - Private Git contexts use
GIT_AUTH_TOKENorGIT_AUTH_HEADER, never tokens in URLs. - SSH builds use dedicated, read-only deploy keys or machine identities, not personal keys.
- CI jobs obtain short-lived, narrowly scoped tokens through OIDC federation where the target supports it.
.dockerignoreexcludes credential files, and final stages copy only built artefacts.- Every image is scanned layer by layer for secrets before push, and history and config are reviewed.
- Any secret ever exposed through a build argument or layer has been rotated.
Standards and references
- Docker: Build secrets
- Docker: Dockerfile reference (RUN --mount, ARG, ENV)
- Docker: SecretsUsedInArgOrEnv build check
- Docker: Build checks
- OWASP: Secrets Management Cheat Sheet
- NIST: SP 800-190 Application Container Security Guide
- NIST: SP 800-204D, Strategies for the Integration of Software Supply Chain Security in DevSecOps CI/CD Pipelines
- MITRE ATT&CK: Credentials In Files (T1552.001)
Related NHI Mgmt Group resources: Secrets in Container Images and Build Artefacts Guide · How to find hard-coded secrets in container images · Docker and Docker Compose Security Guide · CI/CD Pipeline Identity Security Guide