Middle
Dockerfile best practices. What do you use?
sobes.tech AI
Answer from AI
Main best practices for Dockerfile:
- Use minimal base images (e.g., Alpine) to reduce the final image size.
- Minimize the number of layers by combining RUN commands with &&.
- Cache dependencies separately from copying source code to speed up builds when only code changes.
- Use .dockerignore to exclude unnecessary files from the build context.
- Explicitly specify versions of packages and base images for reproducibility.
- Run containers as non-privileged users for security.
- Use multi-stage builds to separate the build stage from the final image to reduce size.
Example:
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o myapp
FROM alpine:latest
RUN adduser -D appuser
USER appuser
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]
This approach allows creating a compact and secure image with minimal layers.