Sobes.tech
Middle

What are the methods to reduce the size of a Docker image?

sobes.tech AI

Answer from AI

Main methods of reducing Docker image size:

  • Using minimal base images (e.g., alpine instead of ubuntu).
  • Multi-stage builds to include only necessary artifacts in the final image.
  • Cleaning cache and temporary files after installing packages (e.g., removing apt cache).
  • Combining RUN commands in the Dockerfile to reduce the number of layers.
  • Removing unnecessary dependencies and tools after building.

Example of a multi-stage build:

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

FROM alpine
COPY --from=builder /app/myapp /myapp
CMD ["/myapp"]