简介:本文详细介绍如何使用GitHub Action实现Docker镜像的自动化构建与上传至GitHub Container Registry,涵盖环境配置、工作流设计、安全优化及故障排查,助力开发者提升CI/CD效率。
在容器化开发成为主流的今天,Docker镜像的构建与分发效率直接影响项目迭代速度。GitHub Action作为GitHub原生CI/CD工具,通过自动化工作流可实现从代码提交到镜像部署的全流程无缝衔接。相较于传统Jenkins方案,GitHub Action具有三大优势:
GitHub Container Registry(GHCR)作为官方容器镜像仓库,提供与代码仓库同源的安全管理,支持细粒度权限控制与漏洞扫描功能。通过GitHub Action实现镜像构建与推送,可构建完整的DevOps闭环。
进入GitHub仓库的Settings > Packages,确保:
repo和package权限最佳实践示例:
# 多阶段构建减少镜像体积FROM golang:1.21 as builderWORKDIR /appCOPY go.mod go.sum ./RUN go mod downloadCOPY . .RUN CGO_ENABLED=0 GOOS=linux go build -o /serverFROM alpine:3.18WORKDIR /COPY --from=builder /server /serverEXPOSE 8080CMD ["/server"]
关键优化点:
在仓库Settings > Secrets创建以下机密:
GHCR_USERNAME: GitHub用户名GHCR_TOKEN: 生成的PAT令牌DOCKER_BUILDKIT: 设为1启用BuildKit
name: Build and Push Docker Imageon:push:branches: [ main ]pull_request:branches: [ main ]jobs:build:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4- name: Set up Docker Buildxuses: docker/setup-buildx-action@v3- name: Login to GHCRuses: docker/login-action@v3with:registry: ghcr.iousername: ${{ secrets.GHCR_USERNAME }}password: ${{ secrets.GHCR_TOKEN }}- name: Extract metadataid: metauses: docker/metadata-action@v5with:images: ghcr.io/${{ github.repository }}/apptags: |type=semver,pattern={{version}}type=ref,event=branch- name: Build and pushuses: docker/build-push-action@v5with:context: .push: ${{ github.event_name != 'pull_request' }}tags: ${{ steps.meta.outputs.tags }}labels: ${{ steps.meta.outputs.labels }}cache-from: type=ghacache-to: type=gha,mode=max
cache-from: type=local,src=/tmp/.buildx-cachecache-to: type=local,dest=/tmp/.buildx-cache-new
通过docker/metadata-action自动处理:
docker/login-action替代直接凭证硬编码
- name: Enable Docker Content Trustrun: export DOCKER_CONTENT_TRUST=1
jobs:build:strategy:matrix:platform: [linux/amd64, linux/arm64]runs-on: ubuntu-lateststeps:- uses: docker/setup-qemu-action@v2- uses: docker/setup-buildx-action@v3with:platforms: ${{ matrix.platform }}
- name: Scan for vulnerabilitiesuses: aquasecurity/trivy-action@masterwith:image-ref: 'ghcr.io/${{ github.repository }}/app:latest'format: 'table'exit-code: '1'ignore-unfixed: trueseverity: 'CRITICAL,HIGH'
- name: Cache Docker layersuses: actions/cache@v3with:path: /tmp/.buildx-cachekey: ${{ runner.os }}-buildx-${{ github.sha }}restore-keys: |${{ runner.os }}-buildx-
| 错误现象 | 解决方案 |
|---|---|
denied: requested access to the resource is denied |
检查PAT权限和仓库可见性 |
layer does not exist |
清理缓存并重新构建 |
unauthorized: authentication required |
验证GHCR登录步骤 |
- name: Build with debugrun: docker build --no-cache --progress=plain .
actions/upload-artifact保存构建日志
# docker-compose.yml示例build:context: .dockerfile: Dockerfilex-bake:platforms:- linux/amd64- linux/arm64cache-from: type=ghacache-to: type=gha,mode=max
trivy image扫描
on:release:types: [published]jobs:deploy:environment: productionruns-on: ubuntu-lateststeps:- uses: docker/build-push-action@v5with:tags: ghcr.io/${{ github.repository }}/app:v${{ github.event.release.tag_name }}
- name: Run SASTuses: github/codeql-action/analyze@v2
- name: Generate SBOMuses: anchore/sbom-action@v0with:image: ghcr.io/${{ github.repository }}/appformat: cyclonedx-json
通过系统化的GitHub Action工作流设计,开发者可实现从代码提交到容器部署的全自动化,显著提升研发效率与部署可靠性。建议定期审查工作流配置,结合项目特性持续优化构建参数与缓存策略,构建适应企业级需求的容器化交付体系。