Secrets Management in Docker: Build-Time vs. Runtime

Docker secrets done right: how credentials leak through ARG, ENV and layers, plus BuildKit secret mounts and safe runtime options.

Executive Summary: Secrets reach containers at two different times, and each needs a different tool. Build-time secrets, such as a private npm token or a deploy key for a private Git repository, should be passed with BuildKit --mount=type=secret or --mount=type=ssh, which exposes them to a single RUN step without writing them into any layer. Runtime secrets, such as database passwords and API keys, should be injected when the container starts, preferably as files on a tmpfs or fetched from a secret manager, never baked into the image. Anything that ever landed in an image layer must be treated as leaked and rotated.
Isometric vault block with a padlock and key above a container, with a leaking secret card marked blocked

A team builds an image that installs private packages with ARG NPM_TOKEN and RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && npm ci && rm .npmrc. The .npmrc is deleted, and the image is pushed to a registry. Anyone who can pull the image can run docker history --no-trunc and read the token in plain text from the build arguments. The rm did nothing useful.

A secret is any value that grants access: passwords, API keys, tokens, private keys, certificates. Docker images are designed to be copied, cached and shared, which is the opposite of what a secret needs. Managing secrets with Docker means keeping them out of images entirely and delivering them only to the process that needs them, at the moment it needs them.

How secrets leak into images

Mistake Where the secret ends up
ARG TOKEN used in a RUN Image history, visible with docker history --no-trunc
ENV API_KEY=... in the Dockerfile Image configuration, visible to anyone who pulls the image
COPY id_rsa then RUN rm id_rsa The earlier layer, extractable from the image tarball
COPY . . with a .env in the directory A layer of the final image
docker run -e DB_PASSWORD=... Shell history, docker inspect, process listings, often logs
App prints its config on startup Log aggregation systems, retained for months

The layer model from images, containers and layers explains the third row: a file deleted in a later layer is hidden, not removed. A .dockerignore that excludes .env, keys and certificates, as covered in the build cache guide, prevents the fourth.

Build-time secrets with BuildKit

Secret mounts

# syntax=docker/dockerfile:1
FROM node:18-bookworm-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    npm ci
docker build --secret id=npmrc,src=$HOME/.npmrc -t billing-api:1.7.0 .

During that one RUN step, BuildKit mounts the file at /root/.npmrc on a temporary filesystem. When the step finishes, the mount disappears. The secret is not in any layer, not in the image history and not in the build cache key, so changing the token does not invalidate the cache either. You can also pass a secret from an environment variable with --secret id=npm_token,env=NPM_TOKEN and read it in the step from /run/secrets/npm_token.

SSH agent forwarding

RUN --mount=type=ssh \
    git clone git@github.com:acme/internal-lib.git /src/internal-lib
docker build --ssh default -t billing-api:1.7.0 .

--ssh default forwards your running SSH agent into the build step, so private Git dependencies can be fetched without copying a private key anywhere. In CI, load a deploy key into an agent first, or use the CI provider’s built-in Git credentials.

Both features require BuildKit, which is the default builder since Docker Engine 23.0, and the # syntax=docker/dockerfile:1 line. In GitHub Actions, the docker/build-push-action accepts a secrets input that maps repository secrets to build secrets in the same way.

Runtime secrets

For values the running application needs, the options range from simple to robust.

Environment variables: acceptable, with care

Environment variables are the most common approach and the one most frameworks expect. They are fine for many teams, provided you never put them in the Dockerfile, pass them from a file rather than the command line (--env-file), restrict who can run docker inspect on the host, and make sure the application never logs its environment. Their weakness is how easily they spread: child processes inherit them, error trackers capture them, and debug pages print them.

Files on tmpfs: better

Mounting the secret as a file, readable only by the application user, reduces accidental exposure. Many official images support it through *_FILE variables, such as POSTGRES_PASSWORD_FILE. Compose secrets mount files at /run/secrets/<name>, as shown in Docker Compose in practice. For your own applications, support both: read DB_PASSWORD, or if DB_PASSWORD_FILE is set, read the file.

import os

def secret(name: str) -> str:
    path = os.environ.get(f"{name}_FILE")
    if path:
        with open(path) as f:
            return f.read().strip()
    return os.environ[name]

DB_PASSWORD = secret("DB_PASSWORD")

Swarm secrets

In Docker Swarm mode, docker secret create stores secrets encrypted in the cluster’s Raft log and delivers them only to services that are granted them, mounted on an in-memory filesystem. If you run Swarm, use them. Plain Docker and single-host Compose do not encrypt secrets; Compose’s file-based secrets are about delivery, not storage.

A secret manager: best for production

HashiCorp Vault, AWS Secrets Manager, Google Secret Manager and Azure Key Vault store secrets centrally, audit every access, support rotation and can issue short-lived credentials. The container authenticates with an identity, such as an IAM role on ECS or a workload identity in Kubernetes, and fetches secrets at startup or through a sidecar agent that writes them to a shared tmpfs. Nothing secret is stored on the host’s disk or in configuration files at all, and rotating a password does not require rebuilding or even redeploying images.

If a secret leaked

  1. Rotate it first. Deleting the image tag does not help; it may already be pulled, cached in CI runners or mirrored. Assume it is public.
  2. Rebuild without it using the techniques above, and delete the affected images from registries.
  3. Add detection. Run a secret scanner such as Gitleaks or TruffleHog on the repository and on built images in CI, so the next mistake is caught before a push.

Frequently Asked Questions

Is it safe to pass secrets as Docker build arguments?

No. Build argument values used in RUN steps are recorded in the image history and can be read by anyone who pulls the image. Use BuildKit secret mounts with docker build –secret instead.

How do I use a private npm or pip token during docker build?

Mount it as a BuildKit secret: RUN –mount=type=secret,id=npmrc,target=/root/.npmrc npm ci, and build with –secret id=npmrc,src=path/to/.npmrc. The token is available only during that step and never stored in a layer.

Are environment variables safe for secrets in Docker?

They are common and acceptable for many teams, but easy to leak through docker inspect, process listings, crash reports and logs. Mounting secrets as files or fetching them from a secret manager at startup reduces that exposure.

Does deleting a file in a later Dockerfile step remove the secret?

No. The file remains in the earlier layer and can be extracted from the image. If a secret was ever copied into an image, rotate it and rebuild the image without it.

Keep secrets out of artifacts

Images are artifacts meant to be shared; secrets are not. Use BuildKit mounts for anything the build needs, inject runtime secrets when the container starts, prefer files and secret managers over plain environment variables as your setup matures, and rotate anything that ever touched a layer. With that discipline, publishing an image never means publishing a password. For the full reference, see the BuildKit secrets guide and the OWASP Secrets Management Cheat Sheet. Related reading on this site: container security hardening and Docker CI/CD.

Originally posted on 30 August 2023 and post last modified on 30 August 2023

DevOps Docker Secrets Management Security

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *