Communitygithub.com

部署模式

部署工作流程、CI/CD 流水線模式、Docker 容器化、健康檢查、回滾策略以及 Web 應用程式的生產就緒檢查清單。在設定 CI/CD、容器化應用程式或發布前檢查生產就緒度時使用。

部署模式 是什麼?

此技能為開發人員和 AI 代理提供了一套全面、可立即使用的部署模式與最佳實務,涵蓋整個生產部署生命週期。它支援多種部署策略(滾動式、藍綠部署、金絲雀部署),並提供其實作方式、優缺點以及適用場景的詳細說明。此外,它還提供了針對 Node.js、Go 和 Python/Django 的實用 Docker 多階段建構範例,以及 Docker 和 CI/CD 管道(包括 GitHub Actions 範例)的標準最佳實務。健康檢查實作涵蓋簡單端點、詳細端點及 Kubernetes 探針,而環境配置則遵循 12-Factor 應用程式模式,並包含類型安全的驗證(使用 Zod)。最後,它提供了一個結構化的回滾策略(包括命令)和一份詳盡的生產就緒檢查清單,涵蓋應用程式、基礎架構、監控、安全性和營運層面。此技能對於使用主要雲端平台(Kubernetes、Vercel、Railway)的團隊,在設定 CI/CD、容器化應用程式或規劃發布時極具價值。

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

在你喜歡的 AI 中提問

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

說明文件

部署模式 是做什麼的?

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

啟動時機

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

部署策略

滾動部署(預設)

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

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  (最後更新)

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

藍綠部署

執行兩個相同的環境。以原子方式切換流量。

藍色 (v1) ← 流量
綠色 (v2)   空閒,正在執行新版本

# 驗證後:
藍色 (v1)   空閒(成為備用環境)
綠色 (v2) ← 流量

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

金絲雀部署

先將一小部分流量路由到新版本。

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、測試
- 加入 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: Deploy to production
        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 → 單元測試 → 整合測試 → 建構映像檔 → 部署到暫存環境 → 煙霧測試 → 部署到生產環境

健康檢查

健康檢查端點

// 簡單健康檢查
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 應用程式模式

# 所有配置都透過環境變數 — 絕不寫在程式碼中
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>

回滾檢查清單

  • 先前的映像檔/成品可用且已標記
  • 資料庫遷移是向後相容的(無破壞性變更)
  • 功能開關可以在無需部署的情況下停用新功能
  • 已配置針對錯誤率飆升的監控告警
  • 在生產環境發布前,已於暫存環境測試回滾

生產就緒檢查清單

在任何生產環境部署之前:

應用程式

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

相關技能