Optimize Docker Images
Docker images can become huge if you're not careful. Smaller images build faster, deploy faster, and reduce security risks. This chapter covers techniques to minimize image size.
1. Use Small Base Images
Instead of
ubuntu:latest (≈70 MB), consider Alpine versions like node:18-alpine (≈40 MB) or python:3.11-slim. Alpine is a minimal Linux distribution.Example:
FROM node:18-alpine2. Combine RUN Commands
Each
RUN instruction creates a new layer. Combine them to reduce layers:RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*3. Multi‑Stage Builds
Use multiple
FROM statements to separate build-time dependencies from runtime. The final image only includes what you copy over.Example (Go app):
# Build stage
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
# Final stage
FROM alpine:latest
COPY --from=builder /app/myapp /usr/local/bin/
CMD ["myapp"]The final image is just Alpine + your binary, not the Go toolchain.4. Remove Unnecessary Files
Clean up package managers' caches after installing. For Alpine:
RUN apk add --no-cache curl && rm -rf /var/cache/apk/*5. Leverage .dockerignore
Exclude development files, logs, and version control directories to keep the build context lean (covered in previous chapter).
6. Use Specific Tags (Avoid Latest)
Using
:latest can lead to unexpected changes. Pin versions for reproducibility, e.g., node:18.16.0-alpine.Two Minute Drill
- Choose small base images like Alpine or slim variants.
- Combine
RUNcommands to reduce layers. - Use multi‑stage builds to exclude build tools from the final image.
- Clean package manager caches and remove temporary files.
- Always use a
.dockerignorefile.
Need more clarification?
Drop us an email at career@quipoinfotech.com
