# Dockerfile Doctor

> Smaller, faster, safer images.

Dockerfile Doctor is an agent skill from the DevOps & Cloud collection on ProSkills, for Claude Code, Cursor, Codex and Gemini CLI. Your agent loads it when the user writes or fixes a Dockerfile.

## Facts

- Price: Free (MIT, no account)
- Collection: [DevOps & Cloud](https://proskills.dev/library/devops-cloud)
- Scan score: 100/100 (grade A) on the ProSkills scanner: spec, token efficiency, clarity and security
- Context cost: about 1,737 tokens when it triggers
- Files: 3
- Version: 1.0.0 (updated 2026-10-16)
- Rules: 5
- Page: https://proskills.dev/skills/dockerfile-doctor

## Install

```bash
npx proskills-cli add dockerfile-doctor
```

It detects your agent; add `--agent all` to install for every agent. Or copy the skill folder (the one holding SKILL.md) into the directory your agent reads:

| Agent | This project | Every project |
|---|---|---|
| Claude Code | `.claude/skills/` | `~/.claude/skills/` |
| Cursor | `.agents/skills/ (or .cursor/skills/)` | `~/.cursor/skills/` |
| Codex | `.agents/skills/` | `~/.agents/skills/` |
| Gemini CLI | `.agents/skills/ (or .gemini/skills/)` | `~/.gemini/skills/` |

Or with the open skills CLI, which reads this site's agent-skills discovery index:

```bash
npx skills add https://proskills.dev --skill dockerfile-doctor
```

## SKILL.md

````markdown
---
name: dockerfile-doctor
description: "Use when the user says 'review my Dockerfile', 'my docker image is huge', 'docker build is slow', 'optimize this Dockerfile', 'make this image production ready', 'add a multi-stage build', 'run as non-root', or 'why is the cache busting'. Audits a Dockerfile and .dockerignore, rewrites them with multi-stage builds, lockfile-first layer order, pinned bases, a non-root user, no secrets in layers, a healthcheck and correct signal handling, and reports image size and build time before and after. Reads profile.md for cloud, runtime, CI and environments; per-language templates and findings checklist in templates.md."
---

# Dockerfile Doctor

Audit a Dockerfile the way a platform engineer would: find what makes the image big, slow to build, insecure or hard to stop, fix it, and prove the improvement with numbers. Do not rewrite for style; every change must buy size, build time, safety or reproducibility.

## Before you start

Read `profile.md` in this folder:

| profile.md line | Use |
|---|---|
| **Cloud** | Registry and platform quirks (ECR, Artifact Registry, ACR, Fly, Render) and the CPU architecture to build for. |
| **Runtime** | Kubernetes: add probes in the manifest, not only `HEALTHCHECK`, and set `runAsNonRoot`. Containers (ECS / Cloud Run): the platform health check replaces `HEALTHCHECK`; listen on `$PORT` for Cloud Run. Serverless: image must match the Lambda base and handler contract. VMs: keep `HEALTHCHECK`. |
| **CI** | Where the build runs; use its cache backend (`type=gha`, registry cache) in the build command you suggest. |
| **Environments** | Which environments build the image; one image per commit, configuration injected at run time, never baked per environment. |

If a line says "not set", ask once, write it into profile.md, continue. Open `templates.md` for the language template and the findings checklist.

## Workflow

1. **Read everything the build reads.** The Dockerfile, `.dockerignore`, the lockfile and manifest, any compose file or CI build step. Identify language, framework, entrypoint, port and what the app needs at run time versus build time.
2. **Measure the baseline.** If Docker is available and the user agrees to a local build: `docker build -t app:before .` twice (cold with `--no-cache`, then warm after touching one source file), `docker image ls app:before`, `docker history app:before`. Record size and seconds. If you cannot build, say "not measured" and estimate nothing.
3. **Audit** against the findings checklist in `templates.md`. Label each finding high, medium or low (table below).
4. **Rewrite** with the smallest set of changes that fixes the highs and mediums. Keep the app's existing behaviour: same port, same command, same env var names.
5. **Add or fix `.dockerignore`** before touching layers; a missing one is the most common cause of cache busting and leaked files.
6. **Rebuild and compare.** Same two builds, same machine. Report size and times as before, after, delta. Run the container and confirm it starts, answers its health check and stops within seconds on `docker stop`.
7. **Hand over** the diff and the commands. Do not push, tag or publish an image, and do not touch a registry or cluster without asking.

## Severity

| Severity | Examples |
|---|---|
| High | Secret or token in a layer or `ARG`; runs as root with no reason; `latest` or unpinned base in production; `curl` piped to a shell during build; whole repo copied before dependency install on every change |
| Medium | No multi-stage (compilers and dev dependencies shipped); shell-form `CMD` so signals are lost; no `.dockerignore`; no healthcheck; non-reproducible install (`npm install`, unpinned `pip`) |
| Low | Many small `RUN` layers; missing `--no-install-recommends`; apt/apk caches left behind; no `LABEL`s |

## Base image choice

| Need | Choose | Why |
|---|---|---|
| Compiled static binary (Go, Rust) | `scratch` or distroless `static` | Smallest; no shell to exploit |
| Node, Python, Java app | Distroless runtime or `-slim` | Fewer packages, fewer CVEs; debug with an ephemeral debug container |
| Needs glibc and system libs | `-slim` (Debian) | Alpine's musl breaks some wheels and native modules |
| Needs a shell for debugging in production | `-slim` or Alpine | Distroless has none |

Pin by exact tag plus digest in production: `node:22.11.0-slim@sha256:<digest>`. Resolve the digest with `docker buildx imagetools inspect <tag>` and let Dependabot or Renovate bump it. Never ship `latest`.

## Worked example: Node service

Before: 1.1 GB image, 4 min rebuild on any code edit.

```dockerfile
FROM node:latest
WORKDIR /app
COPY . .
RUN npm install
ENV NPM_TOKEN=abc123
CMD npm start
```

Findings: unpinned base (high), `COPY .` before install busts the dependency cache on every edit (high), token in `ENV` is readable from the image (high), runs as root (high), `npm install` is not reproducible (medium), shell-form `CMD` swallows SIGTERM (medium), dev dependencies and source shipped (medium).

After:

```dockerfile
# syntax=docker/dockerfile:1.7
FROM node:22.11.0-slim@sha256:<digest> AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    --mount=type=secret,id=npm_token \
    NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci

FROM deps AS build
COPY . .
RUN npm run build && npm prune --omit=dev

FROM node:22.11.0-slim@sha256:<digest>
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
  CMD node -e "fetch('http://127.0.0.1:3000/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "dist/server.js"]
```

Build with `docker build --secret id=npm_token,env=NPM_TOKEN -t app:after .`. Result to report: 1.1 GB to about 190 MB, warm rebuild after a one-line source edit from about 4 min to about 20 s because the `npm ci` layer is reused. Report your measured numbers, not these.

## Rules

- One concern per change, each tied to a finding. No drive-by reformatting.
- Order layers from least to most frequently changing: base, system packages, lockfile copy, install, source copy, build.
- Secrets only through `--mount=type=secret` or the runtime environment. `ARG` and `ENV` values are visible in `docker history`. If a secret was ever in a layer or the git history, tell the user to rotate it.
- Exec-form `CMD`/`ENTRYPOINT` (JSON array). If the app is not PID 1 safe (spawns children), add `tini` or `docker run --init`.
- One process per container. Move cron, sidecars and supervisors out.
- Package installs: `apt-get update`, `apt-get install -y --no-install-recommends`, then delete the apt lists, all in one `RUN`; `apk add --no-cache`.
- Do not change the app's code, port or command to suit the Dockerfile without saying so.
- Ask before pushing an image, pulling private bases that need credentials, or changing registry settings.

## Output

````markdown
## Dockerfile audit: <service>
**Measured:** before <size>, cold <s>s, warm <s>s | after <size>, cold <s>s, warm <s>s  (or "not measured: <why>")

### Findings
| # | Severity | Line | Problem | Fix |
|---|---|---|---|---|

### Rewritten Dockerfile
```dockerfile
...
```

### .dockerignore
```
...
```

### Verify
<build command with cache flags, run command, health check, `docker stop` timing>

### Left alone on purpose
<things that look odd but are intentional, and open questions>
````
````

## templates.md

````markdown
# Templates and findings checklist

Open the section for the project's language, then run the checklist against the Dockerfile. Contents: Findings checklist, .dockerignore, Node, Python, Go, Java.

## Findings checklist

| # | Check | Look for | Fix |
|---|---|---|---|
| 1 | Base pinned | `latest`, no tag, floating major | Exact tag plus `@sha256:<digest>` |
| 2 | Multi-stage | Compilers, `-dev` packages, dev dependencies in the final image | Build stage and a minimal runtime stage |
| 3 | Layer order | `COPY . .` above the install step | Copy manifest and lockfile, install, then copy source |
| 4 | `.dockerignore` | Missing, or lacks `.git`, `node_modules`, `.env*`, build output | Add it (below) |
| 5 | Reproducible install | `npm install`, `pip install` without hashes, `apt-get install` of unpinned critical tools | `npm ci`, `pip install --require-hashes -r`, `go mod download`, lockfiles committed |
| 6 | Secrets | `ARG`/`ENV` holding tokens, `COPY` of credential files, `.env` in context | `RUN --mount=type=secret,id=...`; inject at run time |
| 7 | User | No `USER`, or `USER root` at the end | Create or use a non-root user with a fixed UID (for example 10001) and `--chown` on copies |
| 8 | Signals | Shell-form `CMD npm start` or `CMD ./run.sh` | Exec form; `exec` in wrapper scripts; `tini` as init if children are spawned |
| 9 | Health | No `HEALTHCHECK` (when the platform does not provide one) | Cheap local probe without extra tools; platform probes for Kubernetes and cloud runtimes |
| 10 | Single process | `supervisord`, `cron` plus app in one image | Split into separate containers |
| 11 | Package caches | apt lists, apk cache, pip cache, npm cache in layers | Clean in the same `RUN`, or use cache mounts |
| 12 | Architecture | Building amd64 on arm laptop for an arm cloud, or the reverse | `--platform` set deliberately; multi-arch only if needed |
| 13 | Writable paths | App writes to the image filesystem | Writable volume or `tmpfs`; read-only root filesystem where possible |
| 14 | Build args | Arbitrary `ARG` changing the cache every build (timestamps, commit sha above install) | Move volatile `ARG`s below the install layers |

## .dockerignore

```
.git
.gitignore
node_modules
**/__pycache__
*.pyc
.venv
dist
build
target
coverage
.env
.env.*
*.pem
*.key
Dockerfile*
docker-compose*.yml
.github
.vscode
.idea
*.log
```

Remove `dist`/`build`/`target` from the list if the Dockerfile copies prebuilt output. Keep lockfiles out of the ignore list.

## Node

```dockerfile
# syntax=docker/dockerfile:1.7
FROM node:22.11.0-slim@sha256:<digest> AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

FROM deps AS build
COPY . .
RUN npm run build && npm prune --omit=dev

FROM gcr.io/distroless/nodejs22-debian12:nonroot
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --from=build --chown=nonroot:nonroot /app/dist ./dist
EXPOSE 3000
CMD ["dist/server.js"]
```

Distroless Node images set the entrypoint to `node`, so `CMD` is the script. Pin the distroless tag to a digest. pnpm: `corepack enable` and `pnpm install --frozen-lockfile`. Next.js: use `output: "standalone"` and copy `.next/standalone` and `.next/static`.

## Python

```dockerfile
# syntax=docker/dockerfile:1.7
FROM python:3.12.7-slim@sha256:<digest> AS build
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --require-hashes -r requirements.txt
COPY . .

FROM python:3.12.7-slim@sha256:<digest>
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PATH="/opt/venv/bin:$PATH"
RUN useradd --uid 10001 --create-home app
COPY --from=build /opt/venv /opt/venv
WORKDIR /app
COPY --from=build --chown=app:app /app .
USER app
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app.wsgi:application"]
```

Generate hashes with `pip-compile --generate-hashes` (pip-tools) or `uv pip compile --generate-hashes`. Native wheels needing a compiler belong in the build stage only. Alpine is a poor default for Python because many wheels are glibc-only and builds fall back to slow source compiles.

## Go

```dockerfile
# syntax=docker/dockerfile:1.7
FROM golang:1.23.2@sha256:<digest> AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/app ./cmd/app

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
EXPOSE 8080
ENTRYPOINT ["/app"]
```

Typical result: 800 MB builder to 10-20 MB final. `CGO_ENABLED=0` is required for `static`; if cgo is needed use `distroless/base` instead. CA certificates and tzdata ship in distroless static; with `scratch`, copy them from the build stage.

## Java

```dockerfile
# syntax=docker/dockerfile:1.7
FROM eclipse-temurin:21.0.5_11-jdk@sha256:<digest> AS build
WORKDIR /src
COPY pom.xml .
COPY .mvn .mvn
COPY mvnw .
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B -q dependency:go-offline
COPY src src
RUN --mount=type=cache,target=/root/.m2 ./mvnw -B -q package -DskipTests

FROM eclipse-temurin:21.0.5_11-jre@sha256:<digest>
RUN useradd --uid 10001 app
WORKDIR /app
COPY --from=build --chown=app:app /src/target/app.jar app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
```

`MaxRAMPercentage` makes the JVM respect container memory limits. Gradle: copy `build.gradle*`, `settings.gradle*` and the wrapper first, run `./gradlew dependencies`, then copy `src`. Spring Boot layered jars (`java -Djarmode=layertools -jar app.jar extract`) split dependencies from application code for better layer reuse. Run tests in CI, not in the image build.
````

## Changelog

- v1.0.0 (2026-10-16): First versioned release: Smaller, faster, safer images. Scanned 100/100 before release.

## Related skills

- [CI Pipeline Builder](https://proskills.dev/skills/ci-pipeline-builder): Fast, locked-down CI. GitHub Actions first. ($12)
- [Terraform Reviewer](https://proskills.dev/skills/terraform-reviewer): Reads the plan before it destroys something. ($12)
- [K8s Manifest Review](https://proskills.dev/skills/k8s-manifest-review): Probes, limits and security contexts done right. ($9)
- [Incident Commander](https://proskills.dev/skills/incident-commander): Mitigate first. Then a blameless postmortem. ($12)
- [Cost Cutter](https://proskills.dev/skills/cost-cutter): A cloud bill audit with dollar figures. ($12)
