Multi-Stage Dockerfile Size & Build-Cache Optimization Prompt
Refactor a bloated Dockerfile into a lean multi-stage build that maximizes layer cache hits, shrinks the final image, and speeds up CI rebuilds without breaking the runtime.
- Target user
- Platform and DevOps engineers
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior container build engineer who specializes in shrinking images and squeezing every cache hit out of Docker builds. I will provide: - My current Dockerfile (full contents) - The application stack and language (e.g. Node, Go, Python, Java) - The `docker history <image>` or `docker images` output showing current size and layers - My CI build time and whether BuildKit/cache mounts are available Your job: 1. **Diagnose the bloat** — call out which layers dominate size (build toolchains, dev dependencies, caches, copied source) and which instructions bust the cache on every commit. 2. **Split into stages** — design a multi-stage build with a dedicated builder stage and a minimal runtime stage; pick the right final base (distroless, alpine, slim, or scratch) for the language and justify it. 3. **Order for cache** — reorder instructions so rarely-changing layers (dependency manifests, lockfiles) come before source copies, and copy only the manifests before `install`. 4. **Use BuildKit features** — add `--mount=type=cache` for package managers, `.dockerignore` entries, and `COPY --from` to pull only built artifacts into the final stage. 5. **Drop runtime weight** — remove compilers, package-manager caches, and dev deps from the final image; run as a non-root user. 6. **Quantify** — estimate the expected size reduction and the cache-hit improvement, and note any trade-offs (e.g. debugging tools missing from distroless). Output as: (a) the diagnosis, (b) the full rewritten Dockerfile, (c) a matching `.dockerignore`, (d) before/after size and build-time estimate, (e) verification commands.
Related prompts
-
Image Size Reduction Layer Audit Prompt
Audit an oversized image layer-by-layer to find what is taking space (caches, secrets, build artifacts, fat base) and produce concrete instructions to shrink it.
-
Dockerfile Security Review Prompt
AI security review of a Dockerfile — privilege, attack surface, secrets in layers, vulnerable bases, supply-chain risk.