SRE & AI 实践录

GitOps 工作流在 Kubernetes 集群管理中的最佳实践

· 更新于 2026-07-26 ⏱️ 阅读约 1 分钟 (496 字) GitOps Kubernetes CI/CD

探索 GitOps 理念在 Kubernetes 集群管理中的落地实践,通过 ArgoCD 实现声明式部署与自动化回滚,提升发布效率与运维稳定性。

一、GitOps 概述

GitOps 是一种以 Git 仓库为单一事实来源的运维模型,通过声明式配置和自动化同步机制,确保集群状态始终与仓库中的期望状态一致。在 Kubernetes 环境中,GitOps 已经成为管理多集群、多环境部署的事实标准。

二、ArgoCD 最佳实践

推荐使用 ApplicationSet 管理多集群部署,结合 Kustomize 实现环境差异化配置。ArgoCD 提供的自动同步、自动修复和漂移检测功能,可以大幅降低运维负担。

ArgoCD Application YAML

yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: production-app
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/team/config-repo.git
    targetRevision: main
    path: overlays/production
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true

CI/CD Shell 脚本

bash
#!/bin/bash
# GitOps CI/CD 流水线
set -euo pipefail

REPO_URL="https://github.com/team/app-repo.git"
CONFIG_REPO="https://github.com/team/config-repo.git"
COMMIT_SHA="${CI_COMMIT_SHA:?commit sha required}"

# 构建镜像
docker build -t app:"${COMMIT_SHA}" .

# 推送镜像
docker tag app:"${COMMIT_SHA}" registry.example.com/app:"${COMMIT_SHA}"
docker push registry.example.com/app:"${COMMIT_SHA}"

# 更新配置仓库中的镜像版本
git clone "${CONFIG_REPO}" config-tmp
cd config-tmp
sed -i "s|image: app:.*|image: registry.example.com/app:${COMMIT_SHA}|" overlays/production/deployment.yaml
git add -A
git commit -m "chore: bump app image to ${COMMIT_SHA}"
git push origin main

三、总结

GitOps 通过将部署配置纳入版本控制,实现了可审计、可回滚的发布流程,是云原生时代集群管理的核心范式。结合 ArgoCD 等工具的自动化能力,团队可以将部署频率提升数倍,同时降低人为失误的风险。

本文作者:技术领航员 | 许可协议:CC BY-NC-SA 4.0

本文链接:https://sre-ai-blog.pages.dev/zh/posts/gitops-workflow/(转载请注明出处)