Skip to content

## ๐Ÿ“ Author

Birat Aryal โ€” birataryal.github.io
Created Date: 2025-06-18
Updated Date: Tuesday 17th June 2025 22:02:32
Website - birataryal.com.np
Repository - Birat Aryal
LinkedIn - Birat Aryal
DevSecOps Engineer | System Engineer | Cyber Security Analyst | Network Engineer

๐Ÿ›  Dockerfile Best Practices

Creating efficient, secure, and maintainable Dockerfiles is essential for performance and reproducibility. Below are recommended best practices:

1. Choose a Minimal Base Image

  • Use official minimal images like alpine or debian-slim when possible.

  • Avoid bloated base images to reduce image size and vulnerabilities.

Docker
FROM node:20-alpine

2. Leverage Layer Caching

  • Place commands that change least at the top of the Dockerfile.

  • Group RUN instructions to minimize image layers.

Docker
RUN apt-get update && \
    apt-get install -y curl && \
    rm -rf /var/lib/apt/lists/*

3. Use .dockerignore

  • Prevent unnecessary files from being copied into the image.
Text Only
node_modules
.git
*.log
Dockerfile

4. Avoid Installing Unnecessary Packages

  • Keep your image clean and secure.

  • Use --no-install-recommends with apt.

Docker
RUN apt-get install --no-install-recommends -y python3

5. Use Multi-Stage Builds

  • Compile or build in one stage, copy only whatโ€™s needed to final image.
Docker
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o main .

FROM alpine
COPY --from=builder /app/main /main
ENTRYPOINT ["/main"]

6. Set a Non-Root User

  • Reduce security risk by not running containers as root.
Docker
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

7. Use COPY Instead of ADD

  • COPY is more predictable. Use ADD only for auto-extracting archives or remote URLs.

8. Use Labels for Metadata

  • Add maintainer, version, description, etc.
Docker
LABEL maintainer="yourname@example.com"
LABEL version="1.0"
LABEL description="My awesome app"

9. Specify Exact Version Numbers

  • Helps avoid unexpected updates or changes.
Docker
RUN apt-get install -y nginx=1.18.*

10. Always Use CMD or ENTRYPOINT Correctly

  • CMD is the default command.

  • ENTRYPOINT is useful for scripts and passing arguments.

Docker
CMD ["nginx", "-g", "daemon off;"]