Build Arguments and Secrets
What you'll learn: How to pass build-time configuration safely while keeping sensitive data out of your images.
The Core Idea
When building container images, you often need to inject configuration values—like API endpoints or version numbers—and sometimes sensitive data like authentication tokens. Build arguments let you parameterize builds with variables, while secrets require special handling to prevent leaking credentials into image layers.
Build Arguments (ARG)
You've already learned about ARG instructions. They create variables available only during the build process:
ARG NODE_VERSION=18
FROM node:${NODE_VERSION}
Pass values at build time:
docker build --build-arg NODE_VERSION=20 -t myapp .
Important: ARG values can appear in image history and layers—never use them for passwords or tokens.
Handling Secrets Securely
Secrets (passwords, keys, tokens) should never be baked into layers. With BuildKit, use secret mounts that expose credentials temporarily during RUN commands without persisting them:
# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npm_token \
npm config set //registry.npmjs.org/:_authToken=$(cat /run/secrets/npm_token)
Build with:
docker build --secret id=npm_token,src=./token.txt -t myapp .
The secret is mounted temporarily, used, then discarded—it never enters a layer.
The Analogy
Think of ARG like sticky notes on a package—anyone can read them. Secrets are like borrowing a key temporarily to unlock a door during packing, then returning it without leaving it in the box.
Key Takeaway: Use ARG for non-sensitive build parameters and BuildKit secret mounts for credentials—never hardcode secrets or pass them via ARG, as they'll persist in image layers.