Sobes.tech
Senior

What practices exist for reducing the size of a Docker image?

sobes.tech AI

Answer from AI

Several practices are used to reduce the size of Docker images:

  • Using minimal base images, such as alpine instead of ubuntu.
  • Multi-stage builds, where the application is built in the first stages, and only the minimal runtime with the compiled binary remains in the final image.
  • Cleaning caches and temporary files after installing dependencies inside the Dockerfile.
  • Combining RUN commands to reduce the number of layers.
  • Using .dockerignore to exclude unnecessary files from the build context.

Example of a multi-stage Dockerfile for Go:

# Stage 1: Build
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp

# Stage 2: Minimal runtime
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]

This approach allows obtaining a compact image with a minimal set of files.

What practices exist for reducing the size of a… - sobes.tech