docker-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDocker Best Practices
Docker 最佳实践
Quick Reference
快速参考
- Multi-stage builds: Separate build and runtime dependencies
- Alpine/slim images: Minimal base images for smaller attack surface
- Layer caching: Order instructions from least to most frequently changing
- Security first: Non-root user, pinned versions, minimal packages
- Single process: One primary process per container
- 多阶段构建:分离构建与运行时依赖
- Alpine/slim镜像:最小化基础镜像以缩小攻击面
- 镜像层缓存:按指令变更频率从低到高排序
- 安全优先:使用非root用户、固定版本、最小化依赖包
- 单进程原则:每个容器仅运行一个主进程
Core Principles
核心原则
1. Immutability
1. 不可变性
- Never modify running containers - create new images instead
- Use semantic versioning for image tags ()
v1.2.3 - Treat images as versioned artifacts
- 切勿修改运行中的容器 - 应创建新的镜像替代
- 为镜像标签使用语义化版本(如)
v1.2.3 - 将镜像视为版本化的工件
2. Efficiency & Security
2. 效率与安全性
- Prefer Alpine variants for smaller images ()
node:18-alpine - Use official images from trusted sources
- Update base images regularly for security patches
- Avoid tag in production
latest
- 优先选择Alpine变体以获得更小的镜像(如)
node:18-alpine - 使用来自可信源的官方镜像
- 定期更新基础镜像以获取安全补丁
- 生产环境中避免使用标签
latest
3. Layer Optimisation
3. 镜像层优化
dockerfile
undefineddockerfile
undefinedGOOD: Optimise for caching
GOOD: Optimise for caching
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./ # Cache-friendly: deps change less
RUN npm ci --only=production
COPY . . # App code changes most
undefinedFROM node:18-alpine
WORKDIR /app
COPY package*.json ./ # Cache-friendly: deps change less
RUN npm ci --only=production
COPY . . # App code changes most
undefinedMulti-Stage Builds (Essential)
多阶段构建(必备)
dockerfile
undefineddockerfile
undefinedBuild stage
Build stage
FROM node:18-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:18-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
Production stage
Production stage
FROM node:18-alpine AS production
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/package*.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/main.js"]
undefinedFROM node:18-alpine AS production
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/package*.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/main.js"]
undefinedSecurity Essentials
安全要点
Non-Root User
非root用户
dockerfile
undefineddockerfile
undefinedCreate and use non-root user
Create and use non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
USER nextjs
undefinedRUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
USER nextjs
undefinedMinimal Dependencies
最小化依赖
dockerfile
undefineddockerfile
undefinedCombine commands to reduce layers and clean up
Combine commands to reduce layers and clean up
RUN apk add --no-cache
python3
py3-pip
&& pip install --no-cache-dir flask
&& apk del build-dependencies
python3
py3-pip
&& pip install --no-cache-dir flask
&& apk del build-dependencies
undefinedRUN apk add --no-cache
python3
py3-pip
&& pip install --no-cache-dir flask
&& apk del build-dependencies
python3
py3-pip
&& pip install --no-cache-dir flask
&& apk del build-dependencies
undefinedVersion Pinning
版本固定
dockerfile
undefineddockerfile
undefinedPin specific versions for reproducibility
Pin specific versions for reproducibility
FROM python:3.11.5-slim
RUN pip install flask==2.3.3
undefinedFROM python:3.11.5-slim
RUN pip install flask==2.3.3
undefinedCommon Patterns
常见模式
Python Application
Python应用
dockerfile
FROM python:3.11-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.11-slim AS production
WORKDIR /app
COPY /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY . .
USER nobody
EXPOSE 8000
CMD ["python", "app.py"]dockerfile
FROM python:3.11-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.11-slim AS production
WORKDIR /app
COPY /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY . .
USER nobody
EXPOSE 8000
CMD ["python", "app.py"]Node.js Application
Node.js应用
dockerfile
FROM node:18-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:18-alpine AS production
WORKDIR /app
COPY /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]dockerfile
FROM node:18-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:18-alpine AS production
WORKDIR /app
COPY /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]Go Application
Go应用
dockerfile
FROM golang:1.21-alpine AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o main .
FROM scratch AS production
COPY /app/main /main
EXPOSE 8080
CMD ["/main"]dockerfile
FROM golang:1.21-alpine AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o main .
FROM scratch AS production
COPY /app/main /main
EXPOSE 8080
CMD ["/main"]Performance Optimisation
性能优化
.dockerignore
.dockerignore
dockerignore
node_modules
.git
.gitignore
README.md
.env
.nyc_output
coverage
.vscodedockerignore
node_modules
.git
.gitignore
README.md
.env
.nyc_output
coverage
.vscodeHealth Checks
健康检查
dockerfile
HEALTHCHECK \
CMD curl -f http://localhost:3000/health || exit 1dockerfile
HEALTHCHECK \
CMD curl -f http://localhost:3000/health || exit 1Resource Limits (docker-compose)
资源限制(docker-compose)
yaml
services:
app:
image: myapp:latest
deploy:
resources:
limits:
memory: 512M
cpus: "0.5"yaml
services:
app:
image: myapp:latest
deploy:
resources:
limits:
memory: 512M
cpus: "0.5"Security Checklist
安全检查清单
- Use multi-stage builds
- Run as non-root user
- Use minimal base images (Alpine/slim)
- Pin dependency versions
- Remove unnecessary packages
- Scan images for vulnerabilities
- Set resource limits
- Use secrets management for sensitive data
- 使用多阶段构建
- 以非root用户运行
- 使用最小化基础镜像(Alpine/slim)
- 固定依赖版本
- 移除不必要的包
- 扫描镜像以查找漏洞
- 设置资源限制
- 使用密钥管理处理敏感数据
Common Anti-Patterns to Avoid
需避免的常见反模式
❌ Don't do this:
dockerfile
FROM ubuntu:latest # Use specific versions
RUN apt-get update # Combine with install
COPY . . # Do this after deps
RUN apt-get install -y curl # Separate command
ADD https://example.com/file.tar.gz # Use COPY + RUN✅ Do this instead:
dockerfile
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y \
curl \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .❌ 请勿这样做:
dockerfile
FROM ubuntu:latest # Use specific versions
RUN apt-get update # Combine with install
COPY . . # Do this after deps
RUN apt-get install -y curl # Separate command
ADD https://example.com/file.tar.gz # Use COPY + RUN✅ 正确做法:
dockerfile
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y \
curl \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .Development vs Production
与核心原则的对齐
Development
—
dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]- 安全性:非root用户、最小化攻击面、版本固定
- 效率:多阶段构建、镜像层缓存、最小化基础镜像
- 可复现性:固定版本、明确依赖
- 可维护性:清晰的结构、文档化的模式、一致的实践
Production (Multi-stage)
—
dockerfile
FROM node:18-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:18-alpine AS production
WORKDIR /app
COPY /app/dist ./dist
RUN addgroup -g 1001 nodejs && adduser -S -u 1001 nextjs
USER nextjs
EXPOSE 3000
CMD ["node", "dist/server.js"]—
Alignment with Core Principles
—
- Security: Non-root users, minimal attack surface, version pinning
- Efficiency: Multi-stage builds, layer caching, minimal base images
- Reproducibility: Pinned versions, explicit dependencies
- Maintainability: Clear structure, documented patterns, consistent practices
—