Advanced Docker: Multi-Stage Builds and Optimization
· Pavan Y N · docker, containers, devops, cicd
Docker fundamentals get an application running in a container. Production images need more: small size, fast and cacheable builds, no secrets in layers, and a reduced attack surface. EduGeek explains multi-stage builds, build-cache optimization, image hardening, and Docker Compose patterns here, using BuildKit features that are available in current Docker Engine and Docker Desktop releases. For the basics, start with Docker Fundamentals, and when the images are ready to run on a cluster, continue with Kubernetes Fundamentals.
# Multi-stage builds
## Why multi-stage builds?
A multi-stage build uses several FROM instructions in one Dockerfile. Each FROM starts a new stage, and COPY --from=<stage> moves chosen files from one stage into another. This lets a Dockerfile:
- →Separate build-time dependencies from runtime dependencies
- →Keep compilers, package managers, and test tooling out of the final image
- →Build independent stages in parallel
- →Stay readable, with one Dockerfile instead of a build script plus a runtime Dockerfile
BuildKit, the default builder, builds only the stages that the target stage depends on. A stage that nothing references never runs. This matters for the scanning pattern discussed later.
## Basic multi-stage build
Before (single stage):
FROM node:24
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["node", "dist/server.js"]
The final image carries the full Debian-based toolchain, every development dependency, and the source tree.
After (multi-stage):
# syntax=docker/dockerfile:1
# Build stage: all dependencies, because the build needs dev tooling
FROM node:24-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
# Runtime stage: production dependencies and build output only
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package*.json ./
EXPOSE 3000
USER node
CMD ["node", "dist/server.js"]
Installing with npm ci --omit=dev in the stage that also runs npm run build is a common mistake. Build tools such as bundlers and compilers usually live in devDependencies, so the build fails with command not found. Install everything, build, then prune.
## Advanced multi-stage patterns
1. Separate dependency, build, and runtime stages (Node.js)
Splitting dependencies into their own stage keeps the production node_modules cacheable independently of the build. The --mount=type=cache flag keeps npm's download cache between builds without storing it in an image layer.
# syntax=docker/dockerfile:1
FROM node:24-alpine AS base
WORKDIR /app
# Development stage, used by Compose with `target: development`
FROM base AS development
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
CMD ["npm", "run", "dev"]
# Production dependencies only
FROM base AS prod-deps
RUN --mount=type=bind,source=package.json,target=package.json \
--mount=type=bind,source=package-lock.json,target=package-lock.json \
--mount=type=cache,target=/root/.npm \
npm ci --omit=dev
# All dependencies, then build
FROM base AS build
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
# Runtime image
FROM base AS production
ENV NODE_ENV=production
COPY --from=prod-deps --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "fetch('http://localhost:3000/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
CMD ["node", "dist/server.js"]
Two details are easy to miss. Alpine-based Node.js images do not ship curl, so the health check uses Node's built-in fetch instead. And node is an existing non-root user in the official image, so no adduser step is needed.
2. Go application on a minimal base
# syntax=docker/dockerfile:1
# Run the compiler natively and cross-compile for the target platform
FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS build
ARG TARGETOS TARGETARCH
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -trimpath -ldflags="-s -w" -o /out/server .
# Static distroless image: CA certificates, tzdata, and a non-root user, no shell
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/server /server
EXPOSE 8080
ENTRYPOINT ["/server"]
A few older habits are gone from this version. With CGO_ENABLED=0, the compiler already produces a static binary, so -a -installsuffix cgo and -extldflags "-static" are unnecessary. Hardcoding GOARCH=amd64 produces a binary that fails on ARM hosts, including Apple silicon laptops and ARM cloud instances, so the build takes the architecture from BuildKit's TARGETARCH argument. FROM scratch also works, but the distroless static image adds CA certificates and a non-root user for free. The result is a final image of roughly 15 MB for a small HTTP service.
3. Python application with Poetry
# syntax=docker/dockerfile:1
FROM python:3.14-slim AS builder
ENV POETRY_VIRTUALENVS_IN_PROJECT=true \
POETRY_NO_INTERACTION=1
RUN pip install --no-cache-dir "poetry>=2,<3"
WORKDIR /app
# Install production dependencies into /app/.venv
COPY pyproject.toml poetry.lock ./
RUN --mount=type=cache,target=/root/.cache/pypoetry \
poetry install --only main --no-root
FROM python:3.14-slim AS production
WORKDIR /app
RUN useradd --create-home --uid 1001 appuser
COPY --from=builder --chown=appuser:appuser /app/.venv ./.venv
COPY --chown=appuser:appuser src ./src
ENV PATH="/app/.venv/bin:$PATH"
USER appuser
EXPOSE 8000
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
Poetry 2 removed the --no-dev flag that older guides use. poetry install --no-dev now fails with The option "--no-dev" does not exist. Use --only main to install the main dependency group alone, or --without dev to exclude a group. --no-root skips installing the project itself, which is correct here because the application source is copied into the runtime stage separately. Pin Poetry to a major version range rather than an old exact release.
# Image optimization techniques
## 1. Layer cache optimization
When a layer changes, all layers after it are rebuilt. Put slow, rarely changing steps first.
# Bad: any source change invalidates the dependency install
FROM node:24-alpine
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run build
# Good: dependency files first, source after
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
Other cache mounts follow the same pattern, for example /root/.cache/pip for pip, /go/pkg/mod and /root/.cache/go-build for Go, and /var/cache/apt plus /var/lib/apt with sharing=locked for apt.
## 2. Combine related commands and clean up in the same layer
Layers are immutable. Deleting a file in a later layer hides it but does not shrink the image, because the earlier layer still holds the bytes. Cleanup must happen in the same RUN that created the files.
# Bad: the package lists persist in the earlier layer
FROM debian:13-slim
RUN apt-get update
RUN apt-get install -y curl git
RUN rm -rf /var/lib/apt/lists/*
# Good: update, install, and clean in one layer
FROM debian:13-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
git \
&& rm -rf /var/lib/apt/lists/*
On Alpine, apk add --no-cache avoids writing the package index cache at all, so a separate rm -rf /var/cache/apk/* is unnecessary.
## 3. Use .dockerignore
A .dockerignore file keeps files out of the build context, which speeds up builds and prevents secrets from being copied by COPY . ..
# .dockerignore
node_modules
npm-debug.log
.git
.gitignore
.env
.env.*
*.md
.vscode
.idea
coverage
.nyc_output
dist
build
*.log
.DS_Store
Dockerfile*
compose*.yaml
.dockerignore
## 4. Choose an appropriate base image
| Base image | Characteristics |
|---|---|
node:24 | Full Debian toolchain. Largest. Useful as a build stage. |
node:24-slim | Debian without most build tooling. Uses glibc. |
node:24-alpine | Small. Uses musl instead of glibc, which can break native modules and prebuilt glibc binaries. |
gcr.io/distroless/nodejs24-debian13:nonroot | Runtime only, no shell or package manager. Debug variants add a shell. |
| Docker Hardened Images | Minimal images maintained by Docker, with signed SBOMs and provenance. The Community tier is free under Apache 2.0. |
Distroless images publish latest, nonroot, debug, and debug-nonroot tags per image, and the project treats any other tag as deprecated. The project README lists Debian 13 images for Node.js 22, 24, and 26, and the nodejs20-debian11 name used in older guides is not among them. Node.js 20 itself reached end of life in March 2026.
A distroless Node.js runtime stage looks like this:
FROM gcr.io/distroless/nodejs24-debian13:nonroot
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
EXPOSE 3000
CMD ["dist/server.js"]
The image's entrypoint is already node, so CMD supplies only the script path.
## 5. Copy only what the runtime needs
Deleting source files inside the build stage (for example rm -rf src tests docs) has no effect on the final image, because the final stage only receives what its COPY --from lines select. The savings come from being selective in those COPY lines, so list the exact artifacts the runtime needs and nothing else.
# Security best practices
## 1. Use a non-root user
Assign an explicit user, and an explicit numeric UID and GID where the image does not already provide one, because automatically assigned IDs can change between rebuilds.
FROM node:24-alpine
WORKDIR /app
COPY --chown=node:node package*.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
## 2. Scan for vulnerabilities
Scan the built image, and fail the pipeline when serious findings appear.
# Docker Scout (requires `docker login`): exit code 2 when matching vulnerabilities are found
docker scout cves --only-severity critical,high --exit-code myapp:latest
# Trivy, scanning an exported archive instead of mounting the Docker socket
docker save myapp:latest -o myapp.tar
trivy image --input myapp.tar --severity HIGH,CRITICAL --exit-code 1
# Snyk
snyk container test myapp:latest
Mounting /var/run/docker.sock into a scanner container gives that container control over the Docker daemon, which is equivalent to root on the host. Scanning an exported archive or a registry image avoids that.
A scanning stage inside the Dockerfile does not work the way it first appears to:
FROM node:24-alpine AS builder
# ... build ...
# This stage is never executed: nothing depends on it
FROM aquasec/trivy:latest AS security-scan
COPY --from=builder /app /scan
RUN trivy fs --severity HIGH,CRITICAL --exit-code 1 /scan
FROM node:24-alpine
COPY --from=builder /app/dist ./dist
Because the final stage does not depend on security-scan, BuildKit skips it, and the build succeeds even when the scan would have failed. Run the scan as a separate CI step after the build, or make the final stage depend on the scan stage explicitly.
Scanners are part of the supply chain too. In March 2026, attackers used stolen credentials to publish a malicious Trivy v0.69.4 release and to repoint version tags of the trivy-action and setup-trivy GitHub Actions at malicious commits. Aqua's advisory (GHSA-69fq-xp46-6x23, CVE-2026-33634) lists images referenced by digest as unaffected and recommends pinning container images by digest and GitHub Actions by full commit SHA rather than mutable tags. Never use latest for security tooling.
## 3. Handle secrets safely
Anything set with ENV or ARG, and anything copied into a layer, stays in the image history. Docker's documentation states that build arguments and environment variables are inappropriate for passing secrets to a build.
# Bad: the password is stored in the image configuration
FROM node:24-alpine
ENV DATABASE_PASSWORD=mysecretpassword
CMD ["node", "server.js"]
Build-time secrets use a BuildKit secret mount. The secret is available only during that RUN instruction and is never written to a layer:
# syntax=docker/dockerfile:1
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
# The secret is mounted as a file for this command only
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
npm ci
COPY . .
RUN npm run build
# Pass the secret from a file ...
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:latest .
# ... or from an environment variable
docker build --secret id=NPM_TOKEN -t myapp:latest .
Runtime secrets should be mounted as files or injected by the orchestrator, not baked into the image. Docker Compose supports file-based secrets that appear under /run/secrets/<name>, and many images, such as PostgreSQL, accept a *_FILE variable that points at one:
services:
db:
image: postgres:18-alpine
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./db_password.txt
Docker Swarm has its own secret store (docker secret create), but Docker documents it as available only to Swarm services, not to standalone containers. On Kubernetes, use Kubernetes Secrets with encryption at rest or an external secret store.
## 4. Read-only root filesystem and reduced privileges
A read-only root filesystem is a runtime setting, not a Dockerfile instruction. The container runtime enforces it, and the application writes only to explicitly provided locations.
docker run --rm \
--read-only \
--tmpfs /tmp \
--cap-drop ALL \
--security-opt no-new-privileges:true \
--user 1001:1001 \
myapp:latest
The same settings in Compose:
services:
app:
image: myapp:latest
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
tmpfs:
- /tmp
- /app/tmp
volumes:
- logs:/app/logs
user: "1001:1001"
volumes:
logs:
Drop all Linux capabilities first, then add back only those the application proves it needs with cap_add.
# Advanced Docker Compose patterns
## 1. Development and production configurations
Compose reads compose.yaml, and automatically merges compose.override.yaml when it exists. When file names are passed with -f, Compose merges them in order: single-value options such as image and command are replaced, ports lists are concatenated, and environment is merged by key.
compose.yaml (base):
services:
app:
build:
context: .
environment:
NODE_ENV: ${NODE_ENV:-production}
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
db:
image: postgres:18-alpine
environment:
POSTGRES_DB: ${DB_NAME}
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- postgres-data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d ${DB_NAME}"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:8-alpine
command: redis-server --appendonly yes
volumes:
postgres-data:
compose.dev.yaml (development overrides):
services:
app:
build:
target: development
ports:
- "3000:3000"
- "9229:9229" # Node.js debugger
environment:
NODE_ENV: development
develop:
watch:
- action: sync
path: ./src
target: /app/src
ignore:
- node_modules/
- action: rebuild
path: package.json
db:
ports:
- "5432:5432"
redis:
ports:
- "6379:6379"
compose.prod.yaml (production overrides):
services:
app:
build:
target: production
restart: unless-stopped
deploy:
replicas: 3
resources:
limits:
cpus: "1"
memory: 512M
reservations:
cpus: "0.5"
memory: 256M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
db:
restart: unless-stopped
deploy:
resources:
limits:
cpus: "2"
memory: 2G
redis:
restart: unless-stopped
volumes:
- redis-data:/data
volumes:
redis-data:
Usage:
# Development, with file watching (syncs source changes into the running container)
docker compose -f compose.yaml -f compose.dev.yaml up --watch
# Production
docker compose -f compose.yaml -f compose.prod.yaml up -d
Compose Watch has three actions. sync copies changed files into the container, rebuild builds a new image and replaces the container, and sync+restart copies files and then restarts the container. It replaces the older pattern of bind-mounting the source tree and hiding node_modules behind an anonymous volume.
The deploy.replicas and deploy.resources settings are honored by docker compose up, not only by Swarm. A container started from the production file above reports its configured memory and CPU limits in docker inspect. Because the production app service publishes no host port, scaling to three replicas does not cause port conflicts.
Match the PostgreSQL volume path to the image version. PostgreSQL 18 and later mount the volume at /var/lib/postgresql, while 17 and earlier use /var/lib/postgresql/data.
## 2. Health checks and startup dependencies
services:
app:
image: myapp:latest
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
migration:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://localhost:3000/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
migration:
image: myapp:latest
command: npm run migrate
depends_on:
db:
condition: service_healthy
restart: on-failure
db:
image: postgres:18-alpine
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
volumes:
- postgres-data:/var/lib/postgresql
redis:
image: redis:8-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 3s
retries: 3
secrets:
db_password:
file: ./db_password.txt
volumes:
postgres-data:
The three depends_on conditions mean different things. service_started waits only for the container to start, service_healthy waits for its health check to pass, and service_completed_successfully waits for a one-shot container such as a migration job to exit with status 0.
# Advanced Docker networking
## 1. Segmented networks
services:
frontend:
image: frontend:latest
networks:
- frontend-network
- backend-network
backend:
image: backend:latest
networks:
- backend-network
- database-network
database:
image: postgres:18-alpine
networks:
- database-network
networks:
frontend-network:
driver: bridge
backend-network:
driver: bridge
database-network:
driver: bridge
internal: true # No external connectivity
The frontend service cannot reach database because they share no network. The internal: true setting creates an externally isolated network, so the database also cannot open outbound connections.
## 2. Network aliases
services:
app:
image: myapp:latest
networks:
app-network:
aliases:
- api.local
- app.local
nginx:
image: nginx:1.30-alpine
networks:
- app-network
# nginx can reach the app container as api.local or app.local
networks:
app-network:
# Auditing an existing image
Measure before optimizing. These commands show where size and risk come from.
# Per-layer sizes and the instruction that created each layer
docker history myapp:latest
# Run BuildKit's built-in Dockerfile checks without building
docker build --check .
# Known vulnerabilities, filtered by severity
docker scout cves --only-severity critical,high myapp:latest
docker history shows metadata instructions such as ENV, LABEL, and CMD as 0 B entries, so large entries point directly at RUN and COPY instructions worth reviewing. Hadolint is a widely used third-party Dockerfile linter for CI pipelines.
# Common issues and troubleshooting
## Issue 1: Large image sizes
- →Use multi-stage builds and copy only runtime artifacts.
- →Choose a slim, Alpine, distroless, or hardened base image.
- →Clean package caches in the same
RUNthat creates them. - →Add a
.dockerignoreso large directories never enter the build context.
## Issue 2: Slow builds
BuildKit is the default builder, so no DOCKER_BUILDKIT=1 is needed. Speed comes from layer ordering, cache mounts, and sharing the cache between machines.
# Share build cache through a registry (mode=max also caches intermediate stages)
docker buildx build \
--cache-from type=registry,ref=registry.example.com/myapp:buildcache \
--cache-to type=registry,ref=registry.example.com/myapp:buildcache,mode=max \
-t myapp:new .
Inline cache (--build-arg BUILDKIT_INLINE_CACHE=1 with --cache-from myapp:latest) is a simpler alternative that embeds cache metadata in the image itself. The mode option does not apply to it, and it is a cache-sharing mechanism rather than a way to parallelize builds. Registry cache export with the default docker driver requires the containerd image store, which is the default for fresh installs of Docker Engine 29. Otherwise create a builder with the docker-container driver.
## Issue 3: Permission problems
# Fix: set ownership while copying
FROM node:24-alpine
WORKDIR /app
COPY --chown=node:node . .
RUN npm ci
USER node
CMD ["node", "server.js"]
Running chown -R in a separate RUN duplicates every file into a new layer. Setting ownership with COPY --chown avoids that.
# Key takeaways
- →Install development dependencies in the stage that builds the application, then prune or copy only production dependencies into the runtime stage.
- →BuildKit builds only the stages the target stage depends on, so a scanning stage that nothing references is silently skipped and must run as a separate pipeline step.
- →Use
RUN --mount=type=cachefor package-manager caches andRUN --mount=type=secretfor build credentials, because neither ends up in an image layer. - →Image layers are immutable, so cleanup commands must run in the same
RUNthat created the files, and selecting artifacts inCOPY --fromis what shrinks the final image. - →A read-only root filesystem, dropped capabilities, and
no-new-privilegesare runtime settings applied withdocker runflags or Compose keys, not Dockerfile instructions. - →Pin security tooling and base images by digest where possible, because the March 2026 Trivy compromise showed that mutable tags can turn a scanner into an attack path.
- →Write Compose files without the obsolete
version:key, merge environment-specific files with-f, and usedevelop.watchanddepends_onconditions instead of manual bind-mount and sleep workarounds.
# Further reading
Test yourself: Advanced Docker Optimization assessment