SyntaxStudy
Sign Up
Docker Building Images with docker build
Docker Beginner 1 min read

Building Images with docker build

docker build reads a Dockerfile and produces a new image. The build context — the directory passed as the last argument — is sent to the Docker daemon, so keep it small by adding a .dockerignore file that excludes node_modules, .git, log files, and local .env files. A large build context dramatically slows down builds even if the files are not copied into the image. Build cache is Docker's most important performance feature. Each Dockerfile instruction is hashed against its content and its parent layer's ID. If the hash matches a cached layer, Docker reuses it instead of re-running the instruction. Order instructions from least-frequently-changing to most-frequently-changing: base image, OS packages, dependency installation, then application code. This ensures that copying package.json and running npm install are cached on most builds. The --build-arg flag passes build-time variables that can be referenced in the Dockerfile with ARG. These are useful for injecting version numbers, but never for secrets — build args are visible in docker history. Use --secret (BuildKit) for sensitive values.
Example
# .dockerignore
# node_modules/
# .git/
# .env*
# *.log
# coverage/

# Build with default tag
docker build -t myapp:latest .

# Build with multiple tags
docker build -t myapp:2.1.0 -t myapp:latest .

# Build with build args
docker build \
  --build-arg NODE_VERSION=20 \
  --build-arg APP_VERSION=2.1.0 \
  -t myapp:2.1.0 .

# Build without cache
docker build --no-cache -t myapp:latest .

# Build from a specific Dockerfile
docker build -f Dockerfile.prod -t myapp:prod .

# Enable BuildKit (faster, better caching)
DOCKER_BUILDKIT=1 docker build -t myapp:latest .

# View build history
docker history myapp:latest --no-trunc