Kubernetes部署从手动kubectl apply到声明式GitOps,核心变化是把Git仓库作为应用状态的唯一真实来源。ArgoCD持续监听Git仓库中的manifest变更,自动同步到集群,任何手动修改都会被检测和回滚。本文给出ArgoCD的安装、Application配置、多环境同步策略与权限管理方案。
ArgoCD架构与安装部署
ArgoCD运行在Kubernetes集群内部,由API Server、Repository Server、Application Controller三个核心组件构成。Repository Server负责克隆Git仓库并生成渲染后的manifest,Application Controller对比Git仓库与集群实际状态的差异,触发同步操作。
# 安装ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
# 获取初始密码
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d
# 端口转发访问UI
kubectl port-forward svc/argocd-server -n argocd 8080:443
生产环境建议通过Ingress暴露ArgoCD API和UI,并配置SSO登录,不使用初始admin密码长期运行。
Application声明式配置:Git仓库与同步策略
ArgoCD Application可以用CRD声明式定义,存放在Git仓库中实现Application of Applications模式:
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: my-app-prod
namespace: argocd
spec:
source:
repoURL: https://github.com/org/k8s-manifests
targetRevision: main
path: apps/my-app/overlays/production
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
几个关键参数的含义:prune: true表示Git中删除的资源在集群中也删除;selfHeal: true检测到有人手动修改集群资源时自动恢复为Git定义的状态;CreateNamespace=true自动创建目标命名空间。这三个选项组合实现了真正的GitOps——Git仓库即最终真相,任何偏离都会被纠正。
多环境配置管理:Kustomize Overlay方案
开发、测试、生产三个环境的manifest差异通过Kustomize overlay管理,避免维护多份完整YAML:
# 目录结构
apps/my-app/
base/
deployment.yaml
service.yaml
kustomization.yaml
overlays/
dev/
kustomization.yaml
patches/
replicas-patch.yaml
prod/
kustomization.yaml
patches/
replicas-patch.yaml
resources-patch.yaml
每个overlay引用base目录,只写差异部分。开发环境1副本低资源,生产环境3副本高资源,base里写公共配置。ArgoCD Application中path分别指向overlays/dev和overlays/prod,Git提交后各环境独立同步。
同步窗口与进度级控制
生产环境不能任意时间自动同步,需要配置Sync Window限制同步时间窗口:
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
name: production
namespace: argocd
spec:
sourceRepos:
- https://github.com/org/k8s-manifests
destinations:
- namespace: production
server: https://kubernetes.default.svc
syncWindows:
- kind: allow
schedule: "0 9-18 * * 1-5"
duration: "9h"
applications:
- "*"
namespaces:
- production
这个配置允许周一到周五9点到18点自动同步生产环境,其余时间自动同步被暂停,手动同步仍可触发。配合ArgoCD的PreSync Hook做数据库迁移等前置操作,PostSync Hook做健康检查与通知。
ArgoCD与CI流水线的协作边界
ArgoCD只负责CD(持续部署),不负责CI(持续集成)。标准协作模式:CI流水线(GitLab CI或GitHub Actions)负责构建镜像、跑测试、更新Git仓库中manifest的image tag,ArgoCD检测到Git变更后自动同步到集群。两套系统各司其职,CI不直接操作Kubernetes,CD不构建镜像,通过Git仓库解耦。这种分离让回滚操作变得简单——只需在Git中revert提交,ArgoCD自动将集群状态恢复到上一个版本。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/argocdgitops-chi-xu-jiao-fu-shi-zhan-sheng-ming-shi-bu-shu/