5.2.3 BuildKit Secrets
A focused guide to BuildKit Secrets, connecting core concepts with practical Docker and container operations.
BuildKit secrets is the general capability allowing sensitive values to be made available to specific build steps without those values ever being written into the resulting image's layers, encompassing both file-based secrets and SSH agent forwarding under a unified mounting mechanism.
The General Secret Mount Mechanism
Both secret mounts and SSH mounts are specific applications of BuildKit's broader --mount mechanism, used within RUN instructions to make external, sensitive data available only for the duration of that instruction's execution.
RUN --mount=type=secret,id=api_key \
curl -H "Authorization: Bearer $(cat /run/secrets/api_key)" https://api.example.com/data
Defining Multiple Secrets for a Single Build
A build can define and use several distinct secrets, each identified by its own ID, allowing different build steps to access exactly the specific credential each one actually needs.
RUN --mount=type=secret,id=npm_token npm install
RUN --mount=type=secret,id=docker_registry_token docker login
docker build \
--secret id=npm_token,src=./npm_token.txt \
--secret id=docker_registry_token,src=./registry_token.txt \
-t myapp .
Why Build Arguments Are Not a Safe Substitute
Unlike build arguments, which can be embedded into image history depending on how they're used, secret mounts are specifically designed so the sensitive value never becomes part of any layer at all, which is what makes them appropriate for genuinely sensitive credentials.
ARG API_KEY
RUN curl -H "Authorization: Bearer $API_KEY" https://api.example.com
RUN --mount=type=secret,id=api_key curl -H "Authorization: Bearer $(cat /run/secrets/api_key)" https://api.example.com
The second form is the appropriate choice whenever the value involved is genuinely sensitive.
Why BuildKit's Secret Handling Matters
A unified, well-designed secret mounting mechanism removes the need for risky workarounds previously common when a build genuinely needed access to a credential, making secure handling of build-time secrets a straightforward, well-supported capability rather than an awkward problem each project had to solve independently.