GitHub Actions CI/CD
GitHub 原生 CI/CD,工作流、可复用工作流和组合 action。
CI/CD进阶
为什么
GitHub Actions 内置 GitHub — 无外部 CI 服务。工作流是 .github/workflows 中 YAML,含矩阵构建、密钥和 10k+ 市场 action。
何时使用
GitHub 上项目用 GitHub Actions。复杂自托管 runner 避免(用 Jenkins)。
如何做
1. 工作流 — .github/workflows/ci.yml
2. 触发 — on: push、pull_request、schedule
3. 作业 — runs-on: ubuntu-latest
4. 步骤 — uses: actions/checkout@v4
5. 矩阵 — strategy: matrix 多版本
6. 密钥 — ${{ secrets.NAME }}
7. 缓存 — actions/cache 依赖
示例
# .github/workflows/ci.yml
name: CI
on: { push: { branches: [main] }, pull_request: {} }
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix: { node: [18, 20, 22] }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: ${{ matrix.node }}, cache: npm }
- run: npm ci
- run: npm test
- run: npm run build
deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm run build
- run: npx vercel --prod --token ${{ secrets.VERCEL_TOKEN }}
常见问题
- ⚠工作流未触发 — 检查 on: 语法和分支过滤
- ⚠密钥不可用 — 仓库设置定义,非工作流文件
- ⚠环境间配置漂移 — 使用基础设施即代码(Terraform/Pulumi)保持 dev/staging/prod 一致
最佳实践
- ✓用可复用工作流 — DRY,经 workflow_call 跨仓共享
- ✓action 固定 SHA — 非 @v4(可变标签),用 @v4 → commit SHA 安全
- ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求