关于 deployment-pipeline
deployment-pipeline 面向配置 CI/CD 和发布应用的团队,规范从构建、测试到预发和生产的流程。内容涵盖阶段门禁、金丝雀发布、健康检查与回滚。
主要功能
- 01按四个门禁阶段组织发布
- 02运行测试和发布前检查
- 03在不同环境间晋级变更
- 04发布并监控生产金丝雀
- 05验证健康状态并回滚故障
适用场景
- 01搭建或修改 GitHub Actions 流水线
- 02生产发布前在预发环境验证
- 03通过金丝雀逐步推出变更
- 04处理部署或健康检查失败
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ hieutrtr/ ai1-skills --skill deployment-pipeline安装后在 Claude Code 中输入/deployment-pipeline确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/environment-config.mdgithub-actions-template.ymlrollback-runbook.mdscripts/deploy.shhealth-check.pymigration-dry-run.shsmoke-test.sh详细介绍
部署流水线
适用场景
在以下情况下启用此技能:
- 使用 GitHub Actions 设置或修改 CI/CD 流水线
- 将应用程序更改部署到预发布或生产环境
- 规划环境晋级策略(开发 -> 预发布 -> 生产)
- 实施部署前验证关卡
- 为已部署的服务配置运行状况检查和冒烟测试
- 规划或执行部署失败后的回滚流程
- 设置金丝雀或蓝绿部署策略
- 排查部署失败或流水线错误
输出: 将部署结果写入 deployment-report.md,包括状态、已部署版本、运行状况检查结果,以及必要时的回滚说明。
请勿将此技能用于:
- 构建或优化 Docker 镜像(使用
docker-best-practices) - 响应生产事故(使用
incident-response) - 设置监控或告警(使用
monitoring-setup) - 基础设施预配(Terraform、CloudFormation)
说明
流水线阶段概览
每次部署都必须严格遵循四阶段流水线。不得跳过任何阶段。
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐
│ BUILD │───>│ TEST │───>│ STAGING │───>│ PRODUCTION │
│ │ │ │ │ │ │ │
│ • Lint │ │ • Unit │ │ • Deploy │ │ • Canary 10% │
│ • Build │ │ • Integ │ │ • Smoke │ │ • Monitor │
│ • Image │ │ • E2E │ │ • QA │ │ • Full 100% │
└──────────┘ └──────────┘ └──────────┘ └──────────────┘
Gate: Gate: Gate: Gate:
Build pass Tests pass Smoke pass Health checks
No lint err Coverage ≥80% Manual approve Error rate <1%
阶段 1:构建
构建阶段用于验证代码质量并生成可部署的构件。
步骤:
- Lint 和格式检查 -- Python 运行
ruff check和ruff format --check;React 运行eslint和prettier --check - 类型检查 -- Python 运行
mypy;TypeScript 运行tsc --noEmit - 构建构件 -- 构建 Python wheel/sdist,构建 React 生产环境包
- 构建 Docker 镜像 -- 使用 git SHA 和分支名称作为标签
关卡条件: 所有检查均通过,镜像构建成功。
# GitHub Actions build stage
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Lint Python
run: ruff check src/ && ruff format --check src/
- name: Type check Python
run: mypy src/
- name: Build backend image
run: docker build -t app-backend:${{ github.sha }} -f Dockerfile.backend .
- name: Build frontend
run: npm ci && npm run build
- name: Build frontend image
run: docker build -t app-frontend:${{ github.sha }} -f Dockerfile.frontend .
阶段 2:测试
运行完整测试套件。切勿因部署“紧急”而跳过测试。
步骤:
- 单元测试 --
pytest tests/unit/ -v --cov=src --cov-report=xml - 集成测试 --
pytest tests/integration/ -v(需要测试数据库) - 前端测试 --
npm test -- --coverage - 端到端测试 -- 在测试环境中运行
npx playwright test - 安全扫描 -- Python 使用
pip-audit,Node 使用npm audit
关卡条件: 所有测试均通过,覆盖率 >= 80%,没有严重漏洞。
# GitHub Actions test stage
test:
needs: build
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_DB: testdb
POSTGRES_PASSWORD: testpass
ports: ['5432:5432']
redis:
image: redis:7-alpine
ports: ['6379:6379']
steps:
- uses: actions/checkout@v4
- name: Run unit tests
run: pytest tests/unit/ -v --cov=src --cov-report=xml
- name: Run integration tests
run: pytest tests/integration/ -v
env:
DATABASE_URL: postgresql://postgres:testpass@localhost:5432/testdb
- name: Check coverage threshold
run: coverage report --fail-under=80
阶段 3:预发布环境部署
部署到预发布环境,以便在生产环境部署前进行验证。
部署前检查清单:
- 所有测试均在 CI 中通过
- 已使用
scripts/migration-dry-run.sh测试数据库迁移 - 已验证预发布环境的环境变量
- 已妥善配置功能标记
- 已确认依赖服务可用
步骤:
- 运行迁移演练 -- 对预发布数据库克隆验证 Alembic 迁移
- 部署到预发布环境 -- 推送镜像、应用迁移、重启服务
- 运行冒烟测试 -- 针对预发布 URL 执行
scripts/smoke-test.sh - 运行运行状况检查 -- 对所有端点执行
scripts/health-check.py - 人工 QA -- 团队验证关键用户流程
关卡条件: 冒烟测试通过、运行状况检查正常、QA 验收通过。
阶段 4:生产环境部署
生产环境部署采用金丝雀策略,以尽量降低风险。
金丝雀部署步骤:
- 部署金丝雀(10% 流量) -- 将 10% 的流量路由到新版本
- 监控 10 分钟 -- 观察错误率、延迟和资源使用情况
- 评估金丝雀 -- 如果错误率 < 1%,且 p99 延迟在基线的 20% 以内,则继续
- 提升至 50% -- 将流量提高到 50%,监控 5 分钟
- 全面发布(100%) -- 完成部署
- 部署后冒烟测试 -- 运行完整的冒烟测试套件
Canary Timeline:
0 min 10 min 15 min 20 min
|--------|--------|--------|
10% Check 50% 100%
Deploy Metrics Ramp Full
OK? Up Rollout
|
No -> Rollback immediately
自动回滚触发条件:
- 金丝雀部署期间错误率超过 5%
- p99 延迟增加超过 50%
- 金丝雀实例的运行状况检查失败
- 内存使用率超过 90% 阈值
部署前验证
在任何部署前都运行以下验证。使用 scripts/deploy.sh --validate-only 进行演练。
后端验证:
# Verify migrations are consistent
alembic check
# Verify no pending migrations
alembic heads --verbose
# Test migration against staging clone
./skills/deployment-pipeline/scripts/migration-dry-run.sh \
--db-url "$STAGING_DB_URL" \
--output-dir ./deploy-validation/
# Verify all dependencies are pinned
pip-compile --dry-run requirements.in
前端验证:
# Verify build succeeds
npm run build
# Check bundle size limits
npx bundlesize
# Verify environment variables are set
node -e "const vars = ['REACT_APP_API_URL']; vars.forEach(v => { if(!process.env[v]) throw new Error(v + ' not set') })"
环境晋级
变更在不同环境之间的流转受严格规则约束。
| 方面 | 开发环境 | 预发布环境 | 生产环境 |
|---|---|---|---|
| 部署触发条件 | 推送到 main | 手动触发或测试通过后自动触发 | 需要手动批准 |
| 数据库 | 本地 PostgreSQL | 预发布 PostgreSQL | 生产 PostgreSQL(RDS) |
| 密钥 | .env 文件 | GitHub Secrets | AWS Secrets Manager |
| 日志级别 | DEBUG | INFO | WARNING |
| 功能标志 | 全部启用 | 按功能设置 | 逐步推出 |
| SSL | 自签名证书 | ACM 证书 | ACM 证书 |
| 副本数 | 1 | 2 | 3+(自动扩缩容) |
晋级规则:
- 代码必须通过上一阶段的所有关卡
- 数据库迁移必须向后兼容(不得在迁移窗口之外删除列)
- 必须在部署前配置环境变量
- 必须在部署前将功能标志设为正确状态
- 必须在生产环境部署前记录回滚计划
健康检查
每项服务都提供健康检查端点。部署流水线会在每次部署后验证这些端点。
必需的健康检查端点:
# FastAPI health check endpoints
@router.get("/health")
async def health():
"""Basic liveness check -- returns 200 if process is running."""
return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}
@router.get("/health/ready")
async def readiness(db: AsyncSession = Depends(get_db)):
"""Readiness check -- verifies all dependencies are accessible."""
checks = {}
# Database
try:
await db.execute(text("SELECT 1"))
checks["database"] = "ok"
except Exception as e:
checks["database"] = f"error: {str(e)}"
# Redis
try:
await redis.ping()
checks["redis"] = "ok"
except Exception as e:
checks["redis"] = f"error: {str(e)}"
all_ok = all(v == "ok" for v in checks.values())
return JSONResponse(
status_code=200 if all_ok else 503,
content={"status": "ready" if all_ok else "not_ready", "checks": checks}
)
部署期间的健康检查策略:
After deploy:
Wait 10s -> Check /health (liveness)
Wait 5s -> Check /health/ready (readiness)
Wait 5s -> Check /health/ready again (stability)
All pass -> Deployment successful
Any fail -> Trigger rollback
使用 scripts/health-check.py 自动执行健康检查:
python scripts/health-check.py \
--url https://staging.example.com \
--retries 3 \
--timeout 30 \
--output-dir ./health-results/
回滚流程
部署失败时,请立即按照以下回滚流程操作。完整的分步指南请参阅 references/rollback-runbook.md。
自动回滚(首选):
# Roll back to previous version
./skills/deployment-pipeline/scripts/deploy.sh \
--rollback \
--version "$PREVIOUS_VERSION" \
--output-dir ./rollback-results/
回滚决策矩阵:
| 信号 | 操作 | 时间要求 |
|---|---|---|
| 错误率 > 5% | 自动回滚 | 立即 |
| p99 延迟 > 基线的 2 倍 | 自动回滚 | 立即 |
| 健康检查失败 | 自动回滚 | 重试 2 次后 |
| 用户报告问题 | 手动决定是否回滚 | 15 分钟内 |
| 数据不一致 | 停止流量并调查 | 立即 |
数据库回滚注意事项:
- 优先采用仅向前迁移;避免在生产环境中使用
alembic downgrade - 如果必须撤销迁移,请使用新的向前迁移来撤销变更
- 移除代码引用的同一版本中,绝不能删除列或表
- 采用两阶段方案:阶段 1 部署新代码(向后兼容),阶段 2 删除旧列
GitHub Actions CI/CD
完整的 CI/CD 流水线定义在 .github/workflows/deploy.yml 中。完整模板请参阅 references/github-actions-template.yml。
工作流主要特性:
- 矩阵测试 -- 针对 Python 3.12 和 3.13 进行测试
- 缓存 -- 缓存 pip、npm 和 Docker 层,以加快构建速度
- 并发控制 -- 有新提交到达时,取消进行中的部署
- 环境保护 -- 生产环境需要手动批准
- 密钥管理 -- 按阶段使用 GitHub 环境密钥
# Key sections of the workflow
on:
push:
branches: [main]
workflow_dispatch:
inputs:
environment:
type: choice
options: [staging, production]
concurrency:
group: deploy-${{ github.ref }}
cancel-in-progress: true
jobs:
build: # Stage 1
test: # Stage 2 (needs: build)
staging: # Stage 3 (needs: test)
production: # Stage 4 (needs: staging, manual approval)
金丝雀部署
金丝雀部署会先将一小部分流量路由到新版本,再进行全面发布。
使用 Docker 和 Nginx 实现:
# nginx canary configuration
upstream backend {
server backend-stable:8000 weight=9; # 90% to stable
server backend-canary:8000 weight=1; # 10% to canary
}
金丝雀评估标准:
# Canary health evaluation
def evaluate_canary(metrics: dict) -> bool:
"""Return True if canary is healthy enough to proceed."""
checks = [
metrics["error_rate"] < 0.01, # < 1% error rate
metrics["p99_latency_ms"] < 500, # p99 under 500ms
metrics["memory_usage_pct"] < 85, # Memory under 85%
metrics["cpu_usage_pct"] < 75, # CPU under 75%
metrics["successful_health_checks"] >= 3, # 3+ consecutive passes
]
return all(checks)
金丝雀监控清单:
- 与基线相比的错误率(必须控制在 1% 以内)
- 与基线相比的延迟百分位数(p50、p95、p99)
- 资源利用率(CPU、内存)在阈值范围内
- 日志错误量没有增加
- 健康检查端点响应正常
- 依赖服务的指标没有恶化
部署脚本
以下脚本可自动执行部署任务:
| 脚本 | 用途 | 用法 |
|---|---|---|
scripts/deploy.sh | 部署主流程编排 | ./scripts/deploy.sh --env staging --output-dir ./results/ |
scripts/smoke-test.sh | 部署后冒烟测试 | ./scripts/smoke-test.sh --url https://staging.example.com --output-dir ./results/ |
scripts/health-check.py | 健康检查端点验证 | python scripts/health-check.py --url https://staging.example.com --output-dir ./results/ |
scripts/migration-dry-run.sh | 安全地测试迁移 | ./scripts/migration-dry-run.sh --db-url $DB_URL --output-dir ./results/ |
快速参考
部署到预发布环境:
./skills/deployment-pipeline/scripts/deploy.sh \
--env staging \
--version $(git rev-parse --short HEAD) \
--output-dir ./deploy-results/
部署到生产环境(使用金丝雀发布):
./skills/deployment-pipeline/scripts/deploy.sh \
--env production \
--version $(git rev-parse --short HEAD) \
--canary \
--output-dir ./deploy-results/
运行冒烟测试:
./skills/deployment-pipeline/scripts/smoke-test.sh \
--url https://staging.example.com \
--output-dir ./smoke-results/
紧急回滚:
./skills/deployment-pipeline/scripts/deploy.sh \
--rollback \
--env production \
--version $PREVIOUS_SHA \
--output-dir ./rollback-results/
输出文件
将部署结果写入 deployment-report.md:
# Deployment Report
## Summary
- **Environment:** staging | production
- **Version:** abc1234 (git SHA)
- **Status:** SUCCESS | FAILED | ROLLED_BACK
- **Timestamp:** 2024-01-15T14:30:00Z
- **Duration:** 12 minutes
## Pipeline Stages
| Stage | Status | Duration | Notes |
|-------|--------|----------|-------|
| Build | PASS | 3m | Image built: app:abc1234 |
| Test | PASS | 5m | 142 tests, 85% coverage |
| Staging | PASS | 2m | Smoke tests passed |
| Production | PASS | 2m | Canary 10% → 50% → 100% |
## Health Checks
- `/health` — 200 OK (12ms)
- `/health/ready` — 200 OK (45ms)
## Rollback Instructions
If issues occur, run:
\`\`\`bash
./scripts/deploy.sh --rollback --env production --version $PREV_SHA
\`\`\`
Previous version: def5678
## Next Steps
- Run `/monitoring-setup` to verify alerts are configured
- Run `/incident-response` if errors occur