✦ For everyone, free.

Practical knowledge for real and everyday life

Home

11.1.3.2 Layer Secret Avoidance

A focused guide to Layer Secret Avoidance, connecting core concepts with practical Docker and container operations.

Layer secret avoidance specifically addresses the fact that each layer in an image preserves its own content independently, meaning a secret present in any single layer remains recoverable from that layer even if subsequent layers delete or overwrite the same file.

Why Each Layer's Content Persists Independently

An image's layered structure means a file's deletion in a later layer doesn't remove that file's content from the earlier layer where it was originally written — both layers continue to exist, stacked together.

RUN echo "secret123" > /tmp/secret.txt
RUN rm /tmp/secret.txt

Inspecting the image's individual layers reveals that the first layer still contains /tmp/secret.txt with its original content, despite the file appearing absent from the final, combined filesystem view.

Demonstrating This With a Direct Layer Inspection

Tools that inspect an image's individual layers, rather than just its final combined filesystem, can reveal content that's been deleted in a later layer but still exists in an earlier one.

docker save myapp:1.0 -o myapp.tar
tar -xf myapp.tar

Extracting and examining an image's individual layer archives this way can reveal content never intended to be exposed, despite appearing absent from the running container's own filesystem view.

Why This Makes "Delete It Later" an Ineffective Strategy

Any approach relying on writing a secret and then deleting it within the same Dockerfile fundamentally fails to actually remove that secret from the resulting image, since the deletion only affects a later layer, not the one where the secret was originally written.

RUN curl -H "Authorization: Bearer $TOKEN" https://api.example.com/data

If $TOKEN here came from a build argument or similarly persisted source, this instruction's layer retains evidence of that secret regardless of anything done afterward.

The Only Reliable Solution: Never Writing the Secret to a Persisted Layer at All

BuildKit's secret mounting mechanism is specifically designed to avoid this problem entirely, by never writing the secret to any layer in the first place.

RUN --mount=type=secret,id=token curl -H "Authorization: Bearer $(cat /run/secrets/token)" https://api.example.com/data
Why Layer Secret Avoidance Matters

Understanding that layers preserve content independently, making after-the-fact deletion ineffective, is essential context for recognizing why a purpose-built secret mounting mechanism — rather than any delete-after-use pattern — is the only reliable way to keep a secret out of an image's persisted layers entirely.