Dockerfile Best Practices
Documentation:
Last updated
Documentation:
Last updated
Here:
Use official, minimal base images (e.g., alpine
, scratch
) to reduce attack surface and image size.
Pin versions for base images and dependencies to ensure reproducibility.
Leverage multi-stage builds to keep final images lean and free of build tools.
Order instructions for cache efficiency: copy dependency files and install dependencies before copying the rest of the source code.
Use .dockerignore to exclude unnecessary files (e.g., .git
, node_modules
, tests
).
Avoid running as root: create and use a non-root user for your application.
Set explicit ENTRYPOINT and CMD for clarity and flexibility.
Add HEALTHCHECK to monitor container health.
Scan images for vulnerabilities (e.g., with Trivy, Snyk, or docker scan
).
Do not store secrets in Dockerfiles; use environment variables or secret managers.
Use semantic version tags for images (e.g., myapp:1.2.3
), not latest
in production.
Store Dockerfiles in version control and automate builds with CI/CD (GitHub Actions, Azure Pipelines, GitLab CI).
Clean up unused images and containers regularly (docker system prune
).
Large images due to unnecessary files or lack of multi-stage builds
Running as root (security risk)
Not pinning versions (leads to unpredictable builds)
Hardcoding secrets in Dockerfiles
Not using .dockerignore
, causing slow builds