Argo CD

Argo CD #

Declarative, GitOps continuous delivery tool for Kubernetes. CNCF Graduated 项目。

WebsiteDocGithubDemoComment
Argo CDDocGithubDemoCNCF 毕业项目,GitOps 持续交付工具,提供完整 UI

Read First #

Docs, Github, CNCF

Understand The Basics

Getting Started

Architecture Overview

Argo CD vs Flux — 两大 GitOps 工具对比

Killercoda Argo CD Labs — 在线实验环境


核心概念 #

GitOps 原则 #

  • 声明式配置:应用定义、配置和环境均以 Git 仓库为唯一真实来源(Source of Truth)
  • 版本控制:所有变更通过 Git commit 追踪,具备完整审计能力
  • 自动同步:控制器持续对比 Git 期望状态与集群实际状态,自动或手动同步
  • 拉取模式(Pull):与 CI 的 Push 模式不同,Argo CD 从 Git 拉取期望状态并应用到集群

支持的配置管理工具 #

工具说明
KustomizeKubernetes 原生配置管理,overlay 模式
HelmKubernetes 包管理器,Chart 模板渲染
Jsonnet数据模板语言,适合复杂配置生成
Plain YAML/JSON直接使用 YAML/JSON 清单文件
Config Management Plugin自定义配置管理插件(如 kustomize + helm 组合)

核心 CRD #

CRD说明
Application定义应用的 Source(Git 仓库 + 路径 + 目标 revision)和 Destination(目标集群 + namespace)
AppProject多租户隔离单元,限制 Application 可用的 Git 仓库、目标集群、命名空间和 K8s 资源类型
ApplicationSet自动生成多个 Application 的模板引擎,通过 Generator 批量创建应用(如按集群、Git 目录、矩阵等)

架构组件 #

┌──────────────────────────────────────────────────────────┐
│                    Argo CD 控制面                         │
│                                                          │
│  ┌─────────────┐   ┌─────────────────┐   ┌────────────┐ │
│  │  API Server  │   │  Repo Server    │   │ Redis      │ │
│  │ (gRPC/REST) │   │ (Git 缓存+渲染) │   │ (缓存层)   │ │
│  └──────┬───────┘   └────────┬────────┘   └────────────┘ │
│         │                    │                            │
│  ┌──────┴────────────────────┴────────────────────────┐  │
│  │          Application Controller                     │  │
│  │   (持续监控 → 对比 Git 期望状态 vs 集群实际状态)    │  │
│  └─────────────────────────────────────────────────────┘  │
│                                                          │
│  ┌────────────────────┐  ┌────────────────────────────┐  │
│  │ Dex (SSO/OIDC)    │  │ Notifications Controller   │  │
│  └────────────────────┘  └────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘
          │                         │
    ┌─────┴─────┐             ┌─────┴─────┐
    │ Git Repo  │             │ K8s 集群   │
    │ (Source   │             │ (目标环境)  │
    │  of Truth)│             │            │
    └───────────┘             └───────────┘

三大核心组件 #

组件职责
API ServergRPC/REST 服务,暴露给 Web UI / CLI / CI 系统。负责应用管理、状态报告、认证与 RBAC、Webhook 监听
Repository Server维护 Git 仓库本地缓存,根据 repo URL + revision + path + 模板参数生成并返回 K8s 清单
Application ControllerK8s Controller,持续对比 Git 期望状态与集群实际状态,检测 OutOfSync 并执行同步操作,触发 PreSync/Sync/PostSync 生命周期 Hook

辅助组件 #

组件职责
DexSSO 代理,支持 OIDC/OAuth2/LDAP/SAML/GitHub/GitLab 等身份认证
Redis缓存层,加速清单渲染和状态查询
Notifications Controller发送同步结果通知到 Slack/Teams/Email 等

快速开始 #

1. 安装 #

kubectl create namespace argocd
kubectl apply -n argocd --server-side --force-conflicts \
  -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

--server-side --force-conflicts 是因为部分 CRD(如 ApplicationSet)超过 262KB annotation 限制。

2. 安装 CLI #

# macOS
brew install argocd

# 或从 GitHub Releases 下载
# https://github.com/argoproj/argo-cd/releases/latest

3. 访问 Argo CD #

# 方式一:Port Forwarding(开发环境推荐)
kubectl port-forward svc/argocd-server -n argocd 8080:443
# 访问 https://localhost:8080

# 方式二:LoadBalancer
kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}'

# 方式三:Ingress(生产环境推荐)
# 参考 https://argo-cd.readthedocs.io/en/stable/operator-manual/ingress/

4. 获取初始密码并登录 #

# 获取 admin 初始密码
argocd admin initial-password -n argocd

# CLI 登录
argocd login <ARGOCD_SERVER>

# 修改密码
argocd account update-password

安全提示:修改密码后应删除 argocd-initial-admin-secret Secret。

5. 注册外部集群(可选) #

# 列出所有 kubeconfig context
kubectl config get-contexts -o name

# 注册集群
argocd cluster add <context-name>

部署到 Argo CD 所在集群(in-cluster)时无需注册,使用 https://kubernetes.default.svc 即可。

6. 创建并部署应用 #

# CLI 方式创建 Application
argocd app create guestbook \
  --repo https://github.com/argoproj/argocd-example-apps.git \
  --path guestbook \
  --dest-server https://kubernetes.default.svc \
  --dest-namespace default

# 查看应用状态
argocd app get guestbook

# 同步(部署)应用
argocd app sync guestbook

Application 详解 #

Application YAML 示例 #

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: guestbook
  namespace: argocd
spec:
  project: default                    # AppProject 名称
  source:
    repoURL: https://github.com/argoproj/argocd-example-apps.git
    targetRevision: HEAD              # branch / tag / commit SHA
    path: guestbook                   # 仓库中的路径
    # helm:                           # Helm Chart 配置
    #   valueFiles:
    #     - values.yaml
    # kustomize:                      # Kustomize 配置
    #   namePrefix: prod-
  destination:
    server: https://kubernetes.default.svc   # 目标集群
    namespace: default                        # 目标命名空间
  syncPolicy:
    automated:                       # 自动同步策略
      selfHeal: true                 # 自动修复集群中手动变更
      prune: true                    # 自动删除 Git 中已移除的资源
    syncOptions:
      - CreateNamespace=true         # 自动创建目标 namespace
      - ServerSideApply=true         # 使用 Server-Side Apply

同步状态 #

状态含义
Synced集群实际状态与 Git 期望状态一致
OutOfSync集群实际状态与 Git 期望状态存在差异

健康状态 #

状态含义
Healthy资源正常运行
Progressing资源正在部署中
Degraded资源异常
Suspended资源被暂停
Missing资源尚未创建
Unknown无法判断资源状态

同步策略与选项 #

自动同步(Automated Sync) #

spec:
  syncPolicy:
    automated:
      prune: true       # Git 中删除的资源自动从集群中删除
      selfHeal: true    # 集群中手动变更自动回滚到 Git 状态

常用 Sync Options #

Option说明
Prune=false禁止删除 Git 中已移除的资源
Prune=confirm删除前需要手动确认
Delete=false应用删除时保留该资源(如 PVC)
CreateNamespace=true自动创建目标 namespace
ServerSideApply=true使用 Server-Side Apply 替代 client-side apply
ApplyOutOfSyncOnly=true仅同步 OutOfSync 的资源(大应用优化)
PruneLast=true在所有资源部署健康后再执行 Prune
Replace=true使用 kubectl replace 替代 kubectl apply
Force=true删除并重建资源(适用于 Job 等场景)
FailOnSharedResource=true发现被其他 Application 管理的共享资源时报错
RespectIgnoreDifferences=true同步时也尊重 ignoreDifferences 配置

Sync Waves(同步波次) #

通过 annotation 控制资源的部署顺序:

metadata:
  annotations:
    argocd.argoproj.io/sync-wave: "1"   # 数字越小越先部署

Resource Hooks(生命周期钩子) #

Hook 类型执行时机
PreSync同步前执行(如数据库迁移)
Sync同步时执行
PostSync同步后执行(如健康检查、通知)
SyncFail同步失败时执行
Skip跳过该资源
metadata:
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded

Sync Windows(同步窗口) #

限制同步只能在指定时间窗口内执行:

apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: default
spec:
  syncWindows:
    - kind: allow         # allow 或 deny
      schedule: "0 22 * * *"   # cron 表达式:每天 22:00
      duration: 2h              # 窗口持续 2 小时
      applications:
        - "*"                   # 匹配所有应用
      manualSync: true          # 窗口外允许手动同步

ApplicationSet(批量应用管理) #

通过 Generator 模板自动生成多个 Application:

常用 Generator #

Generator说明
List静态列表,手动指定参数
Cluster自动发现已注册的集群
Git Directory根据 Git 仓库中的目录结构生成应用
Git File根据 Git 仓库中的 JSON/YAML 文件生成应用
Matrix组合多个 Generator 的笛卡尔积
Merge合并多个 Generator 的结果
SCM Provider自动发现 GitHub/GitLab 组织下的仓库
Pull Request根据 PR 生成应用(预览环境)

ApplicationSet 示例 #

apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: guestbook
  namespace: argocd
spec:
  generators:
    - list:
        elements:
          - cluster: staging
            url: https://staging.example.com
          - cluster: production
            url: https://production.example.com
  template:
    metadata:
      name: '{{cluster}}-guestbook'
    spec:
      project: default
      source:
        repoURL: https://github.com/org/guestbook.git
        targetRevision: HEAD
        path: kustomize/{{cluster}}
      destination:
        server: '{{url}}'
        namespace: guestbook

多集群管理 #

注册集群 #

argocd cluster add <context-name>
# 会在目标集群的 kube-system 命名空间创建 argocd-manager ServiceAccount

集群管理模式 #

模式说明
Hub-Spoke一个中心 Argo CD 管理多个远程集群
独立部署每个集群独立部署 Argo CD 实例
Argo CD 分层Management Cluster 管理子集群的 Argo CD 实例(App of Apps 模式)

Hub-Spoke 架构注意事项 #

  • 跨集群网络连通性(API Server 可达)
  • argocd-manager-role 权限可按需缩小到特定 namespace/资源
  • 大规模集群建议使用 ApplicationSet 的 Progressive Syncs 分批部署

安全与多租户 #

RBAC #

# argocd-rbac-cm ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-rbac-cm
  namespace: argocd
data:
  policy.default: role:readonly
  policy.csv: |
    p, role:devops, applications, sync, default/*, allow
    p, role:devops, applications, get, default/*, allow
    g, devops-team, role:devops

SSO 集成 #

支持 OIDC、OAuth2、LDAP、SAML 2.0、GitHub、GitLab、Microsoft、LinkedIn。

AppProject 隔离 #

apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: my-project
  namespace: argocd
spec:
  description: 项目描述
  sourceRepos:            # 允许的 Git 仓库
    - 'https://github.com/my-org/*'
  destinations:           # 允许的目标集群和 namespace
    - server: https://kubernetes.default.svc
      namespace: my-namespace
  clusterResourceWhitelist:  # 允许的集群级资源
    - group: ''
      kind: Namespace
  namespaceResourceBlacklist: # 禁止的资源类型
    - group: ''
      kind: ResourceQuota
  roles:                  # 项目级角色
    - name: admin
      policies:
        - p, proj:my-project:admin, applications, *, my-project/*, allow

常用 CLI 命令 #

# 应用管理
argocd app list                           # 列出所有应用
argocd app get <app>                      # 查看应用详情
argocd app sync <app>                     # 同步应用
argocd app rollback <app> <revision>      # 回滚到指定版本
argocd app diff <app>                     # 查看差异
argocd app delete <app>                   # 删除应用
argocd app history <app>                  # 查看同步历史

# 集群管理
argocd cluster list                       # 列出已注册集群
argocd cluster add <context>              # 注册集群
argocd cluster rm <context>               # 移除集群

# 仓库管理
argocd repo add <repo-url>               # 添加 Git 仓库
argocd repo list                          # 列出已注册仓库

# 项目操作
argocd proj list                          # 列出所有 AppProject
argocd proj get <project>                 # 查看项目详情

最佳实践 #

实践说明
App of Apps 模式用一个根 Application 管理所有子 Application,实现声明式全局管理
环境隔离每个环境(dev/staging/prod)使用独立的 AppProject 和 namespace
Git 分支策略dev→main 分支部署开发环境,release/* 部署预发布,tag 部署生产
Sync Window生产环境仅在维护窗口内允许自动同步
Helm values 分层公共 values.yaml + 环境特定 values-{env}.yaml
Resource Hooks数据库迁移用 PreSync,健康检查用 PostSync
ignoreDifferences忽略由控制器动态管理的字段(如 HPA 的 replicas)
Prune Protection关键资源设置 Prune=confirm 防止误删
Webhook配置 Git Webhook 触发即时同步,减少轮询间隔

Argo CD vs Flux #

维度Argo CDFlux
UI内置 Web UI无(CLI only)
多集群原生支持(Hub-Spoke)通过 Flux instance per cluster
Helm 支持支持原生 Helm Controller(更强)
镜像自动更新需配合 Image Updater内置 Image Automation
通知内置 Notifications需配合 Notification Controller
渐进式交付需配合 Argo Rollouts内置 Flagger
Git 提供者广泛支持广泛支持
CNCF 状态GraduatedGraduated

生态与扩展 #

项目说明
Argo Rollouts金丝雀/蓝绿部署控制器
Argo Image Updater自动更新容器镜像版本
Argo Events事件驱动自动化
Crossplane声明式基础设施管理,与 Argo CD 配合实现全栈 GitOps
Sealed Secrets加密 Secret 安全存储到 Git
External Secrets Operator从 Vault/AWS SM 等外部源同步 Secret
Kustomize与 Argo CD 深度集成的配置管理工具

Question #

ArgoCD 面试题精选 #

基础概念 #

#问题参考答案
1ArgoCD 与 Jenkins 等传统 CI/CD 的核心区别是什么?Jenkins 是 Push 模式(CI 服务器主动推送到集群),ArgoCD 是 Pull 模式(控制器从 Git 拉取期望状态并同步到集群)。Pull 模式更符合 GitOps 原则,无需暴露集群凭证给外部系统,天然具备状态自愈能力。
2什么是 GitOps?ArgoCD 如何体现 GitOps 原则?GitOps 以 Git 为唯一真实来源(Source of Truth),所有基础设施和应用配置声明式存储在 Git 中。ArgoCD 持续监控 Git 变更与集群状态,自动或手动将集群同步到 Git 定义的期望状态。
3ArgoCD 的三大核心组件是什么?各自职责?API Server(gRPC/REST 入口,认证/RBAC/Webhook)、Repository Server(Git 缓存 + 清单渲染)、Application Controller(持续 Reconcile,检测 OutOfSync 并执行同步)。
4Application CRD 中 source 和 destination 分别定义什么?source 定义 Git 仓库地址、路径、revision(分支/tag/commit)和配置管理工具参数;destination 定义目标集群 API Server 地址和目标 namespace。

同步机制 #

#问题参考答案
5Automated Sync 的 prune 和 selfHeal 有什么区别?prune=true:Git 中删除的资源自动从集群中删除;selfHeal=true:集群中被手动修改的资源自动回滚到 Git 定义的状态。两者结合实现完整的声明式管理。
6Sync Waves 和 Resource Hooks 分别解决什么问题?Sync Waves 通过 argocd.argoproj.io/sync-wave annotation 控制同一应用内资源的部署顺序(数字小的先部署);Resource Hooks 在同步生命周期的特定阶段执行任务,如 PreSync 跑数据库迁移、PostSync 发通知。
7OutOfSync 状态一定是问题吗?常见原因有哪些?不一定是问题。常见原因:(1) Git 有新提交尚未同步;(2) 有人手动修改了集群资源;(3) 控制器动态修改了某些字段(如 HPA 修改 replicas),可通过 ignoreDifferences 忽略。
8Sync Window 的 allow 和 deny 模式分别适用于什么场景?allow:仅在指定时间窗口内允许同步(适合生产环境的变更窗口);deny:在指定时间内禁止同步(适合封网期/重大活动期间)。

多集群与多租户 #

#问题参考答案
9ApplicationSet 的常用 Generator 有哪些?List(静态列表)、Cluster(自动发现集群)、Git Directory(按目录生成)、Git File(按配置文件生成)、SCM Provider(发现 GitHub/GitLab 仓库)、Pull Request(预览环境)、Matrix/Merge(组合多个 Generator)。
10AppProject 如何实现多租户隔离?AppProject 可限制:(1) 允许的 Git 仓库(sourceRepos);(2) 允许的目标集群和 namespace(destinations);(3) 允许的集群级资源类型(clusterResourceWhitelist);(4) 禁止的资源类型(namespaceResourceBlacklist);(5) 项目级 RBAC 角色。
11Hub-Spoke 模式 vs 每个集群独立部署 ArgoCD,如何选择?Hub-Spoke 适合集群数量少、网络直通的场景,运维成本低;独立部署适合大规模、网络隔离、安全合规严格的场景。App of Apps 模式可实现分层管理。

生产实践 #

#问题参考答案
12如何在 ArgoCD 中管理 Secret?三种方案:(1) Sealed Secrets — 加密后可安全提交到 Git;(2) External Secrets Operator — 从 Vault/AWS SM/GCP SM 同步;(3) SOPS — Mozilla 的加密工具。避免明文 Secret 提交到 Git。
13ArgoCD 如何与 CI 流水线配合?CI(Tekton/GitHub Actions/Jenkins)负责构建镜像、推送到 Registry、更新 Git 仓库中的镜像 tag;ArgoCD 检测 Git 变更后自动同步到集群。可通过 Webhook 触发即时同步,或使用 Argo Image Updater 直接监控镜像仓库。
14大规模应用中 ApplyOutOfSyncOnly=true 的作用是什么?默认情况下每次同步会 apply 所有资源。当应用包含数千个资源时,该选项只同步 OutOfSync 的资源,减少 API Server 压力并加速同步过程。
15ArgoCD 的 App of Apps 模式是什么?适用于什么场景?用一个根 Application 管理所有子 Application 的声明式定义。适用于:(1) 集群引导(Bootstrap)时自动创建所有基础应用;(2) 全局统一管理和版本控制所有子应用;(3) 配合 ApplicationSet 实现多集群批量部署。

Reference #

Argo CD Official Documentation

Argo CD GitHub Repository

Argo CD Best Practices

Argo CD Example Apps

Killercoda Argo CD Interactive Labs

Argo Blog

OpenGitOps - GitOps Principles

CNCF Argo CD Project Page

Argo CD Demo (Live)