BuildKit Secrets & Build Arguments
Advancedv1.0.0
Securely pass credentials during Docker builds using BuildKit secrets — access private registries, clone private repos, and configure APIs without leaking secrets into image layers.
Content
Overview
Docker build often requires credentials — npm tokens for private packages, SSH keys for private repos, API keys for build-time operations. BuildKit secrets mount credentials temporarily during build without persisting them in any image layer.
Why This Matters
- -ARG and ENV leak into image history — anyone with the image can extract them
- -BuildKit secrets are ephemeral — mounted only during the RUN command, never in layers
- -SSH agent forwarding — clone private repos without copying SSH keys into the image
- -Compliance — secrets in image layers fail security audits
The Problem with ARG/ENV
Step 1: Use BuildKit Secrets
Step 2: SSH Agent Forwarding for Private Repos
Step 3: Multiple Secrets
Step 4: Docker Compose with Secrets
Best Practices
- -Always use
# syntax=docker/dockerfile:1at the top for BuildKit features - -Never use ARG or ENV for secrets — they persist in image metadata
- -Use SSH agent forwarding instead of copying SSH keys
- -Verify secrets are not in layers:
docker history --no-trunc - -In CI, pass secrets from environment:
--secret id=token,env=NPM_TOKEN
Common Mistakes
- -Using ARG for tokens (visible in docker history)
- -Copying secret files and deleting in a later layer (still in earlier layer)
- -Not enabling BuildKit (DOCKER_BUILDKIT=1 or Docker 23+ default)
- -Forgetting the
# syntax=docker/dockerfile:1directive
FAQ
Discussion
Loading comments...