Middle
Best practices for writing Dockerfile: how to make images small and secure?
sobes.tech AI
Answer from AI
To make Docker images small and secure, follow these practices:
- Use minimal base images, such as
alpineorscratch, to reduce size. - Remove temporary files and caches after installing packages (e.g.,
apt-get cleanand deleting/var/lib/apt/lists/*). - Minimize the number of layers by combining commands into a single
RUN. - Use multi-stage builds to include only necessary artifacts in the final image.
- Run containers with non-privileged users instead of root.
- Restrict file permissions and environment variables.
- Update base images and dependencies to patch known vulnerabilities.
Example of a multi-stage Dockerfile:
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
FROM alpine:latest
RUN adduser -D appuser
USER appuser
COPY --from=builder /app/myapp /usr/local/bin/myapp
CMD ["myapp"]
This approach reduces the size of the final image and enhances security by using a minimal environment and a non-privileged user.