11.1.3 Secret Leak Prevention
A focused guide to Secret Leak Prevention, connecting core concepts with practical Docker and container operations.
Secret leak prevention covers the various practices needed to avoid sensitive values — API keys, credentials, private keys — accidentally ending up baked into an image's layers, exposed in build logs, or otherwise leaked through one of several specific, well-known mechanisms.
Why a Secret Baked Into a Layer Is Effectively Permanent
A secret written to a file during a build step, even if later deleted in a subsequent instruction, typically remains recoverable from the layer where it was originally written, since each layer's content is preserved independently.
RUN echo "API_KEY=secret123" > /app/.env
RUN rm /app/.env
Despite the second instruction deleting the file, the layer created by the first instruction still contains it, recoverable by anyone with access to inspect the image's layers.
Avoiding Secrets in Build Arguments
A build argument's value can be recovered from an image's build history, making it an inappropriate mechanism for passing genuinely sensitive values.
ARG API_KEY
docker build --build-arg API_KEY=secret123 -t myapp .
docker history myapp
This history command can reveal the build argument's value, demonstrating why this mechanism shouldn't be used for genuine secrets.
Using BuildKit's Dedicated Secret Mounting Instead
BuildKit provides a purpose-built mechanism for using a secret during a build without it being persisted in any layer at all.
RUN --mount=type=secret,id=api_key cat /run/secrets/api_key
docker build --secret id=api_key,src=./api_key.txt -t myapp .
This secret is available only during this specific instruction's execution, never written to any persisted layer.
Why Secret Leak Prevention Matters
Understanding these specific leak mechanisms — layer persistence, build argument history — and using the dedicated secret mounting mechanism instead is essential for avoiding the serious, often hard-to-fully-remediate consequence of a sensitive value becoming permanently embedded in a distributed image.