Junior — Middle
What approaches exist to reduce the size of the final Docker image?
sobes.tech AI
Answer from AI
The following approaches are used to reduce the size of the final Docker image:
- Using minimal base images: for example,
alpineinstead ofubuntuordebian. - Multi-stage builds: allows building the application in one image and copying only the necessary artifacts to the final image.
- Removing temporary files and caches: cleaning up packages, package manager caches, temporary files after installation.
- Combining RUN commands: reduces the number of image layers.
- Using
.dockerignore: excludes unnecessary files from the build context.
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"]
This approach results in a compact image containing only what is necessary to run the application.