How to Reduce Docker Image Size: Best Practices and Examples
To reduce Docker image size, use
multi-stage builds to separate build and runtime environments, choose minimal base images like alpine, and clean up unnecessary files and caches in each layer. These steps help keep images small and efficient.Syntax
A typical Dockerfile to reduce image size uses multi-stage builds where you have multiple FROM statements. The first stage builds the app, and the final stage copies only the needed files.
Example syntax parts:
FROM base-image AS builder: defines a build stageRUN: runs commands like installing dependencies or buildingCOPY --from=builder: copies files from the build stage to the final image
dockerfile
FROM golang:1.20-alpine AS builder WORKDIR /app COPY . . RUN go build -o myapp FROM alpine:3.18 COPY --from=builder /app/myapp /usr/local/bin/myapp CMD ["myapp"]
Example
This example shows a multi-stage Dockerfile for a Go app. The first stage uses a full Go image to build the app. The second stage uses a small Alpine image and copies only the compiled binary. This reduces the final image size drastically.
dockerfile
FROM golang:1.20-alpine AS builder WORKDIR /app COPY . . RUN go build -o myapp FROM alpine:3.18 RUN apk add --no-cache ca-certificates COPY --from=builder /app/myapp /usr/local/bin/myapp CMD ["myapp"]
Common Pitfalls
Common mistakes that increase image size:
- Using large base images like
ubuntuwhen smaller ones likealpinesuffice. - Not cleaning package manager caches after installing software.
- Copying unnecessary files or build artifacts into the final image.
- Combining many commands without cleaning intermediate files, which creates large layers.
Always clean caches and remove temporary files in the same RUN command to keep layers small.
dockerfile
### Wrong way (large image and leftover cache) FROM ubuntu:22.04 RUN apt-get update && apt-get install -y curl ### Right way (clean cache in one step) FROM ubuntu:22.04 RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
Quick Reference
- Use
alpineor other minimal base images. - Use multi-stage builds to separate build and runtime.
- Clean package manager caches and temporary files in the same
RUNstep. - Copy only necessary files to the final image.
- Combine commands to reduce layers.
Key Takeaways
Use multi-stage builds to keep only necessary files in the final image.
Choose minimal base images like alpine to reduce size.
Clean caches and temporary files in the same RUN command to avoid large layers.
Avoid copying unnecessary files into the image.
Combine commands to reduce the number of image layers.