How to reduce the size of a Docker image?.
sobes.tech AI
Answer from AI
To reduce the size of a Docker image, several approaches can be used:
-
Choosing a minimal base image: For example,
alpineinstead ofubuntuordebian. Alpine weighs about 5 MB. -
Multi-stage builds: Allow building the application in one image and copying only the necessary artifacts to the final image, excluding build tools.
-
Removing unnecessary files: Cleaning package manager caches (
apt-get clean, deleting temporary files) inside the Dockerfile. -
Combining RUN commands: Using
&&to combine commands reduces the number of image layers. -
Minimizing layers: Each layer adds size, so it's advisable to minimize the number of instructions that create layers.
-
Using
.dockerignore: Excludes unnecessary files from the build context.
Example of a multi-stage build for a Go application:
# Build stage
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
# Final image
FROM alpine
COPY --from=builder /app/myapp /usr/local/bin/myapp
CMD ["myapp"]
This approach results in a compact image without build tools.