/devops-skills:dockerfile-generatorfrom devops-skills
Generates production-ready Dockerfiles with multi-stage builds, security hardening, and layer optimization. Supports Node.js, Python, Go, and Java with automatic validation.
Ships in devops-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
This skill provides a comprehensive workflow for generating production-ready Dockerfiles with security, optimization, and best practices built-in. Generates multi-stage builds, security-hardened configurations, and optimized layer structures with automatic validation and iterative error fixing.
Key Features:
Invoke this skill when:
Follow this workflow when generating Dockerfiles. Adapt based on user needs:
Objective: Understand what needs to be containerized and gather all necessary information.
Information to Collect:
Application Details:
Dependencies:
Application Configuration:
Build Requirements:
Production Requirements:
Use AskUserQuestion if information is missing or unclear.
Example Questions:
- What programming language and version is your application using?
- What is the main entry point to run your application?
- Does your application expose any ports? If so, which ones?
- Do you need any system dependencies beyond the base language runtime?
- Does your application need a health check endpoint?
Objective: Research framework-specific containerization patterns and best practices.
When to Perform This Stage:
Research Process:
Try context7 MCP first (preferred):
Use mcp__context7__resolve-library-id with the framework name
Examples:
- "next.js" for Next.js applications
- "django" for Django applications
- "fastapi" for FastAPI applications
- "spring-boot" for Spring Boot applications
- "express" for Express.js applications
Then use mcp__context7__get-library-docs with:
- context7CompatibleLibraryID from resolve step
- topic: "docker deployment production build"
- page: 1 (fetch additional pages if needed)
Fallback to WebSearch if context7 fails:
Search query pattern:
"<framework>" "<version>" dockerfile best practices production 2025
Examples:
- "Next.js 14 dockerfile best practices production 2025"
- "FastAPI dockerfile best practices production 2025"
- "Spring Boot 3 dockerfile best practices production 2025"
Extract key information:
Objective: Create a production-ready, multi-stage Dockerfile following best practices.
Core Principles:
Multi-Stage Builds (REQUIRED for compiled languages, RECOMMENDED for all):
Security Hardening (REQUIRED):
Layer Optimization (REQUIRED):
Production Readiness (REQUIRED):
Language-Specific Templates:
# syntax=docker/dockerfile:1
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
# Copy dependency files for caching
COPY package*.json ./
# Use npm ci for deterministic builds
RUN npm ci --only=production && \
npm cache clean --force
# Copy application code
COPY . .
# Build application (if needed)
# RUN npm run build
# Production stage
FROM node:20-alpine AS production
WORKDIR /app
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
# Copy dependencies and application from builder
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --chown=nodejs:nodejs . .
# Switch to non-root user
USER nodejs
# Expose port
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"
# Start application
CMD ["node", "index.js"]
# syntax=docker/dockerfile:1
# Build stage
FROM python:3.12-slim AS builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
&& rm -rf /var/lib/apt/lists/*
# Copy dependency files
COPY requirements.txt .
# Install Python dependencies
RUN pip install --no-cache-dir --user -r requirements.txt
# Production stage
FROM python:3.12-slim AS production
WORKDIR /app
# Create non-root user
RUN useradd -m -u 1001 appuser
# Copy dependencies from builder
COPY --from=builder /root/.local /home/appuser/.local
# Copy application code
COPY --chown=appuser:appuser . .
# Update PATH
ENV PATH=/home/appuser/.local/bin:$PATH
# Switch to non-root user
USER appuser
# Expose port
EXPOSE 8000
# Health check (adjust endpoint as needed)
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health').read()" || exit 1
# Start application
CMD ["python", "app.py"]
# syntax=docker/dockerfile:1
# Build stage
FROM golang:1.21-alpine AS builder
WORKDIR /app
# Copy go mod files
COPY go.mod go.sum ./
RUN go mod download
# Copy source code
COPY . .
# Build the application
RUN CGO_ENABLED=0 GOOS=linux go build -a -ldflags="-s -w" -o main .
# Production stage (using distroless for minimal image)
FROM gcr.io/distroless/static-debian12 AS production
WORKDIR /
# Copy binary from builder
COPY --from=builder /app/main /main
# Expose port
EXPOSE 8080
# Health check (distroless doesn't have shell, so this is commented)
# HEALTHCHECK not supported in distroless without shell
# Switch to non-root user (distroless runs as nonroot by default)
USER nonroot:nonroot
# Start application
ENTRYPOINT ["/main"]
# syntax=docker/dockerfile:1
# Build stage
FROM eclipse-temurin:21-jdk-jammy AS builder
WORKDIR /app
# Copy Maven wrapper and pom.xml
COPY mvnw pom.xml ./
COPY .mvn .mvn
# Download dependencies (cached layer)
RUN ./mvnw dependency:go-offline
# Copy source code
COPY src ./src
# Build application
RUN ./mvnw clean package -DskipTests && \
mv target/*.jar target/app.jar
# Production stage (using JRE instead of JDK)
FROM eclipse-temurin:21-jre-jammy AS production
WORKDIR /app
# Create non-root user
RUN useradd -m -u 1001 appuser
# Copy JAR from builder
COPY --from=builder --chown=appuser:appuser /app/target/app.jar ./app.jar
# Switch to non-root user
USER appuser
# Expose port
EXPOSE 8080
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD curl -f http://localhost:8080/actuator/health || exit 1
# Start application
ENTRYPOINT ["java", "-jar", "app.jar"]
Selection Logic:
Always Include:
# syntax=docker/dockerfile:1Objective: Create comprehensive .dockerignore to reduce build context and prevent secret leaks.
Always create .dockerignore with generated Dockerfile.
Standard .dockerignore Template:
# Git
.git
.gitignore
.gitattributes
# CI/CD
.github
.gitlab-ci.yml
.travis.yml
.circleci
# Documentation
README.md
CHANGELOG.md
CONTRIBUTING.md
LICENSE
*.md
docs/
# Docker
Dockerfile*
docker-compose*.yml
.dockerignore
# Environment
.env
.env.*
*.local
# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Dependencies (language-specific - add as needed)
node_modules/
__pycache__/
*.pyc
*.pyo
*.pyd
.Python
venv/
.venv/
target/
*.class
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# Testing
coverage/
.coverage
*.cover
.pytest_cache/
.tox/
test-results/
# Build artifacts
dist/
build/
*.egg-info/
Customize based on language:
node_modules/, npm-debug.log, yarn-error.log__pycache__/, *.pyc, .venv/, .pytest_cache/vendor/, *.exe, *.testtarget/, *.class, *.jar (except final artifact)Objective: Ensure generated Dockerfile follows best practices and has no issues.
REQUIRED: Always validate after generation.
Validation Process:
Invoke devops-skills:dockerfile-validator skill:
Use the Skill tool to invoke devops-skills:dockerfile-validator
This will run:
- hadolint (syntax and best practices)
- Checkov (security scanning)
- Custom validation (layer optimization, etc.)
Parse validation results:
Expected validation output:
[1/4] Syntax Validation (hadolint)
[2/4] Security Scan (Checkov)
[3/4] Best Practices Validation
[4/4] Optimization Analysis
Objective: Fix any validation errors and re-validate.
REQUIRED: Iterate at least ONCE if validation finds errors.
Iteration Process:
If validation finds errors:
If validation finds warnings:
Common fixes:
Example iteration:
Iteration 1:
- Error: DL3006 - Missing version tag
- Fix: Change FROM node:alpine to FROM node:20-alpine
- Re-validate
Iteration 2:
- Warning: DL3059 - Multiple consecutive RUN commands
- Fix: Combine RUN commands with &&
- Re-validate
Iteration 3:
- All checks passed ✓
Objective: Provide comprehensive summary and next steps.
Deliverables:
Generated Files:
Validation Summary:
Usage Instructions:
# Build the image
docker build -t myapp:1.0 .
# Run the container
docker run -p 3000:3000 myapp:1.0
# Test health check (if applicable)
curl http://localhost:3000/health
Optimization Metrics (REQUIRED - provide explicit estimates):
Always include a summary like this:
## Optimization Metrics
| Metric | Estimate |
|--------|----------|
| Image Size | ~150MB (vs ~500MB without multi-stage, 70% reduction) |
| Build Cache | Layer caching enabled for dependencies |
| Security | Non-root user, minimal base image, no secrets |
Language-specific size estimates:
Next Steps (REQUIRED - always include as bulleted list):
Always provide explicit next steps:
## Next Steps
- [ ] Test the build locally: `docker build -t myapp:1.0 .`
- [ ] Run and verify the container works as expected
- [ ] Update CI/CD pipeline to use the new Dockerfile
- [ ] Consider BuildKit cache mounts for faster builds (see Modern Docker Features)
- [ ] Set up automated vulnerability scanning with `docker scout` or `trivy`
- [ ] Add to container registry and deploy
The scripts/ directory contains standalone bash scripts for manual Dockerfile generation outside of this skill:
generate_nodejs.sh - CLI tool for Node.js Dockerfilesgenerate_python.sh - CLI tool for Python Dockerfilesgenerate_golang.sh - CLI tool for Go Dockerfilesgenerate_java.sh - CLI tool for Java Dockerfilesgenerate_dockerignore.sh - CLI tool for .dockerignore generationPurpose: These scripts are reference implementations and manual tools for users who want to generate Dockerfiles via command line without using Claude Code. They demonstrate the same best practices embedded in this skill.
When using this skill: Claude generates Dockerfiles directly using the templates and patterns documented in this skill.md, rather than invoking these scripts. The templates in this document are the authoritative source.
Script usage example:
# Manual Dockerfile generation
cd .claude/skills/dockerfile-generator/scripts
./generate_nodejs.sh --version 20 --port 3000 --output Dockerfile
Use Specific Tags:
# Bad
FROM node:alpine
# Good
FROM node:20-alpine
# Better (with digest for reproducibility)
FROM node:20-alpine@sha256:abc123...
Run as Non-Root:
# Create user
RUN addgroup -g 1001 -S appgroup && \
adduser -S appuser -u 1001 -G appgroup
# Switch to user before CMD
USER appuser
Use Minimal Base Images:
Never Hardcode Secrets:
# Bad
ENV API_KEY=secret123
# Good - use build secrets
# docker build --secret id=api_key,src=.env
RUN --mount=type=secret,id=api_key \
API_KEY=$(cat /run/secrets/api_key) ./configure
Layer Caching:
# Copy dependency files first
COPY package.json package-lock.json ./
RUN npm ci
# Copy application code last
COPY . .
Combine RUN Commands:
# Bad (creates 3 layers)
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
# Good (creates 1 layer)
RUN apt-get update && \
apt-get install -y --no-install-recommends curl && \
rm -rf /var/lib/apt/lists/*
Multi-Stage Builds:
# Build stage - can be large
FROM node:20 AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build
# Production stage - minimal
FROM node:20-alpine
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/index.js"]
Health Checks:
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
Proper Signals:
# Use exec form for proper signal handling
CMD ["node", "server.js"] # Good
CMD node server.js # Bad (no signal forwarding)
Metadata:
LABEL maintainer="[email protected]" \
version="1.0.0" \
description="My application"
# syntax=docker/dockerfile:1
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -g 1001 -S nodejs && \
adduser -S nextjs -u 1001
COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
USER nextjs
EXPOSE 3000
CMD ["npm", "start"]
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS builder
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends gcc && \
rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
FROM python:3.12-slim
WORKDIR /app
RUN useradd -m -u 1001 appuser
COPY --from=builder /root/.local /home/appuser/.local
COPY --chown=appuser:appuser . .
ENV PATH=/home/appuser/.local/bin:$PATH
USER appuser
EXPOSE 8000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# syntax=docker/dockerfile:1
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /bin/app
FROM scratch
COPY --from=builder /bin/app /app
ENTRYPOINT ["/app"]
Use Case: Build images that work on both AMD64 and ARM64 architectures (e.g., x86 servers and Apple Silicon Macs).
Enable BuildX:
# BuildX is included in Docker Desktop by default
# For Linux, ensure BuildX is installed
docker buildx version
Create Multi-Platform Images:
# Build for multiple platforms
docker buildx build \
--platform linux/amd64,linux/arm64 \
-t myapp:latest \
--push \
.
# Build and load for current platform (testing)
docker buildx build \
--platform linux/amd64 \
-t myapp:latest \
--load \
.
Dockerfile Considerations:
# Most Dockerfiles work across platforms automatically
# Use platform-specific base images when needed
FROM --platform=$BUILDPLATFORM node:20-alpine AS builder
# Access build arguments for platform info
ARG TARGETPLATFORM
ARG BUILDPLATFORM
RUN echo "Building on $BUILDPLATFORM for $TARGETPLATFORM"
When to Use:
Use Case: Generate SBOM for supply chain security and compliance (increasingly required in 2025).
Generate SBOM During Build:
# Generate SBOM with BuildKit (Docker 24.0+)
docker buildx build \
--sbom=true \
-t myapp:latest \
.
# SBOM is attached as attestation to the image
# View SBOM
docker buildx imagetools inspect myapp:latest --format "{{ json .SBOM }}"
Generate SBOM from Existing Image:
# Using Syft
syft myapp:latest -o json > sbom.json
# Using Docker Scout
docker scout sbom myapp:latest
SBOM Benefits:
Integration with CI/CD:
# GitHub Actions example
- name: Build with SBOM
run: |
docker buildx build \
--sbom=true \
--provenance=true \
-t myapp:latest \
--push \
.
Use Case: Dramatically faster builds by persisting package manager caches across builds.
Already covered in detail in references/optimization_patterns.md (lines 98-125).
Quick reference:
# syntax=docker/dockerfile:1
# NPM cache mount (30-50% faster builds)
RUN --mount=type=cache,target=/root/.npm \
npm ci
# Go module cache
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download
# Pip cache
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
Missing dependency files:
Unknown framework:
Validation failures:
This skill works well in combination with:
This skill is based on comprehensive research from authoritative sources:
Official Docker Documentation:
Security Guidelines:
Optimization Resources:
examples/example.dockerignore (opens in a new tab)examples/golang-distroless.Dockerfile (opens in a new tab)examples/java-springboot.Dockerfile (opens in a new tab)examples/nextjs-production.Dockerfile (opens in a new tab)examples/nodejs-multistage.Dockerfile (opens in a new tab)examples/python-fastapi.Dockerfile (opens in a new tab)examples/test-nodejs.Dockerfile (opens in a new tab)references/language_specific_guides.md (opens in a new tab)references/multistage_builds.md (opens in a new tab)references/optimization_patterns.md (opens in a new tab)references/security_best_practices.md (opens in a new tab)scripts/generate_dockerignore.sh (opens in a new tab)scripts/generate_golang.sh (opens in a new tab)scripts/generate_java.sh (opens in a new tab)scripts/generate_nodejs.sh (opens in a new tab)scripts/generate_python.sh (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (gitjfmd/ansible-skills) — no native marketplace selected
npx claudepluginhub p/gitjfmd-devops-skills-devops-skills-plugin31 skills in this plugin
/ansible-generatorComprehensive toolkit for generating best practice Ansible playbooks, roles, tasks, and inventory files./ansible-validatorComprehensive toolkit for validating, linting, testing, and automating Ansible playbooks, roles, and collections. Use this skill when working with Ansible files (.yml, .yaml playbooks, roles, inventories), validating automation code, debugging playbook execution, performing dry-run testing with check mode, or working with custom modules and collections./azure-pipelines-generatorComprehensive toolkit for generating best practice Azure DevOps Pipelines following current standards and conventions. Use this skill when creating new Azure Pipelines, implementing CI/CD workflows, or building deployment pipelines.Other plugins' skills for the same job