Communitygithub.com

デプロイメントパターン

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

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

このスキルは、Webアプリケーションの本番デプロイに必要なベストプラクティスを包括的に提供します。ローリングデプロイ、ブルーグリーンデプロイ、カナリアデプロイといった主要なデプロイメント戦略の説明と選択基準を示し、それぞれのメリット・デメリットや使用すべき場面を詳述します。また、Node.js、Go、Python(Django)向けのマルチステージDockerfileの実例を通じて、コンテナイメージの軽量化とセキュリティ向上の方法を学べます。GitHub Actionsを用いたCI/CDパイプラインの設定、ヘルスチェックエンドポイントの実装(Kubernetesプローブ含む)、環境設定の12要素アプリパターン、ロールバック手順、本番リリース前のチェックリストなど、実践的な内容が含まれています。このスキルはClaude Code、Cursor、Codexなどの開発者ツールと連携し、ユーザーがコード生成や問題解決を依頼する際、自動的に関連するデプロイメント知識を提供します。

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

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

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

ドキュメント

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

本番環境のデプロイメントワークフローとCI/CDのベストプラクティス。

アクティベート条件

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

デプロイメント戦略

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

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

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% of traffic
v2:  5% of traffic  (カナリア)

# メトリクスが良好な場合:
v1: 50% of traffic
v2: 50% of traffic

# 最終:
v2: 100% of traffic

メリット: 本番トラフィックで問題を早期に発見できる デメリット: トラフィック分割インフラとモニタリングが必要 使用すべき場面: 高トラフィックサービス、リスクの高い変更、フィーチャーフラグ

Docker

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

# Stage 1: Install dependencies
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production=false

# Stage 2: Build
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: Production image
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:22-alpine、node:latestは避ける)
- マルチステージビルドでイメージサイズを最小化する
- 非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: Deploy to production
        run: |
          # Platform-specific deployment command
          # Railway: railway up
          # Vercel: vercel --prod
          # K8s: kubectl set image deployment/app app=ghcr.io/${{ github.repository }}:${{ github.sha }}
          echo "Deploying ${{ github.sha }}"

パイプラインステージ

PR opened:
  lint → typecheck → unit tests → integration tests → preview deploy

Merged to main:
  lint → typecheck → unit tests → integration tests → build image → deploy staging → smoke tests → deploy production

ヘルスチェック

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

// 簡易ヘルスチェック
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 = 150s 最大起動時間

環境設定

12要素アプリパターン

# すべての設定は環境変数を経由 — コード内に記述しない
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>

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

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

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

本番デプロイ前の確認事項:

アプリケーション

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

インフラ

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

モニタリング

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

セキュリティ

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

運用

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

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

関連スキル