Speed Up Docker Builds and Shrink Images with Multi‑Stage Builds and Caching
Learn practical techniques to accelerate Docker image builds, cut down image size, and improve security by selecting lightweight base images, applying multi‑stage builds, exploiting Docker's layer cache, and consolidating RUN commands into fewer layers.
Use an Appropriate Base Image
Selecting a lightweight base image such as Alpine or Ubuntu Minimal reduces the final image size and ensures you start from a secure, up‑to‑date foundation.
Use Multi‑Stage Builds
Multi‑stage builds let you define several FROM statements in a single Dockerfile, copying only the artifacts needed for the final runtime image. This eliminates build‑time dependencies from the final image.
# Build stage 1
FROM golang:1.17 AS builder
WORKDIR /app
COPY . .
# Compile the application
RUN go build -o myapp
# Build stage 2
FROM alpine:latest
# Copy the compiled binary
COPY --from=builder /app/myapp /usr/local/bin/
WORKDIR /usr/local/bin
CMD ["myapp"]Leverage Docker Build Cache
Docker caches each layer during a build. If a layer's instructions and source files haven't changed, Docker reuses the cached layer, dramatically speeding up subsequent builds. The example below shows a typical Node.js Dockerfile that benefits from this cache.
# Set base image
FROM node:14
# Set working directory
WORKDIR /app
# Copy package files and install dependencies
COPY package*.json ./
RUN npm install
# Copy application source
COPY . .
# Define container start command
CMD ["node", "app.js"]When only app.js changes, Docker reuses the cached layer that installed dependencies, avoiding a costly npm install step.
Combine Commands to Reduce Layers
Each RUN creates a new image layer. Merging related commands with && into a single RUN reduces the number of layers and the overall image size.
RUN apt-get update && apt-get install -y \
package1 \
package2 \
package3By consolidating installation steps, you keep the image lean and faster to pull.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
dbaplus Community
Enterprise-level professional community for Database, BigData, and AIOps. Daily original articles, weekly online tech talks, monthly offline salons, and quarterly XCOPS&DAMS conferences—delivered by industry experts.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
