5.2.3.2 Temporary Secret Mounts
A focused guide to Temporary Secret Mounts, connecting core concepts with practical Docker and container operations.
Temporary secret mounts describes the precise lifetime of a BuildKit secret mount — available only for the exact duration of the single RUN instruction that requested it, then unmounted and inaccessible to every subsequent instruction in the build, including ones that immediately follow.
Confirming the Secret Disappears Afterward
Attempting to access a previously mounted secret from a later instruction, after the RUN step that originally requested it has completed, demonstrates this temporary lifetime directly.
RUN --mount=type=secret,id=api_key cat /run/secrets/api_key
RUN cat /run/secrets/api_key
The second instruction fails, since the secret mount existed only for the first instruction's execution and was not requested again for this one.
Why This Temporary Lifetime Is the Point
This deliberately narrow availability window is precisely what prevents a secret from accidentally persisting somewhere it shouldn't — if the mount remained available throughout the entire build, the chance of it inadvertently ending up copied into a layer would increase significantly.
RUN --mount=type=secret,id=db_password \
psql -h db -U admin -W $(cat /run/secrets/db_password) -c "SELECT 1"
The secret is used and discarded entirely within this single instruction, with no opportunity for it to leak into any subsequent step.
Requesting the Same Secret Again if Needed
If a later instruction genuinely needs the same secret, the mount must be explicitly requested again for that instruction specifically — there is no way to make a secret persistently available across multiple instructions by design.
RUN --mount=type=secret,id=api_key step-one.sh
RUN --mount=type=secret,id=api_key step-two.sh
Each instruction independently requests access to the same underlying secret, each receiving it only for its own duration.
Why This Temporary Behavior Matters
Understanding that secret mounts are deliberately temporary, rather than persistently available throughout a build, clarifies both why this mechanism is safe by design and why each instruction needing secret access must explicitly request it on its own.