深色模式
Flux 实战:轻量 GitOps
摘要:Flux 是 CNCF 毕业的 GitOps 工具,全部用 CRD 表达、没有自带 UI、资源占用更小。本文用 CLI 完成 bootstrap,配置 Git 源与 Kustomization,并启用镜像自动更新。
适用环境
- 一个 Kubernetes 集群(kind/minikube 可练习)
kubectl可访问集群- 一个 GitHub/GitLab 仓库与具备写权限的 Personal Access Token
操作步骤
1. 安装 CLI 与 bootstrap
bash
curl -s https://fluxcd.io/install.sh | sudo bash
export GITHUB_TOKEN=<你的Token>
flux bootstrap github \
--owner=<你的账号> --repository=flux-config \
--branch=main --path=./clusters/dev --personal1
2
3
4
5
2
3
4
5
这一步会:安装 Flux 控制器 → 在仓库创建 clusters/dev/flux-system/ → 让 Flux 自管理自身配置。GitLab 用 flux bootstrap gitlab,自建 Git 用 flux bootstrap git。
2. 部署一个应用
bash
mkdir -p clusters/dev/apps/nginx
cat > clusters/dev/apps/nginx/kustomization.yaml <<'EOF'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources: [deployment.yaml]
EOF
cat > clusters/dev/apps/nginx/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata: { name: nginx }
spec:
replicas: 2
selector: { matchLabels: { app: nginx } }
template:
metadata: { labels: { app: nginx } }
spec:
containers: [{ name: nginx, image: nginx:alpine }]
EOF
git add . && git commit -m "add nginx" && git push
flux reconcile kustomization apps --with-source # 不想等 1 分钟轮询1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3. 配置镜像自动更新
bash
flux create image repository nginx --image=nginx --interval=5m \
--export > clusters/dev/apps/nginx/imagerepo.yaml
flux create image policy nginx --image-ref=nginx \
--select-semver=">=1.25.0 <1.27.0" --export > clusters/dev/apps/nginx/imagepolicy.yaml
flux create image update flux-system --git-repo-ref=flux-system \
--git-repo-path=./clusters/dev --checkout-branch=main --push-branch=main \
--author-name=fluxcdbot --author-email=fluxcdbot@users.noreply.github.com \
--interval=5m --export > clusters/dev/flux-system-automation.yaml1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Deployment 上打标记指明改哪个字段:
yaml
containers:
- name: nginx
image: nginx:1.25.0 # {"$imagepolicy": "flux-system:nginx"}1
2
3
2
3
4. 与 Argo CD 怎么选
text
选 Flux:追求轻量、纯 CRD、无需 UI;需要强大的镜像自动更新;习惯 CLI
选 Argo CD:需要可视化 UI、多集群视图、图形化回滚;需要 ApplicationSet 批量管理1
2
2
危险
启用镜像自动更新后 Flux 会向你的 Git 仓库推送提交。务必使用专用 Token 并限定仓库范围。
验证
bash
flux check && flux get kustomizations
kubectl -n default get deploy nginx
flux logs --level=error1
2
3
2
3
- [ ]
flux check全部通过 - [ ] 改 Git 中 replicas 后 1 分钟内集群跟随变化
- [ ] 手动删掉 Deployment,Flux 自动重建
常见坑
Token 权限不足
bootstrap 需要仓库读写权限(建分支、写文件)。Token 只给只读会卡在创建阶段。
reconcile 没生效
Flux 有独立轮询间隔,改完 Git 最快等 1 分钟。调试用 flux reconcile --with-source。
两个工具混装
同一集群不要同时用 Argo CD 和 Flux 管理同一批资源,会互相覆盖。