dockerfile-best-practices
2
总安装量
2
周安装量
#74084
全站排名
安装命令
npx skills add https://github.com/sarpit/agent-skills --skill dockerfile-best-practices
Agent 安装分布
opencode
2
gemini-cli
2
claude-code
2
github-copilot
2
codex
2
kimi-cli
2
Skill 文档
Dockerfile Best Practices
Apply these rules when writing, reviewing, or optimizing any Dockerfile.
Base Images
- Use minimal base images:
alpine,slim,distroless, orscratch - Compiled languages (Go, Rust): use
scratchimages - Interpreted languages (Node.js, Python): use
alpineorslim(runtime needed) - Always use multistage builds to separate build-time and runtime dependencies
Image Optimization
Layer Caching
Order layers from least-changing to most-changing:
Base image â Dependency files â Install dependencies â Config â Source code
Never copy source code before installing dependencies â a code change would invalidate the dependency cache.
Reducing Image Size
- Combine
RUNinstructions to reduce layers - Be explicit with
COPYtargets instead ofCOPY . . - Install only production dependencies in the runtime stage
Security
- Never run as root. Create a dedicated user/group with UID/GID > 10000
- Pin image versions. Never use
latest - Use official or verified images only
- No secrets in images. No API keys, passwords, or config files with credentials
- No
sudoin containers - Use
COPYoverADDto prevent fetching unknown URLs or extracting archives - No debugging tools. Do not install
curl,wget,vim, ornetstat - Executables owned by root, run by non-root user. Prevents an attacker from modifying binaries to persist access
Maintainability
- Sort multi-line package installs alphabetically for cleaner diffs
- Use
WORKDIRto set the working directory - Use exec form for
CMD:["node", "app.js"]â shell form prevents signal forwarding (SIGTERM goes to/bin/sh, not the app) - Comment non-obvious decisions
- Add OCI labels for metadata
Example: Node.js Multistage Dockerfile
# Build stage
FROM node:22-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production
COPY src/ ./src/
# Runtime stage
FROM node:22-alpine
RUN addgroup -g 10001 appgroup && \
adduser -u 10001 -G appgroup -D appuser
WORKDIR /app
COPY /app ./
USER appuser
EXPOSE 3000
CMD ["node", "src/index.js"]