
docker-dockerfile
Expert guidance for Dockerfile authoring — the complete reference for writing production-grade Dockerfiles. Covers every instruction (FROM/RUN/COPY/ADD/ENV/ARG/WORKDIR/EXPOSE/CMD/ENTRYPOINT/USER/HEALTHCHECK/SHELL) with syntax, best practices, and common mistakes. Includes multi-stage build patterns (build+scratch, build+alpine, builder pattern), layer caching optimization strategies, .dockerignore rules, and language-specific production templates (Go/Rust/Java Spring Boot/Python FastAPI/Node.js Express/TypeScript). Use when the user asks about Dockerfile, how to write a Dockerfile, multi-stage build, layer optimization, or needs Dockerfile examples for a specific language. 使用场景:Dockerfile 编写、怎么写 Dockerfile、Dockerfile 指令、多阶段构建、multi-stage、层优化、layer cache、Dockerfile 模板.
- Installs
- 122
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/full-stack-skills/docker-skills --skill docker-dockerfile- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads docker-dockerfile automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Dockerfile — 完整编写指南
Expert reference for writing production-grade Dockerfiles. Every instruction, every pattern, every optimization.
When to Use
ALWAYS use this skill when the user mentions:
- "Dockerfile", "怎么写 Dockerfile", "Dockerfile 指令"
- "多阶段构建", "multi-stage build"
- "Dockerfile 层优化", "layer caching"
- "Dockerfile 模板", language-specific: "Go Dockerfile", "Java Dockerfile", "Python Dockerfile"
- Need to create or optimize a Dockerfile
- "Dockerfile best practices"
Instruction Reference
FROM — Base Image
FROM <image>[:<tag>] [AS <stage-name>]
FROM alpine:3.20 # Tag
FROM alpine:3.20@sha256:abc123...def456 # Digest (production!)
FROM golang:1.22-alpine AS builder # Named stage
FROM scratch # Empty image (for static binaries)
| Best Practice | Why |
|---|---|
| Pin digest for production | Tags are mutable; digest is immutable |
| Use Alpine/slim variants | Smaller attack surface, smaller image |
FROM scratch for Go/Rust | Static binaries need nothing else |
RUN — Execute Commands
# ✅ Chain commands, clean in same layer
RUN apk add --no-cache curl && \
curl -fsSL https://example.com/script.sh -o /usr/local/bin/script && \
chmod +x /usr/local/bin/script
# ❌ Each RUN = new layer (bloat)
RUN apk add curl
RUN curl ... -o /usr/local/bin/script
RUN chmod +x /usr/local/bin/script
# Multi-line readability
RUN set -eux; \
apk add --no-cache \
curl \
ca-certificates \
tzdata; \
curl -fsSL ... | tar xz -C /usr/local
COPY — Copy Files
COPY [--chown=<user>:<group>] <src>... <dest>
COPY . /app
COPY --chown=app:app ./binary /usr/local/bin/
COPY --from=builder /app/build /app # From another stage (multi-stage)
# ✅ Layer-friendly: copy deps first, then source
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# ❌ Source change invalidates dependency cache
COPY . .
RUN go mod download
ADD — Copy + Auto-extract
# ADD auto-extracts tar archives
ADD archive.tar.gz /app/
# Prefer COPY unless you need tar extraction
COPY archive.tar.gz /app/
RUN tar xzf /app/archive.tar.gz -C /app
WORKDIR — Set Working Directory
WORKDIR /app
# All subsequent RUN/COPY/CMD use /app as base
# Prefer over:
RUN cd /app && npm install # ❌ cd doesn't persist
ENV & ARG
# ARG: build-time only (not in final image)
ARG VERSION=1.0.0
FROM myapp:${VERSION}
# ENV: runtime (persists in image)
ENV NODE_ENV=production \
PORT=8080
# Combine: pass ARG to ENV
ARG APP_VERSION
ENV APP_VERSION=${APP_VERSION}
EXPOSE — Document Ports
EXPOSE 8080
EXPOSE 8080/tcp # Protocol-specific
EXPOSE 8080/udp
# Note: EXPOSE does NOT publish ports. Use -p at runtime:
# docker run -p 8080:8080 myapp
CMD vs ENTRYPOINT
# CMD: default command (overridable)
CMD ["nginx", "-g", "daemon off;"]
# docker run myimage echo hello → overrides CMD
# ENTRYPOINT: fixed entry (not overridable)
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["nginx", "-g", "daemon off;"]
# docker run myimage → runs: docker-entrypoint.sh nginx -g 'daemon off;'
# docker run myimage echo hello → runs: docker-entrypoint.sh echo hello
# Common pattern: script + default args
ENTRYPOINT ["/entrypoint.sh"]
CMD ["start"]
USER — Switch to Non-Root
# Create user and group
RUN addgroup --system app && adduser --system --ingroup app app
USER app
HEALTHCHECK
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD wget -qO- http://localhost:8080/health || exit 1
# Dockerfile without shell (scratch):
HEALTHCHECK --interval=30s CMD /app/healthcheck || exit 1
SHELL — Change Default Shell
SHELL ["/bin/bash", "-euxo", "pipefail", "-c"]
RUN echo "Now using bash with strict mode"
Multi-Stage Build Patterns
Pattern 1: Build Binary + Scratch (Go/Rust)
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o server .
FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /app/server /server
USER 1000:1000
CMD ["/server"]
Pattern 2: Build + Minimal Runtime (Java)
FROM maven:3.9-eclipse-temurin-21 AS builder
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn package -DskipTests
FROM eclipse-temurin:21-jre-alpine
RUN addgroup --system app && adduser -S -G app app
COPY --from=builder /app/target/*.jar /app.jar
USER app
CMD ["java", "-jar", "/app.jar"]
Pattern 3: Layer-Optimized (Spring Boot)
FROM eclipse-temurin:21-jre-alpine AS builder
WORKDIR /app
COPY build/libs/*.jar app.jar
RUN java -Djarmode=layertools -jar app.jar extract
FROM eclipse-temurin:21-jre-alpine
RUN addgroup --system app && adduser -S -G app app
# Layers in dependency order (max cache)
COPY --from=builder /app/dependencies/ ./
COPY --from=builder /app/spring-boot-loader/ ./
COPY --from=builder /app/snapshot-dependencies/ ./
COPY --from=builder /app/application/ ./
USER app
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
Pattern 4: Build + Alpline (Node.js)
FROM node:22-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine
RUN addgroup --system app && adduser -S -G app app
COPY --from=builder /app/dist /app
COPY --from=builder /app/node_modules /app/node_modules
USER app
CMD ["node", "/app/index.js"]
Pattern 5: Python Dependencies + Slim Runtime
FROM python:3.12 AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
FROM python:3.12-slim
RUN groupadd --system app && useradd --system -g app app
COPY --from=builder /root/.local /home/app/.local
COPY . /app
ENV PATH=/home/app/.local/bin:$PATH
USER app
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0"]
Layer Caching Strategy
Docker builds layers from top to bottom.
A changed layer invalidates ALL layers below it.
✅ CORRECT order:
FROM base ← rarely changes
RUN install-system-deps ← changes with system updates
COPY go.mod go.sum ./ ← changes with dependency changes
RUN go mod download ← changes with dependency changes
COPY . . ← changes every commit ← MUST BE LAST
❌ WRONG order (slow builds):
COPY . . ← changes every commit
RUN go mod download ← reruns every time!
.dockerignore
# .dockerignore
.git
.gitignore
*.md
.env
.env.*
Dockerfile
docker-compose*.yml
node_modules
__pycache__
*.pyc
.git
.idea
.vscode
*.log
tmp/
Workflow — 推荐编写流程
Step 1: 确定语言和运行时: Go/Java/Node.js/Python → 选择基础镜像
Step 2: 选择构建模式: 单阶段/多阶段/Spring Boot 分层 → 从 templates 选模板
Step 3: 编写 Dockerfile: 先 COPY 依赖 → RUN install → COPY 源码 → CMD
Step 4: 验证: docker build -t app . + docker run + dive 分析镜像大小
Step 5: 生产加固: USER 非 root、HEALTHCHECK、固定 digest、Security 检查
Gotchas — Common Pitfalls
COPY . .beforeRUN install: Every code change invalidates the dependency layer — rebuilds from scratch. → Recovery: Always copy deps first:COPY package.json . → RUN install → COPY src/ ..- Root user by default: Always
USER <non-root>at the end of Dockerfile. Escaping the container as root = host root. → Recovery: AddRUN addgroup -S app && adduser -S app -G app+USER app; verify withdocker exec myapp whoami. ENV SECRET=valuein Dockerfile: Baked into image layers forever. → Recovery: Use BuildKit--mount=type=secretor runtime injectiondocker run -e SECRET=$VAL.- No
.dockerignore: Sends entire project to build context — slow and leaks sensitive files. → Recovery: Create.dockerignorewith at minimum.git node_modules .env; verify withdocker build --no-cache . 2>&1 | head -1. RUN apt update && apt installwithout cleanup: Leaves package lists in layer. → Recovery: Chain with&& rm -rf /var/lib/apt/lists/*; for apk:--no-cacheflag.- Heavy base image:
ubuntu:22.04(77 MB) vsalpine:3.20(7 MB). → Recovery: Prefer alpine; if glibc needed, usedebian:bookworm-slim; check size withdocker images.
Boundary — 能力边界(适用与不适用场景)
| 分类 | 场景 | 说明 |
|---|---|---|
| ✅ 能做 | 编写生产级 Dockerfile | 14 条指令完整参考 + 最佳实践 |
| ✅ 能做 | 多阶段构建(Go/Java/Node/Python) | 5 种语言专属模板 |
| ✅ 能做 | 层缓存优化 | COPY 依赖优先 + RUN 合并 + BuildKit cache mount |
| ✅ 能做 | 镜像瘦身 | 5 步法路线图:多阶段→Alpine→distroless→清理→dive |
| ⚠️ 需条件 | 私有依赖安装 | 需配合 BuildKit --secret 或 SSH forwarding |
| ⚠️ 需条件 | CMD vs ENTRYPOINT 选择 | 见指令参考中的决策树(工具用 ENTRYPOINT,服务用 CMD) |
| ❌ 超范围 | docker build 命令执行 | 使用 docker-build |
| ❌ 超范围 | 多平台构建(arm64/amd64) | 使用 docker-buildx |
| ❌ 超范围 | 容器编排(多容器) | 使用 docker-compose |
When NOT to Use This Skill
| ❌ Skip | ✅ Use Instead |
|---|---|
Building images (docker build ...) | docker-build |
| Multi-platform builds | docker-buildx |
| Compose file authoring | docker-compose |
| Docker basics | docker-basics |
| Running containers | docker-run |
Security & Stability
- All Dockerfile templates are educational. Review and harden before production use.
- Never embed secrets in Dockerfile. Use BuildKit
--mount=type=secretor runtime injection. - Always
USER <non-root>for production. UseCOPY --chownwhen copying files for that user. - Pin base image digests for production reproducibility.
📚 官方文档参考
🧭 Docker Skills Journey
📍 You are here:
docker-dockerfile— Dockerfile 编写
basics → dockerfile → build → buildx → run → compose → ...
→ Next: docker-build — Build images with docker build
FAQ
What does the docker-dockerfile skill do?
Expert guidance for Dockerfile authoring — the complete reference for writing production-grade Dockerfiles. Covers every instruction (FROM/RUN/COPY/ADD/ENV/ARG/WORKDIR/EXPOSE/CMD/ENTRYPOINT/USER/HEALTHCHECK/SHELL) with syntax, best practices, and common mistakes. Includes multi-stage build patterns (build+scratch, build+alpine, builder pattern), layer caching optimization strategies, .dockerignore rules, and language-specific production templates (Go/Rust/Java Spring Boot/Python FastAPI/Node.js Express/TypeScript). Use when the user asks about Dockerfile, how to write a Dockerfile, multi-stage build, layer optimization, or needs Dockerfile examples for a specific language. 使用场景:Dockerfile 编写、怎么写 Dockerfile、Dockerfile 指令、多阶段构建、multi-stage、层优化、layer cache、Dockerfile 模板.
How do I install docker-dockerfile?
Run npx skills add https://github.com/full-stack-skills/docker-skills --skill docker-dockerfile in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/docker-dockerfile/ (personal) or .claude/skills/docker-dockerfile/ (project).
Which AI agents can use docker-dockerfile?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is docker-dockerfile safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains docker-dockerfile?
It is published by full-stack-skills in full-stack-skills/docker-skills. It has 122 recorded installs.
More from full-stack-skills/docker-skills
docker-compose
full-stack-skills/docker-skills
Expert guidance for Docker Compose — writing production-grade compose.yml files for multi-container applications. Covers complete Compose file syntax (services, networks, volumes, secrets, configs, profiles, extends, include), service configuration (image/build, ports, environment, envfile, dependson with health checks, deploy resources, restart policies), networking in Compose (default networks, custom networks, internal networks), volume management, environment variable strategies (.env vs environment vs envfile), override files for multi-environment, profiles for optional services, and migration to Kubernetes with kompose. Use when the user asks about docker compose, docker-compose.yml, compose file, multi-container, service orchestration, compose configuration, or needs to write/modify a compose file. 使用场景:docker compose、docker-compose.yml、compose 文件、多容器、服务编排、compose 配置、dependson、profiles.
docker-security
full-stack-skills/docker-skills
Guidance for Docker security hardening across the full lifecycle — image security (minimal base images, non-root users, pinned versions), runtime security (seccomp/AppArmor/SELinux, capabilities, read-only rootfs, no-new-privileges), secrets management (BuildKit secrets, Docker secrets in Swarm), Docker Bench Security auditing, CIS compliance checklist, and supply-chain security (image signing, content trust, SBOM). Use when the user asks about Docker security, image hardening, non-root containers, seccomp, AppArmor, Docker Bench, secrets management, or securing containers. 使用场景:docker 安全、镜像安全、非root运行、seccomp、AppArmor、security、Docker Bench、secret管理.
docker-troubleshooting
full-stack-skills/docker-skills
Open the skill to read its SKILL.md instructions.
docker-networking
full-stack-skills/docker-skills
Guidance for Docker networking configuration and inter-container communication. Covers network modes (bridge/host/overlay/none/macvlan/ipvlan), custom bridge networks with DNS resolution, port publishing (-p/--publish), container linking and service discovery, network troubleshooting (inspect/ping/nslookup), overlay networks for Swarm, and network security (internal networks, encrypted overlay). Use when the user asks about docker network, container networking, bridge mode, port mapping, inter-container communication, network troubleshooting, or Docker network modes. 使用场景:docker network、容器网络、bridge、overlay、端口映射、容器通信、网络配置、网络排查.
docker-basics
full-stack-skills/docker-skills
Open the skill to read its SKILL.md instructions.
docker-testcontainers
full-stack-skills/docker-skills
Guidance for Testcontainers — running Docker containers in automated integration tests. Covers Java (@Testcontainers, @Container, PostgreSQL/Redis/Kafka/Elasticsearch), Python (testcontainers-python with pytest), container lifecycle management (singleton, reuse), CI/CD integration (Docker-in-Docker, Ryuk), Testcontainer best practices, and database migration testing. Use when the user asks about testcontainers, integration testing with Docker, database testing, Java testcontainers, Python testcontainers, or needs to test with real Docker services. 使用场景:testcontainers、集成测试、docker 测试、数据库测试、Java Testcontainers、Python Testcontainers.
Popular devops & cloud skills
microsoft-foundry
microsoft/azure-skills
Build, deploy, evaluate, optimize, fine-tune, and manage Microsoft Foundry agents, models, and resources end to end. USE FOR: foundry, azd ai agent, azd provision/deploy, hosted agent scaffold/develop/run/deploy/troubleshoot, prompt agent create, managed harness agent create, GitHub Copilot harness agent, create agent, update agent, add tool to agent, invoke agent, agent insights, evaluate agent, batch eval, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, Agent Optimizer scaffold, dataset curation from traces, deploy model, model fine-tuning (SFT/DPO/RFT), Foundry project, RBAC, role assignment, permissions, quota, capacity, region, deployment failure, AI Services, create Foundry resource, knowledge index, customize deployment, onboard, availability, training-data, grader, distillation, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure
azure-diagnostics
microsoft/azure-skills
Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, container app 503 or target port mismatch, troubleshoot functions, function telemetry missing or stopped after a config/connection-string change, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, lock renewal during long-running processing, service bus dead letter.
azure-prepare
microsoft/azure-skills
Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure.
azure-ai
microsoft/azure-skills
Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech.
azure-deploy
microsoft/azure-skills
Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: "run azd up", "run azd deploy", "execute deployment", "push to production", "push to cloud", "go live", "ship it", "bicep deploy", "terraform apply", "publish to Azure", "launch on Azure". DO NOT USE WHEN: "create and deploy", "build and deploy", "create a new app", "set up infrastructure", "create and deploy to Azure using Terraform" — use azure-prepare for these.
azure-validate
microsoft/azure-skills
Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment.