iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

docker build

docker build reads a Dockerfile and produces an image. BuildKit (default since 23.0) adds parallelism, secret mounts, cache mounts, and multi-platform builds. Use it.

Buildx, cache, secrets, multi-platform

EXAMPLE
# Basic build with a tag
docker build -t me/app:1.0 .

# Tag latest and a SHA simultaneously
docker build -t me/app:latest -t me/app:$(git rev-parse --short HEAD) .

# Use buildx (BuildKit) explicitly
docker buildx create --use --name multibuilder
docker buildx build -t me/app:1.0 .

# Multi-platform — one command, both architectures
docker buildx build \
    --platform linux/amd64,linux/arm64 \
    -t me/app:1.0 \
    --push .

# Cache from a previous build or a remote registry — speeds up CI dramatically
docker buildx build \
    --cache-from=type=registry,ref=me/app:cache \
    --cache-to=type=registry,ref=me/app:cache,mode=max \
    -t me/app:1.0 \
    --push .

# Build arguments
Dockerfile:
    ARG NODE_VERSION=20
    FROM node:${NODE_VERSION}-alpine

docker build --build-arg NODE_VERSION=22 -t me/app:22 .

# Secrets — file or env, NEVER copy a secret into a layer
# Dockerfile:
#   RUN --mount=type=secret,id=npmrc cp /run/secrets/npmrc ~/.npmrc && npm ci && rm ~/.npmrc

docker buildx build --secret id=npmrc,src=$HOME/.npmrc -t me/app .

# Cache mounts — keep npm/cache between builds without baking it in
# Dockerfile:
#   RUN --mount=type=cache,target=/root/.npm npm ci

Why it matters

Always use --mount=type=secret for build-time credentials. Copying a .npmrc / id_rsa into a layer leaves it in the image history forever — one of the most common image-secret leaks.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
docker build -t my-api:1.0 .
docker build --no-cache -t my-api:1.0 .
Try it Yourself »

Exercise

Build an image and tag it.

docker build -t my-api:1.0

Discussion

Loading…