dockerfile-optimization

Optimize Dockerfiles for smaller images, faster builds, better caching, and security. Use this skill when writing, reviewing, or debugging Dockerfiles.

16 stars

Best use case

dockerfile-optimization is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Optimize Dockerfiles for smaller images, faster builds, better caching, and security. Use this skill when writing, reviewing, or debugging Dockerfiles.

Teams using dockerfile-optimization should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/dockerfile-optimization/SKILL.md --create-dirs "https://raw.githubusercontent.com/diegosouzapw/awesome-omni-skill/main/skills/devops/dockerfile-optimization/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/dockerfile-optimization/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How dockerfile-optimization Compares

Feature / Agentdockerfile-optimizationStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Optimize Dockerfiles for smaller images, faster builds, better caching, and security. Use this skill when writing, reviewing, or debugging Dockerfiles.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Dockerfile Optimization

You are a Docker expert. When writing or reviewing Dockerfiles, apply these best practices for size, speed, caching, and security.

## Multi-Stage Build Pattern

Always use multi-stage builds for compiled languages:

```dockerfile
# Stage 1: Build
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production=false
COPY . .
RUN npm run build

# Stage 2: Production
FROM node:22-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY package*.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]
```

**Go example (even smaller — scratch base):**
```dockerfile
FROM golang:1.23-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /server ./cmd/server

FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /server /server
EXPOSE 8080
ENTRYPOINT ["/server"]
```

## Layer Caching Rules

Docker caches each layer. When a layer changes, all layers after it are rebuilt.

### Maximize Cache Hits
```dockerfile
# BAD — any source change invalidates npm install cache
COPY . .
RUN npm ci

# GOOD — only re-install if package.json changes
COPY package*.json ./
RUN npm ci
COPY . .
```

### Order: Least-changing → Most-changing
1. Base image (rarely changes)
2. System packages (rarely changes)
3. Dependency manifests (changes occasionally)
4. Dependency install (changes with manifests)
5. Source code (changes frequently)
6. Build step (changes with source)

## Image Size Optimization

### Use Alpine or Distroless Base Images
| Base | Size | Use When |
|------|------|----------|
| `scratch` | 0 MB | Static Go binaries |
| `distroless` | ~2 MB | Java, Go, Python without shell |
| `alpine` | ~7 MB | Need a shell, package manager |
| `slim` | ~80 MB | Need Debian packages |
| `full` | ~200+ MB | Development only, never production |

### Reduce Layer Count
```dockerfile
# BAD — 3 layers
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*

# GOOD — 1 layer, cleaned up
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl && \
    rm -rf /var/lib/apt/lists/*
```

### Use .dockerignore
Create a `.dockerignore` to exclude unnecessary files:
```
.git
node_modules
dist
*.md
.env*
.vscode
.idea
__pycache__
*.pyc
coverage
.next
```

## Security Best Practices

### Run as Non-Root
```dockerfile
# Create a non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

# Or use built-in user
USER node          # Node.js images
USER nobody:nobody # Generic
```

### Pin Versions
```dockerfile
# BAD — unpredictable
FROM node:latest
RUN apt-get install python3

# GOOD — reproducible
FROM node:22.12-alpine3.19
RUN apk add --no-cache python3=3.11.6-r0
```

### Don't Store Secrets in Images
```dockerfile
# BAD — secret baked into image
ENV API_KEY=sk-secret123
COPY .env .

# GOOD — pass at runtime
# docker run -e API_KEY=sk-secret123 myapp
# or use Docker secrets / mount
```

### Scan for Vulnerabilities
```bash
# Docker Scout
docker scout cves myimage:latest

# Trivy
trivy image myimage:latest

# Grype
grype myimage:latest
```

## Common Anti-Patterns

| Anti-Pattern | Problem | Fix |
|-------------|---------|-----|
| `FROM ubuntu:latest` | Large, unpredictable | Use `alpine` or `distroless`, pin version |
| `COPY . .` before `npm install` | Breaks caching | Copy manifests first, install, then copy source |
| `RUN apt-get update` alone | Stale package list cached | Combine with `install` in one `RUN` |
| `USER root` in production | Security risk | Create and switch to non-root user |
| No `.dockerignore` | Bloated context, slow builds | Add `.dockerignore` with exclusions |
| `ENTRYPOINT` without `exec` form | Signals not forwarded | Use `["executable", "arg"]` form |
| Not cleaning up in same layer | Larger image | Combine install + cleanup in one `RUN` |

## Health Checks
```dockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1
```

## Debugging Dockerfiles
```bash
# Build with progress output
docker build --progress=plain .

# Build up to a specific stage
docker build --target builder .

# Inspect image layers
docker history myimage:latest

# Run shell in failed build
docker run -it --entrypoint /bin/sh myimage:latest

# Check image size breakdown
docker image inspect myimage:latest --format='{{.Size}}'
dive myimage:latest  # Interactive layer explorer
```

Related Skills

database-cloud-optimization-cost-optimize

16
from diegosouzapw/awesome-omni-skill

You are a cloud cost optimization expert specializing in reducing infrastructure expenses while maintaining performance and reliability. Analyze cloud spending, identify savings opportunities, and ...

cost-optimization

16
from diegosouzapw/awesome-omni-skill

Optimize cloud costs through resource rightsizing, tagging strategies, reserved instances, and spending analysis. Use when reducing cloud expenses, analyzing infrastructure costs, or implementing c...

completion-marker-optimization

16
from diegosouzapw/awesome-omni-skill

Efficient completion marker generation to prevent timeouts and improve task completion reliability. Use when marking tasks complete to ensure atomic completion marker output. Prevents timeout issues and reduces completion time by 10-15 seconds.

web-performance-optimization

16
from diegosouzapw/awesome-omni-skill

Optimize website and web application performance including loading speed, Core Web Vitals, bundle size, caching strategies, and runtime performance

python-performance-optimization

16
from diegosouzapw/awesome-omni-skill

Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance.

performance-optimization

16
from diegosouzapw/awesome-omni-skill

Optimize Node.js application performance with caching, clustering, profiling, and monitoring techniques

freight-optimization

16
from diegosouzapw/awesome-omni-skill

When the user wants to optimize freight transportation, reduce shipping costs, or improve carrier selection. Also use when the user mentions "freight management," "carrier optimization," "mode selection," "LTL/TL optimization," "freight consolidation," "load planning," or "transportation procurement." For local delivery routes, see route-optimization. For last-mile, see last-mile-delivery.

database-optimization

16
from diegosouzapw/awesome-omni-skill

Use when optimizing database queries, indexes, N+1 problems, slow queries, or analyzing query performance. Triggers on keywords like "slow query", "N+1", "index", "query optimization", "database performance", "eager loading".

data-sql-optimization

16
from diegosouzapw/awesome-omni-skill

Production-grade SQL optimization for OLTP systems: EXPLAIN/plan analysis, balanced indexing, schema and query design, migrations, backup/recovery, HA, security, and safe performance tuning across PostgreSQL, MySQL, SQL Server, Oracle, SQLite.

context-optimization

16
from diegosouzapw/awesome-omni-skill

Apply compaction, masking, and caching strategies

bazel-build-optimization

16
from diegosouzapw/awesome-omni-skill

Optimize Bazel builds for large-scale monorepos. Use when configuring Bazel, implementing remote execution, or optimizing build performance for enterprise codebases.

app-store-optimization

16
from diegosouzapw/awesome-omni-skill

Complete App Store Optimization (ASO) toolkit for researching, optimizing, and tracking mobile app performance on Apple App Store and Google Play Store