21.2 GitHub Actions

GitHub Actions 是 GitHub 推出的一款 CI/CD 工具。

我們可以在每個 jobstep 中使用 Docker 執行建立步驟。

21.2.1 最小可用範例

更多語法、許可權模型和可用 action,請以 GitHub Actions 官方文件 為準。

在倉庫根目錄建立 .github/workflows/ci.yml

name: CI

on:
  push:
  pull_request:

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: docker/setup-buildx-action@v4
      - uses: docker/build-push-action@v7
        with:
          context: .
          push: false
          tags: local/test:ci

該範例會在 GitHub Actions 中建立當前倉庫的 Docker 映象(不推送到 registry)。

21.2.2 建立並推送到 Registry

實際專案中通常需要在 CI 中建立映象並推送到容器 Registry。以下範例展示了多階段建立 + 登入 + 推送的完整流程:

name: Build and Push

on:
  push:
    branches: [main]

permissions:
  contents: read
  packages: write

jobs:
  build-push:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - uses: docker/setup-buildx-action@v4

      - uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          tags: |
            ghcr.io/${{ github.repository }}:${{ github.sha }}
            ghcr.io/${{ github.repository }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: mode=max
          sbom: true

關鍵說明:

  • docker/login-action 負責認證,支援 Docker Hub、GHCR、ECR 等主流 Registry。
  • cache-from / cache-to 使用 GitHub Actions 原生快取(type=gha),無需額外設定即可加速增量建立。
  • 標籤同時使用 commit hash 和 latest,兼顧版本追溯與部署便利。
  • provenance: mode=maxsbom: true 會把建立來源證明和 SBOM 附加到推送的映象上;只做本地 load: true 的建立無法完整保留這些 attestation。

21.2.3 最佳實踐

  • 生產流水線要按完整 commit SHA 固定第三方 action;範例中使用 @v4 / @v6 只是為了可讀性,仍屬於信任 tag 維護者的取捨,不能等同於不可變引用。
  • 設定最小許可權(例如 contents: read),需要寫入許可權時再開啟。
  • 需要依賴快取時,優先使用官方支援的快取方案(例如針對語言套件管理器的 cache 或 BuildKit cache)。
  • 敏感憑據(Registry 密碼、Deploy Key 等)一律透過 secrets 注入,禁止硬編碼。
  • 多平臺建立可在 build-push-action 中新增 platforms: linux/amd64,linux/arm64

如果你需要在某個步驟裡直接執行容器映象(而不是建立映象),可以使用 docker:// 語法:

- name: Run container step
  uses: docker://golang:alpine
  with:
    args: go version
第 168 页,共 196 页
使用 mdPress 构建