GitHub Actions 的门槛很低(写个 YAML 就能跑),但写好不简单。我们把它从”能跑单测”扩展到”测试 + 构建镜像 + 部署”后,踩的坑主要集中在缓存、权限和并发上。
最小可用的 workflow
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| name: CI
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: 20 cache: npm - run: npm ci - run: npm run lint - run: npm test
|
setup-node 的 cache: npm 自动缓存 ~/.npm,key 是 lock 文件的 hash。这一行比手写 actions/cache 更省事,很多人不知道。
matrix:多版本并行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| jobs: test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: node: [18, 20, 22] os: [ubuntu-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node }} cache: npm - run: npm ci - run: npm test
|
6 个组合并行跑。fail-fast: false 很关键——默认是 true,第一个失败就取消其余任务,你就不知道其他版本是不是也有问题。
Windows runner 比 Linux 慢很多(我们的测试从 1 分 20 秒变成 4 分 30 秒)。如果不是必须,只在 Linux 上跑;需要跨平台的场景可以拆分:
1 2 3 4 5 6 7 8 9 10 11
| strategy: matrix: include: - os: ubuntu-latest node: 18 - os: ubuntu-latest node: 20 - os: ubuntu-latest node: 22 - os: windows-latest node: 20
|
多 job 与依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| jobs: lint: runs-on: ubuntu-latest steps: [...]
test: runs-on: ubuntu-latest steps: [...]
build: needs: [lint, test] runs-on: ubuntu-latest steps: [...]
deploy: needs: build if: github.ref == 'refs/heads/main' && github.event_name == 'push' runs-on: ubuntu-latest steps: [...]
|
needs 形成 DAG,不同分支的任务并行跑。if 里可以访问 github.*、env.*、steps.*.outputs.*。
job 之间不共享文件系统(每个 job 是独立机器),要传文件必须用 artifact:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| build: steps: - run: npm run build - uses: actions/upload-artifact@v4 with: name: dist path: dist/ retention-days: 3
deploy: needs: build steps: - uses: actions/download-artifact@v4 with: name: dist path: dist/
|
注意 v4 的 upload-artifact 不再支持同名 artifact 重复上传(v3 可以),并发上传同名会报错。matrix 场景要用 name: dist-${{ matrix.node }}。
缓存:收益最大也最容易错
1 2 3 4 5 6 7 8
| - uses: actions/cache@v4 with: path: | ~/.npm node_modules key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node-
|
三个要点:
1. key 要包含依赖的变化点
hashFiles('**/package-lock.json') 在 lock 变化时生成新的 key,缓存自动失效。
2. restore-keys 是”部分命中”
新的 key 不存在时,会找前缀匹配的最新缓存。这样 lock 变了也能复用大部分(npm 会增量更新)。
3. 缓存 node_modules 有风险
跨平台/跨 Node 版本的 node_modules 可能包含不兼容的原生模块(.node 文件)。安全做法是只缓存 ~/.npm(下载缓存),让 npm ci 每次都重建 node_modules。
我们的数据:只缓存 ~/.npm 时安装依赖 18 秒;缓存 node_modules 时 4 秒,但偶尔出现平台不匹配的诡异错误。最后选了前者,稳定优先。
缓存的作用域:
| 分支 |
能否读 main 的缓存 |
| main |
能读自己的 |
| feature 分支 |
能读 main 的(作为 restore-keys 兜底) |
| fork 的 PR |
不能(安全隔离) |
最后一条很容易踩:从 fork 提的 PR,缓存全部 miss,CI 会慢很多。
不要忘记 permissions
1 2
| permissions: contents: read
|
默认 GITHUB_TOKEN 权限很宽(可以写仓库)。最小权限原则在这里是硬要求——如果你的 workflow 被恶意 PR 注入,宽权限就是灾难。
只需要打 tag/发布时:
1 2 3
| permissions: contents: write packages: write
|
构建并推送镜像
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| jobs: image: needs: [test] runs-on: ubuntu-latest permissions: contents: read packages: write 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/metadata-action@v5 id: meta with: images: ghcr.io/${{ github.repository }} tags: | type=sha,prefix= type=ref,event=branch type=semver,pattern={{version}}
- uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max
|
cache-from: type=gha 是 GitHub Actions 专用的构建缓存后端,比自建 registry 缓存简单。mode=max 会缓存中间层(体积大但命中率高)。
metadata-action 会自动生成 tag:sha-abc1234、main、1.2.3。不要用 latest 作为唯一 tag——回滚时无法确定是哪个版本。
密钥管理
1 2 3 4
| - run: ./deploy.sh env: SSH_KEY: ${{ secrets.SSH_KEY }} API_TOKEN: ${{ secrets.API_TOKEN }}
|
三类来源:
| 来源 |
用途 |
| Repository secrets |
单个仓库共用 |
| Environment secrets |
按环境(production/staging)隔离,可配审批 |
| Organization secrets |
组织内共享 |
fork PR 拿不到 secrets——这是安全设计,不是 bug。如果你的 CI 需要 secrets 才能跑(比如要连测试数据库),fork PR 就会失败。解法是用 pull_request_target(危险,慎用)或者跳过这类测试:
1 2
| - if: github.event.pull_request.head.repo.full_name == github.repository run: npm run test:integration
|
OIDC 是更好的方案:不用存长期密钥,让 Actions 临时换取云厂商凭证:
1 2 3 4 5 6 7 8
| permissions: id-token: write contents: read
- uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789:role/github-actions aws-region: ap-northeast-1
|
这样没有任何长期密钥存在 GitHub 里,泄露风险大幅降低。
并发控制
1 2 3
| concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true
|
两个效果:
- 同一分支连推 3 次,前两次的 workflow 会被取消(省时间)
- 部署场景要不取消,避免部署到一半被打断:
1 2 3
| concurrency: group: deploy-production cancel-in-progress: false
|
部署必须用固定的 group(不带 github.ref),否则两个分支可以同时部署到同一个环境。
条件执行与失败处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| - if: github.ref == 'refs/heads/main'
- if: always()
- if: failure()
- run: | if git diff --quiet HEAD^ HEAD -- src/; then echo "changed=false" >> $GITHUB_OUTPUT else echo "changed=true" >> $GITHUB_OUTPUT fi
|
always() 常用来上传测试报告:
1 2 3 4 5
| - uses: actions/upload-artifact@v4 if: always() with: name: coverage path: coverage/
|
不写 if: always() 的话,测试失败了报告就不会上传——而你恰恰在失败时最需要看报告。
超时与重试
1 2 3
| jobs: test: timeout-minutes: 15
|
默认超时 6 小时。一个卡住的测试会白烧 6 小时的额度。每个 job 都该设一个合理的超时。
重试没有原生支持,常见做法:
1 2 3 4 5
| - uses: nick-fields/retry@v3 with: timeout_minutes: 10 max_attempts: 3 command: npm run test:e2e
|
但重试掩盖了不稳定测试。我们只对 E2E(有网络/浏览器因素)用重试,单元测试不允许重试。
复用:composite action 与 reusable workflow
composite action(在仓库内复用步骤):
1 2 3 4 5 6 7 8 9 10 11 12
| name: Setup description: 安装 Node 与依赖 runs: using: composite steps: - uses: actions/setup-node@v4 with: node-version: 20 cache: npm - run: npm ci shell: bash
|
1 2 3
| - uses: actions/checkout@v4 - uses: ./.github/actions/setup
|
注意 composite action 里每个 run 都要写 shell,否则报错。
reusable workflow(跨仓库复用):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| on: workflow_call: inputs: node-version: type: string default: '20'
jobs: ci: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: ${{ inputs.node-version }} - run: npm ci && npm test
|
1 2 3 4 5 6
| jobs: ci: uses: myorg/ci-workflows/.github/workflows/node-ci.yml@main with: node-version: '20'
|
多仓库统一 CI 时这个很有用。注意调用方不能再用 steps,只能传 with 和 secrets: inherit。
踩过的坑
1. actions/checkout 默认只拉一个 commit
做 git diff HEAD^ HEAD 判断变更时会失败(没有父提交)。要加:
1 2 3
| - uses: actions/checkout@v4 with: fetch-depth: 2
|
2. $GITHUB_OUTPUT 换行问题
1 2 3 4 5 6 7
| echo "content=$VALUE" >> $GITHUB_OUTPUT
echo "content<<EOF" >> $GITHUB_OUTPUT echo "$VALUE" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT
|
3. secrets 在 if 里不可用
1 2
| if: secrets.DEPLOY_KEY != ''
|
要用 job 级环境变量做中转:
1 2
| env: HAS_KEY: ${{ secrets.DEPLOY_KEY != '' }}
|
4. ubuntu-latest 的版本会变
ubuntu-latest 从 20.04 升到 22.04、24.04,某些依赖(比如旧版 libssl)会突然不可用。生产流程建议锁定版本:runs-on: ubuntu-22.04。
5. 缓存导致”本地能过 CI 不能过”
镜像/缓存里的 node_modules 和 lock 不同步。出现诡异问题时先删缓存(GitHub 的 Actions 页面可以 delete cache)。
6. 定时任务不是整点触发
1 2 3
| on: schedule: - cron: '0 2 * * *'
|
GitHub 明确说明高峰期会延迟(可能 10-30 分钟)。对时间敏感的任务不要依赖 cron 精确性。而且 schedule 只在默认分支生效。
7. 账单
公开仓库免费,私有仓库有免费额度(Linux 2000 分钟/月)。Windows 和 macOS 消耗倍率是 2x / 10x。我们的一个 Windows matrix 把额度烧掉一大半——查账单才发现。
一份完整的工作流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| name: CI/CD
on: push: branches: [main] pull_request:
permissions: contents: read
concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env: NODE_VERSION: '20'
jobs: quality: runs-on: ubuntu-latest timeout-minutes: 15 strategy: fail-fast: false 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 run lint - run: npm run typecheck - run: npm test -- --coverage - uses: actions/upload-artifact@v4 if: always() && matrix.node == 20 with: name: coverage path: coverage/
e2e: runs-on: ubuntu-latest timeout-minutes: 20 needs: quality steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} cache: npm - run: npm ci - run: npx playwright install --with-deps chromium - run: npm run test:e2e - uses: actions/upload-artifact@v4 if: failure() with: name: playwright-traces path: test-results/
deploy: needs: [quality, e2e] if: github.ref == 'refs/heads/main' && github.event_name == 'push' runs-on: ubuntu-latest timeout-minutes: 20 environment: production concurrency: group: deploy-production cancel-in-progress: false steps: - uses: actions/checkout@v4 - uses: ./.github/actions/setup - run: ./scripts/deploy.sh env: DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
小结
GitHub Actions 上手成本低,但四个点决定了它能不能放心用在生产:
- 权限最小化(
permissions)—— 防止 PR 注入
- 并发控制(
concurrency)—— 防止部署打架
- 超时(
timeout-minutes)—— 防止烧额度
- 缓存 key 设计(
hashFiles + restore-keys)—— 决定 CI 快不快
一个观察:CI 从 8 分钟优化到 3 分钟,对团队的影响比想象中大很多。8 分钟意味着”提交后去看会儿别的”,上下文切换的成本远大于 5 分钟本身。CI 速度是开发者体验的一部分。