Communitygithub.com

部署模式

部署工作流程、CI/CD 管線模式、Docker 容器化、健康檢查、回滾策略以及網頁應用程式的生產就緒檢查清單。適用於設定 CI/CD、將應用程式容器化,或在發佈前檢查生產就緒狀態。

部署模式 是什麼?

此「部署模式」技能為 AI 代理(如 Claude Code、Cursor、Codex)提供了一個全面的參考指南,用於處理生產級網頁應用程式的部署工作流程和 CI/CD 最佳實踐。它涵蓋了主要的部署策略(滾動式、藍綠部署、金絲雀部署),並附有清晰的圖解來說明流量轉換,同時也提供了在 Node.js、Go 及 Python/Django 等多種環境中的實作 Dockerfile 範例。此技能支援 GitHub Actions 等 CI/CD 平台,並詳細說明了如何設定多階段管線,包括測試、建置和部署。此外,它還提供了實用的健康檢查端點實作、Kubernetes 探針配置、遵循 12-Factor App 原則的環境設定、資料庫回滾及功能標誌等回滾策略,以及一份詳盡的生產就緒檢查清單。此技能對於正在設定新專案的 CI/CD、規劃部署策略,或是在重大發佈前確保應用程式穩定性與安全性的開發人員特別有幫助。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/deployment-patterns

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

部署模式 是做什麼的?

生產部署工作流程與 CI/CD 最佳實務。

啟用時機

  • 設定 CI/CD 管線
  • 將應用程式 Docker 化
  • 規劃部署策略(藍綠、金絲雀、滾動)
  • 實作健康檢查與就緒探測
  • 準備生產發佈
  • 配置環境特定設定

部署策略

滾動部署(預設)

逐步取代執行個體——在推出過程中,新舊版本會同時執行。

Instance 1: v1 → v2  (先更新)
Instance 2: v1        (仍在執行 v1)
Instance 3: v1        (仍在執行 v1)

Instance 1: v2
Instance 2: v1 → v2  (第二個更新)
Instance 3: v1

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

優點: 零停機時間、逐步推出 缺點: 兩個版本同時執行——需要向後相容的變更 使用時機: 標準部署、向後相容的變更

藍綠部署

執行兩個相同的環境。原子性地切換流量。

Blue  (v1) ← 流量
Green (v2)   空閒,執行新版本

# 驗證後:
Blue  (v1)   空閒(成為備用)
Green (v2) ← 流量

優點: 即時回滾(切回藍色)、乾淨的切換 缺點: 部署期間需要 2 倍的基礎設施 使用時機: 關鍵服務、對問題零容忍

金絲雀部署

先將一小部分流量導向新版本。

v1: 95% 的流量
v2:  5% 的流量  (金絲雀)

# 如果指標良好:
v1: 50% 的流量
v2: 50% 的流量

# 最終:
v2: 100% 的流量

優點: 在全面推出前,用真實流量捕捉問題 缺點: 需要流量分割基礎設施與監控 使用時機: 高流量服務、高風險變更、功能標誌

Docker

多階段 Dockerfile (Node.js)

# 階段 1:安裝相依套件
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production=false

# 階段 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

# 階段 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:22-alpine, 而非 node:latest)
- 多階段建置以最小化映像檔大小
- 以非 root 使用者執行
- 先複製相依套件檔案(圖層快取)
- 使用 .dockerignore 排除 node_modules、.git、tests
- 加入 HEALTHCHECK 指令
- 在 docker-compose 或 k8s 中設定資源限制

# 不良實務
- 以 root 執行
- 使用 :latest 標籤
- 在一個 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 "正在部署 ${{ 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: "資料庫無法連線" };
  }
}

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-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"),
});

// 啟動時驗證——如果配置錯誤則快速失敗
export 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 環境測試回滾

生產就緒檢查清單

在任何生產部署之前:

應用程式

  • 所有測試通過(單元、整合、端對端)
  • 程式碼或配置檔案中無硬編碼密碼
  • 錯誤處理涵蓋所有邊緣情況
  • 日誌結構化(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.

相關技能