Browse topics

BuildKit build secrets

Version
29
Review
Draft

Summary#

Pass a file or an environment variable to BuildKit with --secret. A matching secret mount makes it available to one RUN instruction without adding the mounted file to the image.

Syntax#

sh
docker build --secret id=license,src=/path/to/license.txt .
dockerfile
RUN --mount=type=secret,id=license,required=true test -s /run/secrets/license

Example#

Use a disposable Docker daemon with the docker BuildKit driver. Discard its storage afterward to clear the build cache.

sh
(
  set -eu
  name="dlr-docker-commands-secret-$$"
  dir=$(mktemp -d)
  trap 'docker rm -f "$name" >/dev/null 2>&1 || true; docker image rm "$name:demo" >/dev/null 2>&1 || true; rm -rf -- "$dir"' EXIT

  printf 'sample-license\n' > "$dir/license.txt"
  mkdir "$dir/context"
  cat > "$dir/context/Dockerfile" <<'EOF'
FROM alpine:3
RUN --mount=type=secret,id=license,required=true \
    test -s /run/secrets/license && echo 'license present during build' > /result
CMD ["sh", "-c", "cat /result; test ! -e /run/secrets/license && echo 'secret absent at runtime'"]
EOF

  docker build --quiet --secret "id=license,src=$dir/license.txt" \
    --tag "$name:demo" "$dir/context" >/dev/null
  docker run --pull never --rm --name "$name" "$name:demo"
)

Expected output#

Text
license present during build
secret absent at runtime

Common mistakes#

Keep credential files out of the build context so a broad COPY cannot include them. A secret mount does not protect values that a build command prints or writes into a layer. Changing only the secret's contents does not invalidate the cache for that step.

Version applicability#

Checked with Docker Engine 29 and BuildKit. RUN --mount requires Dockerfile syntax 1.2 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0