dockerfile-optimizer
Dockerfileをマルチステージビルドやベストプラクティスに基づいて最適化し、イメージサイズの削減・ビルド高速化・キャッシュ効率の向上・セキュリティ強化を実現します。「Dockerfileを最適化したい」「Dockerイメージを軽量化したい」「アプリをコンテナ化したい」といったリクエスト時に活用してください。
description の原文を見る
Optimizes Dockerfiles for smaller images, faster builds, better caching, and security hardening using multi-stage builds and best practices. Use when users request "optimize Dockerfile", "reduce Docker image size", "Docker best practices", or "containerize application".
SKILL.md 本文
Dockerfile オプティマイザー
本番環境のベストプラクティスに従い、最適化されたセキュアで効率的なキャッシュのDockerイメージをビルドします。
コアワークフロー
- 現在のDockerfileを分析: 最適化の機会を特定
- マルチステージビルドを実装: ビルドと実行環境を分離
- レイヤーキャッシュを最適化: 命令を効率的に順序付け
- イメージサイズを最小化: スリムなベースイメージを使用してクリーンアップ
- セキュリティハードニングを追加: 非rootユーザー、最小限のパーミッション
- ヘルスチェックを設定: コンテナーヘルス監視を確保
ベースイメージの選択
イメージサイズ比較
| ベースイメージ | サイズ | ユースケース |
|---|---|---|
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"]
レイヤーキャッシュ最適化
命令を変更頻度順に順序付け
# ✓ 良い例: 最も変更頻度が低い → 最も高い
FROM node:20-alpine
# 1. System dependencies (めったに変更されない)
RUN apk add --no-cache dumb-init
# 2. Create user (めったに変更されない)
RUN adduser -D appuser
# 3. Set working directory
WORKDIR /app
# 4. Copy dependency files (時々変更される)
COPY package.json package-lock.json ./
# 5. Install dependencies (パッケージファイルが変更されなければキャッシュ)
RUN npm ci --production
# 6. Copy source code (頻繁に変更される)
COPY --chown=appuser:appuser . .
USER appuser
CMD ["dumb-init", "node", "index.js"]
# ✗ 悪い例: 依存関係の前にソースコード
FROM node:20-alpine
WORKDIR /app
COPY . . # ファイルが変更されるたびにキャッシュが無効化
RUN npm install # 毎回再インストール必須
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.*
イメージサイズ削減
同じレイヤーでクリーンアップ
# ✓ 良い例: インストールとクリーンアップを1つのレイヤーで
RUN apt-get update && \
apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get clean
# ✗ 悪い例: 別のレイヤーでクリーンアップ (サイズ削減されない)
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/* # 遅すぎて、すでに前のレイヤーに含まれている
--no-install-recommends を使用
# ✓ 最小インストール
RUN apt-get install -y --no-install-recommends package-name
# ✗ 不要な推奨パッケージもインストール
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'
一般的な最適化
バージョンをピン留め
# ✓ 再現可能性のためにピン留めされたバージョン
FROM node:20.11.0-alpine3.19
# ✗ 最新タグはビルドを破壊する可能性
FROM node:latest
FROM node:20-alpine
ADDではなくCOPYを使用
# ✓ COPYは明確で推奨
COPY package.json .
# ✗ ADDは余分な機能を持つが、ほとんど必要ない
ADD package.json . # Only use for URLs or tar extraction
RUNコマンドを結合
# ✓ 単一レイヤー、より小さいイメージ
RUN apt-get update && \
apt-get install -y package1 package2 && \
rm -rf /var/lib/apt/lists/*
# ✗ 複数レイヤー、より大きいイメージ
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 .
ベストプラクティス
- マルチステージビルドを使用: ビルドと実行環境を分離
- レイヤーを変更頻度順に順序付け: キャッシュヒット率を最大化
- .dockerignoreを使用: 不要なファイルを除外
- 非rootとして実行: 常に非rootユーザーを作成して使用
- ベースイメージバージョンをピン留め: 再現可能なビルドを確保
- 同じレイヤーでクリーンアップ: イメージサイズを削減
- ヘルスチェックを追加: コンテナーオーケストレーションを有効化
- 脆弱性をスキャン: Trivy、Snyk等を使用
- スリム/Alpineベースを使用: 攻撃面を最小化
- シークレットを保存しない: ランタイムインジェクションを使用
出力チェックリスト
最適化されたすべてのDockerfileには次のものを含める必要があります:
- ビルドと実行環境を分離するマルチステージビルド
- スリムまたはAlpineベースイメージ
- ピン留めされたベースイメージバージョン
- レイヤーキャッシュ最適化 (ソースの前に依存関係)
- 非rootユーザー設定
- 定義されたヘルスチェック
- .dockerignoreファイル
- イメージ内にシークレットなし
- インストールされたパッケージを最小化
- インストール時と同じレイヤーでクリーンアップ
- メタデータ用ラベル
- CIでのセキュリティスキャン
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- patricio0312rev
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/patricio0312rev/skills / ライセンス: MIT
関連スキル
superpowers-streamer-cli
SuperPowers デスクトップストリーマーの npm パッケージをインストール、ログイン、実行、トラブルシューティングできます。ユーザーが npm から `superpowers-ai` をセットアップしたい場合、メールまたは電話でサインインもしくはアカウント作成を行いたい場合、ストリーマーを起動したい場合、表示されたコントロールリンクを開きたい場合、後で停止したい場合、またはソースコードへのアクセスなしに npm やランタイムの一般的な問題から復旧したい場合に使用します。
catc-client-ops
Catalyst Centerのクライアント操作・監視機能 - 有線・無線クライアントのリスト表示・フィルタリング、MACアドレスによる詳細なクライアント検索、クライアント数分析、時間軸での分析、SSIDおよび周波数帯によるフィルタリング、無線トラブルシューティング機能を提供します。MACアドレスやIPアドレスでのクライアント検索、サイト別やSSID別のクライアント数集計、無線周波数帯の分布分析、Wi-Fi信号の問題調査が必要な場合に活用できます。
ci-cd-and-automation
CI/CDパイプラインの設定を自動化します。ビルドおよびデプロイメントパイプラインの構築または変更時に使用できます。品質ゲートの自動化、CI内のテストランナー設定、またはデプロイメント戦略の確立が必要な場合に活用します。
shipping-and-launch
本番環境へのリリース準備を行います。本番環境へのデプロイ準備が必要な場合、リリース前チェックリストが必要な場合、監視機能の設定を行う場合、段階的なロールアウトを計画する場合、またはロールバック戦略が必要な場合に使用します。
linear-release-setup
Linear Releaseに向けたCI/CD設定を生成します。リリース追跡の設定、LinearのCIパイプライン構築、またはLinearリリースとのデプロイメント連携を実施する際に利用できます。GitHub Actions、GitLab CI、CircleCIなど複数のプラットフォームに対応しています。
tracking-application-response-times
API エンドポイント、データベースクエリ、サービスコール全体にわたるアプリケーションのレスポンスタイムを追跡・最適化できます。パフォーマンス監視やボトルネック特定の際に活用してください。「レスポンスタイムを追跡する」「API パフォーマンスを監視する」「遅延を分析する」といった表現で呼び出せます。