Docker Build & BuildKit
Complete guide to building Docker images with docker build, BuildKit features, build contexts, build arguments, and caching strategies.
The docker build command compiles a Dockerfile and its surrounding context into a runnable Docker image.
Basic Build Syntax
docker build [OPTIONS] PATH | URL | -# Build an image from current directory and tag it
docker build -t myapp:1.0.0 .
# Build with a custom Dockerfile name
docker build -f Dockerfile.prod -t myapp:prod .
# Build without using cached layers
docker build --no-cache -t myapp:fresh .The Build Context
The final argument (.) specifies the Build Context. The Docker CLI packages and sends this entire directory to the Docker daemon/BuildKit engine before executing instructions.
[!WARNING] If you run
docker build -t myapp .from your root folder without a.dockerignorefile, you may accidentally send hundreds of megabytes (likenode_modulesor.git) to the Docker daemon.
BuildKit: Next-Generation Builder
Modern Docker versions enable BuildKit by default. BuildKit features include:
- Parallel stage execution in multi-stage builds.
- Efficient mount caches (
RUN --mount=type=cache,target=/root/.npm). - Secret mounts that do not leak into final image layers (
RUN --mount=type=secret,id=npmrc).
# Explicitly enable BuildKit (if disabled)
export DOCKER_BUILDKIT=1
docker build -t myapp:latest .Build Arguments (ARG)
Build arguments pass dynamic values at build time that are NOT persisted in the running container environment:
# Dockerfile
ARG NODE_VERSION=22
FROM node:${NODE_VERSION}-alpine
ARG APP_ENV=production
RUN echo "Building for $APP_ENV"# CLI execution
docker build --build-arg NODE_VERSION=20 --build-arg APP_ENV=staging -t myapp:staging .Multi-Platform Builds (docker buildx)
Build images for multiple CPU architectures (e.g. linux/amd64 and linux/arm64) using Buildx:
docker buildx create --use
docker buildx build --platform linux/amd64,linux/arm64 -t username/myapp:latest --push .Related Topics
Dockerfile Reference & Instructions
Complete reference for writing clean, efficient, and secure Dockerfiles using standard instructions like FROM, WORKDIR, COPY, RUN, CMD, and ENTRYPOINT.
Docker Run & Container Execution
Complete guide to running containers with docker run, including interactive modes, detached background mode, auto-removal, restart policies, and environment configuration.