mirror of
https://github.com/yeasy/docker_practice.git
synced 2026-08-10 08:27:25 +00:00
- 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
2.8 KiB
2.8 KiB
21.2 GitHub Actions
GitHub Actions 是 GitHub 推出的一款 CI/CD 工具。
我们可以在每个 job 的 step 中使用 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
关键说明:
docker/login-action负责认证,支持 Docker Hub、GHCR、ECR 等主流 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:// 语法:
- name: Run container step
uses: docker://golang:alpine
with:
args: go version