找回密码
立即注册
搜索
热搜: Java Python Linux Go
发回帖 发新帖

2605

积分

0

好友

347

主题
发表于 2 小时前 | 查看: 3| 回复: 0

先抛一个反直觉的事实:2024年4月,GitOps理念的提出者Weaveworks倒闭了,其开源项目Flux曾是ArgoCD的最大竞争对手。然而,到2026年,ArgoCD在GitOps工具的市场份额已达65%,成为六成以上Kubernetes团队的首选。这并非源于对手的失败,而是因为ArgoCD自身的架构更为成熟——ApplicationSet、精细的同步控制以及完善的Web UI,使其从一个“部署工具”进化为了真正的“企业级GitOps平台”。

这篇文章将为你系统性地拆解ArgoCD,涵盖从核心架构、安装部署,到多集群管理、生产踩坑以及2026年的选型对比,助你彻底掌握这一工具。

一、核心架构:ArgoCD 到底是怎么工作的?

ArgoCD 有哪些组件

┌─────────────────────────────────────────────────────────────────┐
│                        ArgoCD 架构图                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│   Git Repository (GitOps 单一可信源)                             │
│         │                                                      │
│         ▼                                                      │
│   ┌─────────────┐                                              │
│   │ Repo Server │ ← 负责拉取 Git 仓库,渲染 Helm/Kustomize     │
│   └──────┬──────┘                                              │
│          │                                                      │
│   ┌──────▼──────┐     ┌────────────────┐                      │
│   │   Redis     │◄───►│  API Server     │◄─── Web UI / CLI    │
│   │  (缓存/队列) │     │  (认证鉴权/REST)│                      │
│   └─────────────┘     └────────┬────────┘                      │
│                                │                                 │
│                    ┌───────────▼───────────┐                    │
│                    │  Application Controller │                   │
│                    │  (状态对比/同步/漂移检测) │                   │
│                    └───────────┬───────────┘                    │
│                                │                                 │
│   ┌────────────────────────────▼─────────────────────────────┐ │
│   │           Target Kubernetes Clusters                     │ │
│   │  (生产集群1 / 生产集群2 / 测试集群 / 边缘集群)               │ │
│   └──────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘

核心组件详解

1. Repo Server(仓库服务)
负责所有 Git 操作:

  • 拉取 Git 仓库内容
  • 渲染 Helm Chart(ArgoCD 直接渲染,无需 helm template 预处理)
  • 处理 Kustomize Overlay
  • 缓存已渲染的 Manifest(避免重复拉取)
# Repo Server 高可用配置(Helm values)
repoServer:
  replicas: 3  # 至少3副本,避免单点
  autoscaling:
    enabled: true
    minReplicas: 2
    maxReplicas: 10
    # 根据 Git 仓库数量和渲染频率自动扩缩容
  resources:
    requests:
      cpu: "500m"
      memory: "1Gi"
    limits:
      cpu: "2"
      memory: "4Gi"

2. Application Controller(应用控制器)
ArgoCD 的核心引擎,持续运行:

  • 状态对比:每 3 秒对比 Git 期望状态与集群实际状态
  • 漂移检测:发现集群手动修改自动标记 OutOfSync
  • Sync 执行:按 Sync Policy 执行资源部署
  • 健康检查:对 Deployment/StatefulSet/Service 做健康评估
# Application Controller 调优(大规模集群)
controller:
  # 状态处理并发数(默认10,500+应用建议50)
  status.processors: "50"
  # 操作处理并发数(默认10,建议25)
  operation.processors: "25"
  # Redis 超时(高延迟集群调大)
  redis.proxy.timeout_seconds: "30"

3. Redis(缓存与队列)
ArgoCD v2.5+ 将 Redis 作为分布式缓存:

  • 缓存 Git 仓库内容和已渲染 Manifest
  • 缓存 Application 状态(减少 Repo Server 压力)
  • 作为 Controller 与 Repo Server 之间的消息队列
# Redis 高可用(生产必须)
redis:
  enabled: true
  replicas: 3
  metrics:
    enabled: true  # 开启 Prometheus 监控

4. API Server

  • 对外暴露 REST API 和 gRPC 接口
  • 处理所有认证鉴权(OIDC/LDAP/OAuth)
  • 管理 RBAC 权限模型
  • Web UI 的后端服务

漂移检测原理(关键机制)

Git 仓库(期望状态)           集群(实际状态)
    │                              │
    │    Application Controller    │
    │        每3秒轮询             │
    │ ──────────────────────────▶ │
    │                              │
    │   ┌─────────────────────┐   │
    │   │   对比差异分析        │   │
    │   │  resource version    │   │
    │   │  spec差异            │   │
    │   │  annotation差异       │   │
    │   │  label差异            │   │
    │   └─────────────────────┘   │
    │                              │
    ◀── OutOfSync / Synced / Healthy ──│

手动修改导致漂移的典型场景

# Git 中的 Deployment(期望状态)
spec:
  replicas: 3
  template:
    spec:
      containers:
        - name: api
          image: myapp:v1.2.3  # v1.2.3

---
# 运维手动 scale up(实际状态)
spec:
  replicas: 5  # 被手动改成了5

# ArgoCD 检测到差异 → OutOfSync
# 如果配置了 selfHeal: true → 自动恢复到3

二、ApplicationSet:多集群部署的核心

ApplicationSet 是 ArgoCD 应对多集群、规模化部署的核心功能。一个 YAML 文件,即可自动生成 N 个 Application 资源。

8种生成器深度解析

生成器1:Git Directory Generator

根据 Git 仓库目录结构批量生成 Application:

apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-apps
spec:
  generators:
    - git:
        repoURL: https://github.com/myorg/k8s-manifests.git
        revision: HEAD
        directories:
          - path: apps/services/*
          - path: apps/platform/*
            exclude: true  # 排除特定路径
  template:
    metadata:
      name: '{{path.basename}}'  # 目录名作为应用名
    spec:
      project: default
      source:
        repoURL: https://github.com/myorg/k8s-manifests.git
        targetRevision: HEAD
        path: '{{path}}'  # 目录路径
      destination:
        server: '{{server}}'
        namespace: '{{path.basename}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true

生成器2:Cluster Generator

根据已注册 ArgoCD 的集群标签批量部署:

generators:
  - clusters:
      selector:
        matchLabels:
          environment: production  # 只选生产集群
          team: platform
      # 可选:提供默认值
      values:
        replicas: "3"
        imageTag: "v1.0.0"

注册集群并打标签

# 注册集群时直接打标签
argocd cluster add prod-us-east \
  --name production \
  --label environment=production \
  --label region=us-east \
  --label team=platform

# 查看已注册集群及其标签
argocd cluster list

# 输出示例:
# NAME         SERVER                      LABELS
# production   https://k8s.prod.example.com  environment=production, region=us-east, team=platform

生成器3:List Generator

最简单的列表生成器,适合固定集群列表:

generators:
  - list:
      elements:
        - cluster: prod-us-east
          url: https://prod-us-east.k8s.example.com
          replicas: "5"
          region: us-east
        - cluster: prod-eu-west
          url: https://prod-eu-west.k8s.example.com
          replicas: "3"
          region: eu-west
        - cluster: staging
          url: https://staging.k8s.example.com
          replicas: "1"
          region: us-east

生成器4:Matrix Generator(矩阵组合)

两个生成器的结果做笛卡尔积,常用于“服务 × 集群”组合:

generators:
  - matrix:
      generators:
        # 维度1:所有生产集群
        - clusters:
            selector:
              matchLabels:
                environment: production
        # 维度2:平台服务列表
        - list:
            elements:
              - service: cert-manager
              - service: ingress-nginx
              - service: metrics-server
              - service: prometheus

  template:
    metadata:
      name: '{{name}}-{{service}}'
      # 例如:prod-us-east-cert-manager
    spec:
      source:
        chart: '{{service}}'
        repoURL: https://charts.bitnami.com/bitnami
        helm:
          releaseName: '{{service}}'
      destination:
        server: '{{server}}'
        namespace: '{{service}}'

生成器5:Merge Generator(配置覆盖合并)

在多个生成器之间做合并,并支持覆盖默认值,是生产多集群差异化配置的核心工具:

generators:
  - merge:
      mergeKeys: [server]  # 以server为合并键
      generators:
        # 基础配置:所有生产集群副本数=3
        - clusters:
            selector:
              matchLabels:
                environment: production
            values:
              replicas: "3"
              resources: standard

        # 差异化覆盖:高流量集群副本数=10
        - clusters:
            selector:
              matchLabels:
                high-traffic: "true"
            values:
              replicas: "10"
              resources: high-capacity

        # 边缘集群:副本数=1
        - clusters:
            selector:
              matchLabels:
                edge: "true"
            values:
              replicas: "1"
              resources: minimal

生成器6:Pull Request Generator

监听 GitLab/GitHub/Bitbucket 的 PR 事件,自动为每个 PR 创建 Preview 环境:

generators:
  - pullRequest:
      # GitHub 配置
      github:
        owner: myorg
        repo: myapp
        api: https://api.github.com/
        tokenRef:
          secretName: github-token
          key: token
      # 过滤条件
      filter: >-
        "[?target_branch == 'main']"
      labels:
        - preview  # 只处理带preview标签的PR

生成器7:SCM Provider Generator

直接对接 GitHub/GitLab 仓库,自动发现分支/标签进行部署:

generators:
  - scmProvider:
      github:
        # 扫描所有符合条件的仓库
        organization: myorg
        tokenRef:
          secretName: github-token
          key: token
        # 扫描包含特定标签的仓库
        filter: 'repo:myorg/.*'
      cloneProtocol: ssh  # 推荐用SSH避免token泄露

生成器8:Cluster Decision Resource Generator

根据外部资源动态决定目标集群,适合动态调度场景:

generators:
  - clusterDecisionResource:
      # 监听 Job 资源,由外部系统决定部署目标
      groovy:
        script: |
          # 返回匹配特定标签的集群
          return params.clusters
      resource:
        apiVersion: batch/v1
        kind: Job
        name: cluster-selector
        namespace: argocd

完整的 App-of-Apps 模式

用一个大 Application 管理所有其他 Application,实现集群初始化的一键完成:

git仓库
└── root/
    ├── argocd-apps/           # ApplicationSet 目录
    │   ├── platform.yaml      # 平台基础组件(cert-manager/ingress...)
    │   ├── microservices.yaml # 微服务列表
    │   └── ml-pipeline.yaml   # ML 服务
    └── values/
        ├── prod.yaml
        └── staging.yaml
# root-app.yaml(根 Application)
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: root-app
  finalizers:
    - resources-finalizer.argocd.argoproj.io  # 级联删除保护
spec:
  project: default
  source:
    repoURL: https://github.com/myorg/argocd-manifests.git
    targetRevision: HEAD
    path: root/argocd-apps
  destination:
    server: https://kubernetes.default.svc
    namespace: argocd
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true

三、Sync 策略:什么时候同步?怎么控制顺序?

Sync 的四个阶段

PreSync Hook ──▶ Sync 资源 ──▶ PostSync Hook ──▶ Prune(清理)
 (执行一次)    (主要部署)    (执行一次)      (可选,清理已删除资源)

典型 Hook 使用场景

apiVersion: batch/v1
kind: Job
metadata:
  name: db-migration
  annotations:
    # 关键:注解控制执行阶段和顺序
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded
    # HookSucceeded = Job成功后退删除,避免残留
    # HookFailed = Job失败后保留,方便排错
spec:
  ttlSecondsAfterFinished: 300
  template:
    spec:
      restartPolicy: OnFailure
      containers:
        - name: migrate
          image: myapp-migrate:latest
          command: ["python", "manage.py", "migrate"]
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  # 主资源在 Sync 阶段部署(默认行为,无需注解)
  replicas: 3
  template:
    spec:
      containers:
        - name: myapp
          image: myapp:v1.2.3
---
apiVersion: v1
kind: Service
metadata:
  name: myapp-svc
  annotations:
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded
spec:
  # 验证 Deployment 健康后再暴露 Service
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 8080

Sync Waves(同步波次)

通过注解控制资源部署顺序,适用于有依赖关系的资源:

# Wave 0:先部署 CRD(必须最早,否则后续资源无法创建)
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  annotations:
    argocd.argoproj.io/sync-wave: "0"
spec: ...

# Wave 1:部署 CR 实例(依赖 CRD)
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
  annotations:
    argocd.argoproj.io/sync-wave: "1"
spec: ...

# Wave 2:部署应用(依赖 Operator)
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    argocd.argoproj.io/sync-wave: "2"
spec: ...

三种 Sync 策略对比

策略 适用场景 风险
手动 Sync 生产环境关键应用,由人工确认后部署 低风险,但人工成本高
自动化 Sync(selfHeal) 开发/测试环境,快速迭代 存在集群意外修改被自动覆盖的风险
蓝绿 Sync 有金丝雀/蓝绿部署时,配合 Argo Rollouts 最高控制力,但配置最复杂

生产推荐配置

syncPolicy:
  automated:
    # 启用自动化(根据环境决定)
    prune: true      # Git中删除的资源,集群中同步删除
    selfHeal: true   # 集群手动修改自动恢复(生产环境建议false)
  syncOptions:
    - Validate=false          # 跳过 kubectl apply --validate(避免自定义CRD验证失败)
    - CreateNamespace=true    # 自动创建目标命名空间
    - PruneLast=true          # 在最后阶段清理(避免清理过程中新资源报错)
    - ServerSideApply=true    # 使用服务端apply(解决字段管理器冲突)
    - RespectIgnoreDifferences=true  # 尊重IgnoreDifferences配置

四、多集群部署拓扑:怎么选架构?

方案1:Hub-and-Spoke(中心辐射型)—— ≤20个集群

                    ┌────────────────────────────────────┐
                    │          管理集群 (Hub)              │
                    │   ArgoCD Server + Repo Server         │
                    │   + Redis HA                          │
                    └──────────────┬───────────────────────┘
                                   │
            ┌──────────────────────┼──────────────────────┐
            │                      │                      │
            ▼                      ▼                      ▼
    ┌──────────────┐      ┌──────────────┐      ┌──────────────┐
    │ prod-us-east │      │ prod-eu-west│      │  staging     │
    │ 集群         │      │  集群        │      │  集群         │
    └──────────────┘      └──────────────┘      └──────────────┘

适用条件

  • 集群数量 ≤ 20
  • 平台团队统一管理基础设施
  • 集群之间网络互通(管理集群能访问所有集群 API Server)

核心配置

# 逐个注册集群并打标签
argocd cluster add prod-us-east --name prod-us-east \
  --label environment=production --label region=us-east
argocd cluster add prod-eu-west --name prod-eu-west \
  --label environment=production --label region=eu-west
argocd cluster add staging --name staging \
  --label environment=staging

方案2:Federated(联邦型)—— ≥20个集群或强隔离需求

        ┌──────────────────────────────────────────────┐
        │              元 ArgoCD(管理 ArgoCD)          │
        │   只需配置 ApplicationSet 指向各子 ArgoCD 实例  │
        └────────────────────┬─────────────────────────┘
                             │
        ┌────────────────────┼────────────────────┐
        ▼                    ▼                    ▼
┌───────────────┐    ┌───────────────┐    ┌───────────────┐
│ ArgoCD #1     │    │ ArgoCD #2     │    │ ArgoCD #3     │
│ (prod-us-east)│    │ (prod-eu-west)│    │ (edge-asia)   │
│ 管理该集群工作负载│    │ 管理该集群工作负载│    │ 管理该集群工作负载│
└───────────────┘    └───────────────┘    └───────────────┘

适用条件

  • 集群数量 > 20
  • 强网络隔离(各集群在不同的 VPC/网络区域)
  • 各团队需要独立管理自己的 ArgoCD 实例

优势:每个团队完全自治,故障隔离;元 ArgoCD 只需管理 ApplicationSet 配置

AppProject 隔离(两种架构通用)

apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: platform-team
  namespace: argocd
spec:
  description: Platform Team 专用项目

  # 允许访问哪些 Git 仓库
  sourceRepos:
    - https://github.com/myorg/platform-*
    - https://github.com/myorg/infra-*

  # 允许部署到哪些集群
  destinations:
    - server: https://prod-us-east.k8s.example.com
      namespace: platform-*
    - server: https://prod-eu-west.k8s.example.com
      namespace: platform-*
    - server: https://staging.k8s.example.com
      namespace: platform-*

  # 禁止部署到 kube-system 和 argocd
  namespaceResourceBlacklist:
    - group: ""
      kind: Namespace

  # 只能创建/修改这些资源类型
  resourceAllowList:
    - group: "apps"
      kinds: ["Deployment", "StatefulSet", "DaemonSet"]
    - group: ""
      kinds: ["ConfigMap", "Secret", "Service"]

  # RBAC 角色
  roles:
    - name: admin
      description: Platform Team Admin
      policies:
        - p: 'p, proj:platform-team:admin, applications, *, platform-team/*, allow'

五、Helm + Kustomize 深度集成

Helm:直接渲染,无需预处理

ArgoCD 原生支持渲染 Helm Chart,无需预先执行 helm template

source:
  repoURL: https://charts.bitnami.com/bitnami
  chart: redis
  targetRevision: "20.0.0"
  helm:
    # 内联 values(替代 valuesFiles)
    valuesObject:
      architecture: replication
      replica:
        replicaCount: 3
      auth:
        enabled: true
        password: "supersecret"  # 建议用 External Secrets 引用

    # 参数替换(不推荐复杂场景)
    parameters:
      - name: replica.replicaCount
        value: "3"

    # 版本锁定(防止 Git 同步延迟导致版本漂移)
    version: "20.0.0"

    # Pass credentials to chart(Chart 中有 subchart 需要认证时)
    passCredentials: true

Kustomize:Overlay 差异化配置

ArgoCD 同样原生支持 Kustomize,可以方便地实现环境间的配置差异化。

source:
  repoURL: https://github.com/myorg/k8s-manifests.git
  path: overlays/production
  kustomize:
    # 镜像版本覆盖(无需修改 kustomization.yaml)
    images:
      - myapp=myregistry.io/myapp:v2.3.1
      - redis=redis:7.2-alpine
    # 版本锁定
    version: "v2.3.1"
    # 命名空间覆盖
    namespace: production
    # Labels 注入
    commonAnnotations:
      team: platform

Kustomize 目录结构

k8s-manifests/
├── base/
│   ├── deployment.yaml
│   ├── service.yaml
│   └── kustomization.yaml
└── overlays/
    ├── production/     # 生产:3副本,高资源配置
    │   ├── kustomization.yaml
    │   └── patches/
    │       ├── replica-patch.yaml
    │       └── resource-patch.yaml
    └── staging/       # 测试:1副本,最小资源
        └── kustomization.yaml
# overlays/production/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - ../../base

replicas:
  - name: myapp
    count: 5

patches:
  - path: patches/replica-patch.yaml
  - target:
      kind: Deployment
    patch: |
      - op: replace
        path: /spec/template/spec/containers/0/resources
        value:
          limits:
            cpu: "2"
            memory: "4Gi"
          requests:
            cpu: "1"
            memory: "2Gi"

六、Flux vs ArgoCD:2026 年选型

维度 ArgoCD Flux
市场份额(2026) 65% 25%
GitOps 理念提出者 🚫(CNCF 项目,理念继承者) ✅(Weaveworks 原创)
多集群管理 ✅ ApplicationSet(成熟) Application + Kustomize
Web UI ✅ 成熟完善 ⚠️ 需要额外的 Flux UI 插件
CLI 体验 ✅ argocd CLI 功能完整 ✅ flux CLI 同样成熟
Helm 原生支持 ✅ 直接渲染 Chart ✅ Helm Operator/Controller
CRD 数量 多(有 ApplicationSet/ApplicationSetGenerator) 少(Flux 2.x 整合后更简洁)
学习曲线 较平缓 较陡(Flux 2.x 后改善明显)
GitOps 社区活跃度 非常活跃(CNCF 毕业项目) 活跃(CNCF 孵化项目)
生产案例 major:Intuit / GitLab / Canonical major:Weaveworks 遗产 + 中型企业

一句话建议

  • 需要成熟 UI + 多集群管理 → 选 ArgoCD
  • 已有 Flux 使用经验 / 需要极简架构 / GitOps 理念践行者 → 选 Flux
  • 新团队起步 → ArgoCD(社区文档更丰富,遇到问题更容易找到答案)

七、生产高可用部署

全组件高可用配置

# 使用 Helm 安装并配置高可用
helm install argocd argo/argo-cd \
  --namespace argocd \
  --create-namespace \
  --set server.replicas=2 \
  --set server.autoscaling.enabled=true \
  --set server.autoscaling.minReplicas=2 \
  --set server.autoscaling.maxReplicas=5 \
  \
  --set controller.replicas=2 \
  --set controller.status.processors=50 \
  --set controller.operation.processors=25 \
  \
  --set repoServer.replicas=3 \
  --set repoServer.autoscaling.enabled=true \
  --set repoServer.autoscaling.minReplicas=2 \
  --set repoServer.autoscaling.maxReplicas=10 \
  \
  --set redis.replicas=3 \
  \
  --set server.service.type=ClusterIP \
  --set server.service.externalIPs=["10.0.0.100"] \
  \
  --set server.ingress.enabled=true \
  --set server.ingress.ingressClassName=nginx \
  --set server.ingress.host=argocd.mycompany.com \
  --set server.ingress.annotations."cert-manager\.io/cluster-issuer"=letsencrypt-prod \
  \
  --set server.configURL=https://raw.githubusercontent.com/argoproj/argo-cd/master/assets/argocd-server-certs.crt \
  --set global.securityContext.runAsNonRoot=true \
  --set global.securityContext.fsGroup=1000

# 等待所有组件就绪
kubectl wait --for=condition=ready pod \
  -l app.kubernetes.io/name=argocd-server \
  -n argocd \
  --timeout=300s

OIDC 单点登录集成(生产必备)

# server.config cmap 配置 OIDC
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-cm
  namespace: argocd
data:
  # 使用 Keycloak 作为 IdP
  url: https://argocd.mycompany.com
  oidc.config: |
    name: Keycloak
    issuer: https://keycloak.mycompany.com/realms/company
    clientID: argocd
    clientSecret: $oidc.keycloak.client-secret
    requestedScopes: ["openid", "profile", "email", "groups"]

  # 基于组的 RBAC
  # admin 组 -> 管理员
  # platform 组 -> 工程能力
  # readonly 组 -> 只读
  policy.default: role:readonly
  policy.csv: |
    g, platform-team, role:admin
    g, dev-team, role:engineering
    g, qa-team, role:readonly

External Secrets 集成(密钥管理)

# 安装 External Secrets Operator
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
  name: external-secrets
  namespace: operators
spec:
  channel: stable
  name: external-secrets
  source: operatorhubio-catalog

---
# 定义 SecretStore 和 ExternalSecret
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: argocd-secrets
  namespace: argocd
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: vault-backend
    kind: ClusterSecretStore
  target:
    name: argocd-oidc-secret  # ArgoCD 期望的 Secret 名称
    creationPolicy: Owner
  data:
    - secretKey: client-secret
      remoteRef:
        key: production/argocd/oidc
        property: keycloak-secret

八、踩坑实录

坑1:ArgoCD 无法删除 Terminating 状态的资源

# 症状:Sync 时某些资源一直处于 Terminating

# 排查:查看 Finalizer 是否卡住
kubectl get deployment myapp -o yaml | grep finalizers

# 原因:自定义 Finalizer 的资源,Git 中已删除但 Finalizer 未清理

# 方案1:手动清理 Finalizer
kubectl patch deployment myapp \
  -p '{"metadata":{"finalizers":null}}' \
  --type=merge

# 方案2:配置 ArgoCD 使用非级联删除(谨慎使用)
spec:
  syncPolicy:
    managedNamespaceMetadata:
      labels:
        argocd.argoproj.io/managed: "true"

# 方案3:使用 ArgoCD Hook 在删除前清理资源
# 添加 PreDelete Hook

坑2:ApplicationSet 生成的 Application 一直 OutOfSync

# 排查步骤
argocd app get matrix-example-myapp

# 常见原因1:生成器模板变量为空(变量名拼写错误)
# ❌ 错误:'{{metadata.name}}'
# ✅ 正确:'{{name}}'(不同生成器可用变量不同)

# 常见原因2:Merge Generator 的 mergeKeys 配置错误
# 必须指定正确的合并键(通常是 server 或 cluster)

# 常见原因3:Helm values 格式错误(内联 vs 文件)
# valuesObject(内联)是 map 结构,不需要引号
# ✅ valuesObject.replicaCount: 3
# ❌ valuesObject.replicaCount: "3" (字符串可能有问题)

坑3:Repo Server OOM(内存耗尽)

# 症状:Repo Server Pod 频繁重启,OOMKilled

# 原因:Git 仓库过大(monorepo)或 Helm Chart 过于复杂

# 解决方案1:减小 Repo Server 内存限制(实际需求内)
--set repoServer.resources.limits.memory="4Gi"

# 解决方案2:限制并发请求数
--set controller.status.processors=20

# 解决方案3:使用专用 Git 代理(如 git-proxy)加速大仓库拉取
# 解决方案4:拆分 monorepo 为多个小仓库

坑4:Helm Chart 中的随机值每次 Sync 都产生漂移

# 问题:Chart 使用了随机生成器(如 random annotation),每次渲染结果不同

# 症状:ArgoCD 一直显示 OutOfSync,但 diff 是随机的 annotation

# 解决方案1:配置 ArgoCD 忽略特定字段
spec:
  ignoreDifferences:
    - group: apps
      kind: Deployment
      jsonPointers:
        - /spec/template/metadata/annotations/random-seed  # 忽略随机注解

# 解决方案2:使用 Helm 原生 random 功能而非自定义脚本
# 解决方案3:改用 Kustomize 替代 Helm(Kustomize 不支持随机生成)

坑5:多集群部署时 Vault Secret 集群 A 能读到,集群 B 读不到

# 原因:External Secrets 的 SecretStore 通常是 ClusterScoped
# 但 Vault Policy 可能没有覆盖所有集群的 namespace

# 排查:检查 Vault Policy
vault policy read argocd-policy

# 解决方案:Vault Policy 必须包含所有目标 namespace
path "secret/data/production/*" {
  capabilities = ["read"]
}

# 或使用 ClusterSecretStore + Vault Namespace
apiVersion: external-secrets.io/v1beta1
kind: ClusterSecretStore
metadata:
  name: vault-backend
spec:
  provider:
    vault:
      server: "https://vault.mycompany.com"
      namespace: "production"
      auth:
        kubernetes:
          mountPath: /vault/kubernetes
          role: argocd-secrets

九、一句话总结

场景 结论
集群数量 ≤ 20 Hub-and-Spoke(一个 ArgoCD 管所有)
集群数量 > 20 Federated(每个集群一个 ArgoCD + 元 ArgoCD)
开发测试环境 自动化 Sync(selfHeal: true)
生产环境 手动 Sync 或 Argo Rollouts
密钥管理 External Secrets + Vault(绝不直接存 Git)
工具选型 ArgoCD(UI 成熟 + 社区活跃 + 文档丰富)

GitOps 不是银弹,但 ArgoCD 是目前最接近“GitOps 平台”这个定位的工具。

希望这篇从原理到实战的深度解析,能帮助你更好地理解和应用 ArgoCD。如果你在实践中遇到其他问题,欢迎在 云栈社区 的运维板块与广大开发者交流探讨。




上一篇:深入解析Harness Engineering:破解AI Agent长时间运行的工程化新范式
下一篇:深入理解Kafka核心机制:副本、ISR与偏移量保障高可用
您需要登录后才可以回帖 登录 | 立即注册

手机版|小黑屋|网站地图|云栈社区 ( 苏ICP备2022046150号-2 )

GMT+8, 2026-3-29 06:17 , Processed in 0.704914 second(s), 39 queries , Gzip On.

Powered by Discuz! X3.5

© 2025-2026 云栈社区.

快速回复 返回顶部 返回列表