## ๐ 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
alpineordebian-slimwhen possible. -
Avoid bloated base images to reduce image size and vulnerabilities.
FROM node:20-alpine
2. Leverage Layer Caching
-
Place commands that change least at the top of the Dockerfile.
-
Group
RUNinstructions to minimize image layers.
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.
node_modules
.git
*.log
Dockerfile
4. Avoid Installing Unnecessary Packages
-
Keep your image clean and secure.
-
Use
--no-install-recommendswithapt.
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.
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.
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
7. Use COPY Instead of ADD
COPYis more predictable. UseADDonly for auto-extracting archives or remote URLs.
8. Use Labels for Metadata
- Add maintainer, version, description, etc.
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.
RUN apt-get install -y nginx=1.18.*
10. Always Use CMD or ENTRYPOINT Correctly
-
CMDis the default command. -
ENTRYPOINTis useful for scripts and passing arguments.
CMD ["nginx", "-g", "daemon off;"]