mcpField
D
dockerfile-optimizer

dockerfile-optimizer

github.com/patricio0312rev云与 DevOps63532 次安装41 周前更新
代码仓库

关于 dockerfile-optimizer

面向开发者的 Dockerfile 优化技能,指导构建更精简、安全且便于缓存的镜像。内容覆盖多阶段构建、层缓存、非 root 用户、健康检查与 CI/CD。

主要功能

  1. 01多阶段构建与基础镜像选择
  2. 02按变更频率优化层缓存
  3. 03缩减镜像体积
  4. 04配置非 root 用户与安全选项
  5. 05设置健康检查和 CI/CD 构建

适用场景

  1. 01优化应用的生产 Docker 镜像
  2. 02减少依赖变更导致的重复构建
  3. 03为容器添加非 root 运行和健康检查
  4. 04在 CI/CD 中构建并检查镜像

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/patricio0312rev/skills --skill dockerfile-optimizer

安装后在 Claude Code 中输入/dockerfile-optimizer确认已加载。

详细介绍

Dockerfile 优化器

遵循生产环境最佳实践,构建经过优化、安全且缓存高效的 Docker 镜像。

核心工作流

  1. 分析当前 Dockerfile:找出优化机会
  2. 实施多阶段构建:分离构建和运行环境
  3. 优化层缓存:高效排列指令顺序
  4. 缩减镜像大小:使用精简的基础镜像并清理文件
  5. 强化安全性:使用非 root 用户和最小权限
  6. 配置健康检查:确保监控容器健康状态

基础镜像选择

镜像大小对比
基础镜像大小使用场景
node:20~1GB仅用于开发
node:20-slim~200MB通用生产环境
node:20-alpine~130MB对大小要求严格的生产环境
gcr.io/distroless/nodejs20~120MB最高安全性
按语言划分的建议
# Node.js
FROM node:20-alpine

# Python
FROM python:3.12-slim

# Go
FROM golang:1.22-alpine AS builder
FROM scratch AS runtime  # Or gcr.io/distroless/static

# Rust
FROM rust:1.75-alpine AS builder
FROM alpine:3.19 AS runtime

# Java
FROM eclipse-temurin:21-jdk-alpine AS builder
FROM eclipse-temurin:21-jre-alpine AS runtime

多阶段构建

Node.js 应用
# ==================== Build Stage ====================
FROM node:20-alpine AS builder

WORKDIR /app

# Install dependencies first (cache layer)
COPY package.json package-lock.json ./
RUN npm ci --ignore-scripts

# Copy source and build
COPY . .
RUN npm run build

# Prune dev dependencies
RUN npm prune --production

# ==================== Production Stage ====================
FROM node:20-alpine AS production

# Security: Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nextjs -u 1001

WORKDIR /app

# Copy only necessary files
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nextjs:nodejs /app/dist ./dist
COPY --from=builder --chown=nextjs:nodejs /app/package.json ./

# Security: Switch to non-root user
USER nextjs

# 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))"

EXPOSE 3000

CMD ["node", "dist/index.js"]
Next.js 应用
# ==================== Dependencies ====================
FROM node:20-alpine AS deps

RUN apk add --no-cache libc6-compat

WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

# ==================== Builder ====================
FROM node:20-alpine AS builder

WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Disable telemetry during build
ENV NEXT_TELEMETRY_DISABLED=1

RUN npm run build

# ==================== Runner ====================
FROM node:20-alpine AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nextjs

# Copy static assets
COPY --from=builder /app/public ./public

# Set correct permissions for prerender cache
RUN mkdir .next && chown nextjs:nodejs .next

# Copy build output
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

HEALTHCHECK --interval=30s --timeout=3s \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1

CMD ["node", "server.js"]
Python 应用
# ==================== Builder ====================
FROM python:3.12-slim AS builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# Create virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# ==================== Production ====================
FROM python:3.12-slim AS production

WORKDIR /app

# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser

# Copy virtual environment from builder
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Copy application code
COPY --chown=appuser:appuser . .

USER appuser

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=3s \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Go 应用
# ==================== Builder ====================
FROM golang:1.22-alpine AS builder

RUN apk add --no-cache git ca-certificates tzdata

WORKDIR /app

# Download dependencies
COPY go.mod go.sum ./
RUN go mod download && go mod verify

# Build
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-w -s -X main.version=$(git describe --tags --always)" \
    -o /app/server ./cmd/server

# ==================== Production ====================
FROM scratch AS production

# Copy CA certificates for HTTPS
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo

# Copy binary
COPY --from=builder /app/server /server

EXPOSE 8080

ENTRYPOINT ["/server"]

层缓存优化

按更改频率排列指令
# ✓ GOOD: Least changing → Most changing
FROM node:20-alpine

# 1. System dependencies (rarely change)
RUN apk add --no-cache dumb-init

# 2. Create user (rarely changes)
RUN adduser -D appuser

# 3. Set working directory
WORKDIR /app

# 4. Copy dependency files (change occasionally)
COPY package.json package-lock.json ./

# 5. Install dependencies (cached if package files unchanged)
RUN npm ci --production

# 6. Copy source code (changes frequently)
COPY --chown=appuser:appuser . .

USER appuser
CMD ["dumb-init", "node", "index.js"]
# ✗ BAD: Source code before dependencies
FROM node:20-alpine
WORKDIR /app
COPY . .                    # Invalidates cache on ANY file change
RUN npm install             # Must reinstall every time
CMD ["node", "index.js"]
.dockerignore
# Version control
.git
.gitignore

# Dependencies (reinstalled in container)
node_modules
.pnpm-store

# Build outputs
dist
build
.next
out

# Development files
.env*.local
*.log
coverage
.nyc_output

# IDE
.idea
.vscode
*.swp
*.swo

# Docker
Dockerfile*
docker-compose*
.docker

# Documentation
*.md
docs

# Tests (unless needed in container)
__tests__
*.test.ts
*.spec.ts
jest.config.*

缩减镜像大小

在同一层中清理
# ✓ GOOD: Install and clean in one layer
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        curl \
        ca-certificates \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# ✗ BAD: Separate layers (cleanup doesn't reduce size)
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*  # Too late, already in previous layer
使用 --no-install-recommends
# ✓ Minimal installation
RUN apt-get install -y --no-install-recommends package-name

# ✗ Installs unnecessary recommended packages
RUN apt-get install -y package-name
Alpine 软件包管理
# Alpine uses apk, not apt
RUN apk add --no-cache \
    curl \
    git \
    && rm -rf /var/cache/apk/*

强化安全性

非 root 用户
# Create user in Debian/Ubuntu
RUN groupadd -r appgroup && useradd -r -g appgroup appuser

# Create user in Alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Set ownership and switch user
COPY --chown=appuser:appgroup . .
USER appuser
只读文件系统
# In docker-compose.yml or docker run
services:
  app:
    read_only: true
    tmpfs:
      - /tmp
      - /var/run
安全扫描
# Add labels for security scanning
LABEL org.opencontainers.image.source="https://github.com/org/repo"
LABEL org.opencontainers.image.description="Application description"
LABEL org.opencontainers.image.licenses="MIT"
最小化功能
# docker-compose.yml
services:
  app:
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE  # Only if binding to port < 1024
    security_opt:
      - no-new-privileges:true

健康检查

HTTP 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1
不使用 curl(镜像更小)
# Node.js
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3000/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))"

# Python
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1

# wget (Alpine)
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

环境变量

# Build-time arguments
ARG NODE_ENV=production
ARG APP_VERSION=unknown

# Runtime environment variables
ENV NODE_ENV=$NODE_ENV
ENV APP_VERSION=$APP_VERSION

# Don't include secrets in Dockerfile
# Use docker run --env-file or secrets management

用于开发的 Docker Compose

# docker-compose.yml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
      target: development  # Multi-stage target
    volumes:
      - .:/app
      - /app/node_modules  # Anonymous volume for node_modules
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=development
    command: npm run dev

  app-prod:
    build:
      context: .
      dockerfile: Dockerfile
      target: production
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
    healthcheck:
      test: ["CMD", "wget", "--spider", "http://localhost:3000/health"]
      interval: 30s
      timeout: 3s
      retries: 3

CI/CD 集成

GitHub Actions 构建
# .github/workflows/docker.yml
name: Docker Build

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: |
            ghcr.io/${{ github.repository }}:latest
            ghcr.io/${{ github.repository }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Scan for vulnerabilities
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: ghcr.io/${{ github.repository }}:${{ github.sha }}
          format: 'table'
          exit-code: '1'
          severity: 'CRITICAL,HIGH'

常见优化

固定版本
# ✓ Pinned versions for reproducibility
FROM node:20.11.0-alpine3.19

# ✗ Latest tags can break builds
FROM node:latest
FROM node:20-alpine
使用 COPY 而非 ADD
# ✓ COPY is explicit and preferred
COPY package.json .

# ✗ ADD has extra features rarely needed
ADD package.json .  # Only use for URLs or tar extraction
合并 RUN 命令
# ✓ Single layer, smaller image
RUN apt-get update && \
    apt-get install -y package1 package2 && \
    rm -rf /var/lib/apt/lists/*

# ✗ Multiple layers, larger image
RUN apt-get update
RUN apt-get install -y package1
RUN apt-get install -y package2

调试

检查镜像层
# View layer history
docker history image-name

# Analyze image with dive
docker run --rm -it \
  -v /var/run/docker.sock:/var/run/docker.sock \
  wagoodman/dive:latest image-name
显示构建进度
# Detailed build output
docker build --progress=plain -t myapp .

# Build specific stage
docker build --target builder -t myapp:builder .

最佳实践

  1. 使用多阶段构建:分离构建和运行环境
  2. 按更改频率排列各层:尽可能命中缓存
  3. 使用 .dockerignore:排除不必要的文件
  4. 以非 root 用户身份运行:始终创建并使用非 root 用户
  5. 固定基础镜像版本:确保构建可复现
  6. 在同一层中清理:缩减镜像大小
  7. 添加健康检查:支持容器编排
  8. 扫描漏洞:使用 Trivy、Snyk 或类似工具
  9. 使用 slim/alpine 基础镜像:缩小攻击面
  10. 不要存储机密:在运行时注入

输出检查清单

每个经过优化的 Dockerfile 都应包含:

  • 分离构建和运行环境的多阶段构建
  • 精简或 Alpine 基础镜像
  • 固定版本的基础镜像
  • 层缓存优化(依赖项先于源代码)
  • 非 root 用户配置
  • 已定义健康检查
  • .dockerignore 文件
  • 镜像中不含机密
  • 尽可能少的已安装软件包
  • 在安装所在的同一层中进行清理
  • 用于元数据的标签
  • 在 CI 中进行安全扫描

评论

支持 Markdown