daithanh-hua/optimized-dockerfiles icon
public
Published on 5/17/2025
Optimized Dockerfiles

Dockerfile Optimization Rule

Rules

For Dockerfile generation:

  1. Base Images: Use official, minimal base images (e.g., eclipse-temurin:17-jre-jammy for Java, alpine for utilities). Specify versions explicitly, avoid latest.
  2. Multi-Stage Builds: Leverage multi-stage builds, especially for compiled languages like Java, to keep the final image small. The build stage can use a JDK, the runtime stage only a JRE.
  3. Layer Minimization: Combine related RUN commands using && to reduce image layers.
  4. Cache Efficiency: Order commands from least to most frequently changing (e.g., copy dependency manifests and download dependencies before copying application code).
  5. Non-Root User: Create and run the application as a non-root user.
  6. Clean Up: Remove unnecessary files, package manager caches, and build artifacts in the same RUN instruction they were created.
  7. Healthchecks: Include a HEALTHCHECK instruction if applicable.