Communitygithub.com

デプロイメントパターン

Webアプリケーション向けのデプロイメントワークフロー、CI/CDパイプライン、Dockerコンテナ化、ヘルスチェック、ロールバック戦略、および本番環境準備チェックリスト。CI/CDのセットアップ、アプリのコンテナ化、またはリリース前の本番環境準備確認を行う際に使用します。

デプロイメントパターン とは?

このスキルは、開発者がプロダクション向けのデプロイメントワークフローとCI/CDのベストプラクティスを迅速に実装するための包括的なガイドを提供します。ローリングデプロイ、ブルーグリーンデプロイ、カナリアデプロイといった主要なデプロイメント戦略と、それぞれの長所・短所・推奨ユースケースを詳しく説明します。Node.js、Go、Python/Django向けのマルチステージDockerfileの例、GitHub ActionsのCI/CDパイプラインテンプレート、ヘルスチェックエンドポイントの実装、Kubernetesプローブの設定、Twelve-Factor Appに基づく環境設定、そしてロールバック戦略や本番環境準備チェックリストも含まれています。これらのパターンは汎用的に設計されており、Claude Code、Cursor、Codexなど、AIエージェントがコード生成や設定ファイルの作成、デプロイメントの自動化を支援する際に活用できます。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/deployment-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

デプロイメントパターン は何をしますか?

プロダクションデプロイメントワークフローとCI/CDのベストプラクティス。

いつ使用するか

  • CI/CDパイプラインのセットアップ
  • アプリケーションのDocker化
  • デプロイメント戦略の計画(ブルーグリーン、カナリア、ローリング)
  • ヘルスチェックと readiness probe の実装
  • 本番リリースの準備
  • 環境固有の設定の構成

デプロイメント戦略

ローリングデプロイ(デフォルト)

インスタンスを段階的に置き換え — ロールアウト中は新旧両方のバージョンが同時に実行されます。

Instance 1: v1 → v2  (最初に更新)
Instance 2: v1        (まだ v1 を実行中)
Instance 3: v1        (まだ v1 を実行中)

Instance 1: v2
Instance 2: v1 → v2  (2番目に更新)
Instance 3: v1

Instance 1: v2
Instance 2: v2
Instance 3: v1 → v2  (最後に更新)

メリット: ゼロダウンタイム、段階的ロールアウト デメリット: 2つのバージョンが同時に実行される — 後方互換性が必要 使用するケース: 標準的なデプロイ、後方互換性のある変更

ブルーグリーンデプロイ

2つの同一環境を実行し、トラフィックをアトミックに切り替えます。

Blue  (v1) ← トラフィック
Green (v2)   アイドル中、新しいバージョンを実行

# 検証後:
Blue  (v1)   アイドル中(スタンバイになる)
Green (v2) ← トラフィック

メリット: 即時ロールバック(Blueに戻す)、クリーンな切り替え デメリット: デプロイ中に2倍のインフラストラクチャが必要 使用するケース: クリティカルなサービス、問題を一切許容しない場合

カナリアデプロイ

最初に新しいバージョンに少量のトラフィックをルーティングします。

v1: 95% のトラフィック
v2:  5% のトラフィック (カナリア)

# メトリクスが良好な場合:
v1: 50% のトラフィック
v2: 50% のトラフィック

# 最終:
v2: 100% のトラフィック

メリット: フルロールアウト前に実際のトラフィックで問題を検出できる デメリット: トラフィック分割インフラ、モニタリングが必要 使用するケース: 高トラフィックサービス、リスクの高い変更、フィーチャーフラグ

Docker

マルチステージDockerfile (Node.js)

# Stage 1: 依存関係のインストール
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production=false

# Stage 2: ビルド
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
RUN npm prune --production

# Stage 3: プロダクションイメージ
FROM node:22-alpine AS runner
WORKDIR /app

RUN addgroup -g 1001 -S appgroup && adduser -S appuser -u 1001
USER appuser

COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/package.json ./

ENV NODE_ENV=production
EXPOSE 3000

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

CMD ["node", "dist/server.js"]

マルチステージDockerfile (Go)

FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /server ./cmd/server

FROM alpine:3.19 AS runner
RUN apk --no-cache add ca-certificates
RUN adduser -D -u 1001 appuser
USER appuser

COPY --from=builder /server /server

EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://localhost:8080/health || exit 1
CMD ["/server"]

マルチステージDockerfile (Python/Django)

FROM python:3.12-slim AS builder
WORKDIR /app
RUN pip install --no-cache-dir uv
COPY requirements.txt .
RUN uv pip install --system --no-cache -r requirements.txt

FROM python:3.12-slim AS runner
WORKDIR /app

RUN useradd -r -u 1001 appuser
USER appuser

COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY . .

ENV PYTHONUNBUFFERED=1
EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=3s CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/')" || exit 1
CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "4"]

Dockerのベストプラクティス

# 良いプラクティス
- 特定のバージョンタグを使用する(node:latestではなくnode:22-alpine)
- マルチステージビルドでイメージサイズを最小化する
- 非rootユーザーとして実行する
- 依存関係ファイルを最初にコピーする(レイヤーキャッシュの活用)
- .dockerignoreを使用してnode_modules、.git、テストを除外する
- HEALTHCHECK命令を追加する
- docker-composeまたはk8sでリソース制限を設定する

# 悪いプラクティス
- rootとして実行する
- :latestタグを使用する
- リポジトリ全体を1つのCOPYレイヤーでコピーする
- プロダクションイメージに開発用依存関係をインストールする
- イメージ内にシークレットを保存する(環境変数またはシークレットマネージャーを使用する)

CI/CDパイプライン

GitHub Actions(標準パイプライン)

name: CI/CD

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

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm run typecheck
      - run: npm test -- --coverage
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: coverage
          path: coverage/

  build:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v5
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  deploy:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    environment: production
    steps:
      - name: 本番環境にデプロイ
        run: |
          # プラットフォーム固有のデプロイコマンド
          # Railway: railway up
          # Vercel: vercel --prod
          # K8s: kubectl set image deployment/app app=ghcr.io/${{ github.repository }}:${{ github.sha }}
          echo "Deploying ${{ github.sha }}"

パイプラインのステージ

PRがオープンされたとき:
  lint → typecheck → ユニットテスト → 統合テスト → プレビューデプロイ

mainにマージされたとき:
  lint → typecheck → ユニットテスト → 統合テスト → イメージビルド → stagingにデプロイ → スモークテスト → 本番にデプロイ

ヘルスチェック

ヘルスチェックエンドポイント

// シンプルなヘルスチェック
app.get("/health", (req, res) => {
  res.status(200).json({ status: "ok" });
});

// 詳細なヘルスチェック(内部モニタリング用)
app.get("/health/detailed", async (req, res) => {
  const checks = {
    database: await checkDatabase(),
    redis: await checkRedis(),
    externalApi: await checkExternalApi(),
  };

  const allHealthy = Object.values(checks).every(c => c.status === "ok");

  res.status(allHealthy ? 200 : 503).json({
    status: allHealthy ? "ok" : "degraded",
    timestamp: new Date().toISOString(),
    version: process.env.APP_VERSION || "unknown",
    uptime: process.uptime(),
    checks,
  });
});

async function checkDatabase(): Promise<HealthCheck> {
  try {
    await db.query("SELECT 1");
    return { status: "ok", latency_ms: 2 };
  } catch (err) {
    return { status: "error", message: "Database unreachable" };
  }
}

Kubernetesプローブ

livenessProbe:
  httpGet:
    path: /health
    port: 3000
  initialDelaySeconds: 10
  periodSeconds: 30
  failureThreshold: 3

readinessProbe:
  httpGet:
    path: /health
    port: 3000
  initialDelaySeconds: 5
  periodSeconds: 10
  failureThreshold: 2

startupProbe:
  httpGet:
    path: /health
    port: 3000
  initialDelaySeconds: 0
  periodSeconds: 5
  failureThreshold: 30    # 30 * 5s = 150秒の最大起動時間

環境設定

Twelve-Factor Appパターン

# すべての設定は環境変数を介して — コード内には決して記述しない
DATABASE_URL=postgres://user:pass@host:5432/db
REDIS_URL=redis://host:6379/0
API_KEY=${API_KEY}           # シークレットマネージャーから注入
LOG_LEVEL=info
PORT=3000

# 環境固有の動作
NODE_ENV=production          # または staging, development
APP_ENV=production           # 明示的なアプリケーション環境

設定のバリデーション

import { z } from "zod";

const envSchema = z.object({
  NODE_ENV: z.enum(["development", "staging", "production"]),
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  REDIS_URL: z.string().url(),
  JWT_SECRET: z.string().min(32),
  LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
});

// 起動時にバリデーション — 設定が間違っている場合は早期に失敗
const env = envSchema.parse(process.env);

ロールバック戦略

即時ロールバック

# Docker/Kubernetes: 以前のイメージを指定
kubectl rollout undo deployment/app

# Vercel: 以前のデプロイをプロモート
vercel rollback

# Railway: 以前のコミットを再デプロイ
railway up --commit <previous-sha>

# データベース: マイグレーションをロールバック(元に戻せる場合)
npx prisma migrate resolve --rolled-back <migration-name>

ロールバックチェックリスト

  • 以前のイメージ/アーティファクトが利用可能でタグ付けされていること
  • データベースマイグレーションが後方互換性があること(破壊的な変更がないこと)
  • フィーチャーフラグでデプロイなしに新機能を無効にできること
  • エラーレートの急上昇に対するモニタリングアラートが設定されていること
  • 本番リリース前にstagingでロールバックがテストされていること

本番環境準備チェックリスト

本番デプロイ前:

アプリケーション

  • すべてのテストが合格している(ユニット、統合、E2E)
  • コードや設定ファイルにハードコードされたシークレットがない
  • エラーハンドリングがすべてのエッジケースをカバーしている
  • ログが構造化されており(JSON)、PIIを含んでいない
  • ヘルスチェックエンドポイントが意味のあるステータスを返す

インフラストラクチャ

  • Dockerイメージが再現可能にビルドされる(バージョン固定)
  • 環境変数が文書化され、起動時にバリデーションされている
  • リソース制限が設定されている(CPU、メモリ)
  • 水平スケーリングが構成されている(最小/最大インスタンス数)
  • すべてのエンドポイントでSSL/TLSが有効化されている

モニタリング

  • アプリケーションメトリクスがエクスポートされている(リクエストレート、レイテンシ、エラー数)
  • エラーレートがしきい値を超えた場合のアラートが設定されている
  • ログ集約が設定されている(構造化ログ、検索可能)
  • ヘルスエンドポイントのアップタイムモニタリングが設定されている

セキュリティ

  • 依存関係がCVEに対してスキャンされている
  • CORSが許可されたオリジンのみに設定されている
  • パブリックエンドポイントにレート制限が有効化されている
  • 認証と認可が検証されている
  • セキュリティヘッダーが設定されている(CSP、HSTS、X-Frame-Options)

運用

  • ロールバック計画が文書化されテストされている
  • データベースマイグレーションが本番規模のデータに対してテストされている
  • 一般的な障害シナリオのためのRunbookが用意されている
  • オンコールローテーションとエスカレーションパスが定義されている

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル