在 Kubernetes 集群中部署 ArgoCD 实现 GitOps 的完整步骤

1. 准备工作
  • 确保已安装并配置 kubectl 访问目标集群
  • 准备 Git 仓库存储应用清单(如 GitHub/GitLab)
2. 安装 ArgoCD
# 创建专用命名空间
kubectl create namespace argocd

# 安装官方清单
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

3. 暴露 ArgoCD Server
# 方式1:端口转发(临时)
kubectl port-forward svc/argocd-server -n argocd 8080:443

# 方式2:修改为 LoadBalancer(生产环境)
kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}'

4. 获取管理员密码
# 获取初始密码
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d

5. 登录 ArgoCD UI
  • 访问 https://localhost:8080 (端口转发) 或 LoadBalancer IP
  • 用户名:admin
  • 密码:上一步获取的密码
6. 配置 Git 仓库连接

在 UI 或 CLI 中添加仓库:

argocd repo add https://github.com/your-repo.git \
  --username <git-user> \
  --password <git-token> \
  --insecure-ignore-host-key

7. 创建应用部署清单

在 Git 仓库中创建应用配置(示例:my-app.yaml):

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: my-app
spec:
  project: default
  source:
    repoURL: https://github.com/your-repo.git
    targetRevision: HEAD
    path: k8s-manifests/  # 存放 K8s 清单的目录
  destination:
    server: https://kubernetes.default.svc
    namespace: my-app-ns
  syncPolicy:
    automated:
      prune: true
      selfHeal: true

8. 部署应用
# 应用配置到集群
kubectl apply -f my-app.yaml

9. 验证 GitOps 流程
  • 在 UI 的 APPLICATIONS 面板查看同步状态
  • 修改 Git 仓库中的清单文件,ArgoCD 将自动同步变更
  • 查看同步日志:
    argocd app logs my-app
    

10. 配置自动同步(可选)

Application 清单中启用自动同步:

syncPolicy:
  automated:
    prune: true
    selfHeal: true

关键概念说明
  1. GitOps 工作流
    $$ \text{Git 仓库} \xrightarrow{\text{变更}} \text{ArgoCD} \xrightarrow{\text{自动同步}} \text{K8s 集群} $$

  2. 同步策略

    • prune: 自动删除集群中已移除的资源
    • selfHeal: 当集群状态偏离 Git 配置时自动修复
故障排查
# 检查控制器状态
kubectl get pods -n argocd

# 查看同步历史
argocd app history my-app

提示:生产环境建议启用 SSO 认证和 RBAC 授权,详细配置参考 ArgoCD 官方文档

更多推荐