Files
docker_practice/21_case_devops/21.2_github_actions.md
T
yeasy 8b9e4518c8 docs(content): add Mac alternatives, K8s transition guide, CI/CD registry push example
- Add OrbStack/Colima comparison table to Mac install chapter (3.7.4)
- Add Docker→K8s concept mapping paragraph to Ch13 intro
- Add KubeKey/RKE2 deployment tool notes to Ch14
- Add production image checklist to Dockerfile chapter summary
- Add build-and-push-to-registry workflow example to GitHub Actions section
- Expand Ch18 security summary with dimension table
2026-05-21 21:33:58 -07:00

99 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 21.2 GitHub Actions
GitHub [Actions](https://github.com/features/actions) 是 GitHub 推出的一款 CI/CD 工具。
我们可以在每个 `job` `step` 中使用 Docker 执行构建步骤
### 21.2.1 最小可用示例
更多语法权限模型和可用 action请以 [GitHub Actions 官方文档](https://docs.github.com/en/actions) 为准。
在仓库根目录创建 `.github/workflows/ci.yml`
```yaml
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以下示例展示了多阶段构建 + 登录 + 推送的完整流程
```yaml
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
```
关键说明
* `docker/login-action` 负责认证支持 Docker HubGHCRECR 等主流 Registry
* `cache-from` / `cache-to` 使用 GitHub Actions 原生缓存`type=gha`),无需额外配置即可加速增量构建
* 标签同时使用 commit hash `latest`兼顾版本追溯与部署便利
### 21.2.3 最佳实践
* 固定 action 的主版本例如 `@v4` / `@v6`),避免使用 `@master` 这类浮动引用
* 设置最小权限例如 `contents: read`),需要写入权限时再打开
* 需要依赖缓存时优先使用官方支持的缓存方案例如针对语言包管理器的 cache BuildKit cache)。
* 敏感凭据Registry 密码Deploy Key 一律通过 `secrets` 注入禁止硬编码
* 多平台构建可在 `build-push-action` 中添加 `platforms: linux/amd64,linux/arm64`
如果你需要在某个步骤里直接运行容器镜像而不是构建镜像),可以使用 `docker://` 语法
```yaml
- name: Run container step
uses: docker://golang:alpine
with:
args: go version
```