dockerfile-optimizer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dockerfile Optimizer

Dockerfile 优化指南

Optimize Docker images for size, speed, and security.
针对镜像体积、构建速度和安全性优化Docker镜像。

Quick Start

快速开始

Analyze current Dockerfile:
bash
docker build -t myapp .
docker images myapp
分析现有Dockerfile:
bash
docker build -t myapp .
docker images myapp

Note the size, then optimize

记录当前镜像大小,随后进行优化

undefined
undefined

Instructions

操作步骤

Step 1: Analyze Current Dockerfile

步骤1:分析现有Dockerfile

Review for optimization opportunities:
  • Base image choice
  • Layer structure
  • Build dependencies
  • Caching strategy
  • Security practices
排查可优化的方向:
  • 基础镜像选择
  • 分层结构
  • 构建依赖
  • 缓存策略
  • 安全实践

Step 2: Optimize Base Image

步骤2:优化基础镜像

Choose minimal base:
dockerfile
undefined
选择轻量基础镜像:
dockerfile
undefined

Before: Large base

优化前:体积较大的基础镜像

FROM ubuntu:22.04 # ~77MB
FROM ubuntu:22.04 # ~77MB

After: Minimal base

优化后:轻量基础镜像

FROM alpine:3.18 # ~7MB
FROM alpine:3.18 # ~7MB

or

FROM node:18-alpine # ~170MB vs node:18 ~990MB

**Use specific tags**:
```dockerfile
FROM node:18-alpine # ~170MB 对比 node:18 ~990MB

**使用特定版本标签**:
```dockerfile

Bad: Unpredictable

不推荐:版本不可预测

FROM node:latest
FROM node:latest

Good: Specific version

推荐:指定具体版本

FROM node:18.17-alpine3.18
undefined
FROM node:18.17-alpine3.18
undefined

Step 3: Implement Multi-Stage Builds

步骤3:实现多阶段构建

For compiled languages:
dockerfile
undefined
针对编译型语言:
dockerfile
undefined

Before: Single stage

优化前:单阶段构建

FROM golang:1.21 WORKDIR /app COPY . . RUN go build -o app CMD ["./app"]
FROM golang:1.21 WORKDIR /app COPY . . RUN go build -o app CMD ["./app"]

Result: ~800MB

结果镜像体积:~800MB

After: Multi-stage

优化后:多阶段构建

FROM golang:1.21-alpine AS builder WORKDIR /app COPY . . RUN go build -o app
FROM alpine:3.18 COPY --from=builder /app/app /app CMD ["/app"]
FROM golang:1.21-alpine AS builder WORKDIR /app COPY . . RUN go build -o app
FROM alpine:3.18 COPY --from=builder /app/app /app CMD ["/app"]

Result: ~15MB

结果镜像体积:~15MB

undefined
undefined

Step 4: Optimize Layer Caching

步骤4:优化分层缓存

Order by change frequency:
dockerfile
undefined
按变更频率排序命令:
dockerfile
undefined

Bad: Code changes invalidate all layers

不推荐:代码变更会导致所有分层失效

FROM node:18-alpine COPY . . RUN npm install CMD ["node", "server.js"]
FROM node:18-alpine COPY . . RUN npm install CMD ["node", "server.js"]

Good: Dependencies cached separately

推荐:依赖单独缓存

FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . CMD ["node", "server.js"]
undefined
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . CMD ["node", "server.js"]
undefined

Step 5: Combine and Minimize Layers

步骤5:合并并减少分层数量

Reduce layer count:
dockerfile
undefined
减少分层数量:
dockerfile
undefined

Before: Multiple layers

优化前:多个独立分层

RUN apt-get update RUN apt-get install -y curl RUN apt-get install -y git RUN apt-get clean
RUN apt-get update RUN apt-get install -y curl RUN apt-get install -y git RUN apt-get clean

After: Single layer

优化后:合并为单个分层

RUN apt-get update &&
apt-get install -y curl git &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
undefined
RUN apt-get update &&
apt-get install -y curl git &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
undefined

Step 6: Use .dockerignore

步骤6:使用.dockerignore文件

Create
.dockerignore
:
node_modules
npm-debug.log
.git
.gitignore
README.md
.env
.DS_Store
*.md
.vscode
.idea
dist
build
coverage
创建.dockerignore文件:
node_modules
npm-debug.log
.git
.gitignore
README.md
.env
.DS_Store
*.md
.vscode
.idea
dist
build
coverage

Step 7: Remove Build Dependencies

步骤7:移除构建依赖

Clean up after install:
dockerfile
undefined
安装完成后清理:
dockerfile
undefined

Python example

Python 示例

RUN pip install --no-cache-dir -r requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

Node example

Node 示例

RUN npm ci --only=production && npm cache clean --force
RUN npm ci --only=production && npm cache clean --force

Alpine example

Alpine 示例

RUN apk add --no-cache curl &&
apk del build-dependencies
undefined
RUN apk add --no-cache curl &&
apk del build-dependencies
undefined

Step 8: Add Security Improvements

步骤8:添加安全增强措施

Run as non-root:
dockerfile
undefined
以非root用户运行:
dockerfile
undefined

Create user

创建用户

RUN addgroup -g 1001 -S appuser &&
adduser -u 1001 -S appuser -G appuser
RUN addgroup -g 1001 -S appuser &&
adduser -u 1001 -S appuser -G appuser

Switch to user

切换至该用户

USER appuser
USER appuser

Or use existing user

或使用系统内置用户

USER nobody
undefined
USER nobody
undefined

Step 9: Verify Optimization

步骤9:验证优化效果

Check image size:
bash
docker images myapp
docker history myapp
Analyze layers:
bash
docker history myapp --no-trunc
Use dive tool:
bash
dive myapp
检查镜像大小:
bash
docker images myapp
docker history myapp
分析镜像分层:
bash
docker history myapp --no-trunc
使用dive工具分析:
bash
dive myapp

Optimization Patterns

优化模式

Node.js Optimization:
dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
Python Optimization:
dockerfile
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
USER nobody
CMD ["python", "app.py"]
Go Optimization:
dockerfile
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM scratch
COPY --from=builder /app/app /app
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
EXPOSE 8080
CMD ["/app"]
Node.js 优化方案:
dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
Python 优化方案:
dockerfile
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
USER nobody
CMD ["python", "app.py"]
Go 语言优化方案:
dockerfile
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

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

Common Issues

常见问题

Issue: Large image size
  • Use alpine or slim base images
  • Implement multi-stage builds
  • Remove build dependencies
  • Use .dockerignore
Issue: Slow builds
  • Optimize layer caching
  • Order commands by change frequency
  • Use build cache mounts
  • Parallelize where possible
Issue: Security vulnerabilities
  • Use minimal base images
  • Keep images updated
  • Run as non-root
  • Scan with security tools
Issue: Build cache not working
  • Check command order
  • Avoid COPY . . early
  • Use specific COPY commands
  • Check .dockerignore
问题:镜像体积过大
  • 使用alpine或slim版本的基础镜像
  • 实现多阶段构建
  • 移除构建依赖
  • 配置.dockerignore文件
问题:构建速度缓慢
  • 优化分层缓存策略
  • 按变更频率排序命令
  • 使用构建缓存挂载
  • 尽可能并行执行构建步骤
问题:存在安全漏洞
  • 使用轻量基础镜像
  • 保持镜像版本更新
  • 以非root用户运行
  • 使用安全工具扫描镜像
问题:构建缓存未生效
  • 检查命令顺序
  • 避免过早执行COPY . .
  • 使用精准的COPY命令
  • 检查.dockerignore配置

Advanced

进阶内容

For detailed information, see:
  • Multi-Stage Builds - Advanced multi-stage patterns
  • Layer Caching - Caching strategies and optimization
  • Base Images - Base image selection guide
如需详细信息,请参考:
  • Multi-Stage Builds - 进阶多阶段构建模式
  • Layer Caching - 缓存策略与优化
  • Base Images - 基础镜像选择指南