从零搭建 CI/CD 流水线:GitHub Actions + ArgoCD + K8s

Mei Lin | 2026-08-26T23:02:18 | DevOps, Cloud

完整演示从代码提交到自动部署的 GitOps 流水线搭建过程,涵盖构建、测试、镜像推送、自动同步。

# 从零搭建 CI/CD 流水线 ## 整体架构 ``` 代码提交 -> GitHub Actions (CI) -> 单元测试 -> 构建 Docker 镜像 -> 推送到 ECR -> 更新 K8s manifests -> ArgoCD 自动同步 (CD) -> K8s 集群部署 ``` ## GitHub Actions 工作流 ```yaml # .github/workflows/ci.yml name: CI Pipeline on: push: branches: [main] pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: distribution: temurin java-version: '17' cache: maven - run: mvn verify build-and-push: needs: test if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::role/github-actions aws-region: ap-southeast-1 - uses: aws-actions/amazon-ecr-login@v2 id: ecr - name: Build and push env: REGISTRY: ${{ steps.ecr.outputs.registry }} IMAGE_TAG: ${{ github.sha }} run: | docker build -t $REGISTRY/my-app:$IMAGE_TAG . docker push $REGISTRY/my-app:$IMAGE_TAG - name: Update K8s manifests run: | cd k8s-manifests sed -i "s|image:.*|image: $REGISTRY/my-app:$IMAGE_TAG|" deployment.yaml git config user.name "github-actions" git config user.email "actions@github.com" git add . git commit -m "chore: update image to $IMAGE_TAG" git push ``` ## ArgoCD 配置 ```yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: name: my-app namespace: argocd spec: project: default source: repoURL: https://github.com/org/k8s-manifests targetRevision: main path: apps/my-app destination: server: https://kubernetes.default.svc namespace: production syncPolicy: automated: prune: true selfHeal: true syncOptions: - CreateNamespace=true ``` ## 回滚策略 ```bash # ArgoCD 一键回滚 argocd app rollback my-app # 或者 Git revert git revert HEAD git push # ArgoCD 自动同步 ``` ## 最佳实践 1. CI 和 CD 的 Git 仓库分离(应用代码 vs K8s manifests) 2. 使用 Git commit SHA 作为镜像 tag(不要用 latest) 3. PR 合并前自动运行测试和安全扫描 4. 配合 Sealed Secrets 管理敏感配置

← Back to Blog