本节介绍 CloneSet 最佳实践,以下示例参考 OpenKruise CloneSet 官方文档,展示常用参数的典型用法。

基础部署

以下示例展示了一个最基础的 CloneSet 配置:

apiVersion: apps.kruise.io/v1alpha1
kind: CloneSet
metadata:
  name: sample
spec:
  replicas: 5
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      containers:
        - name: nginx
          image: nginx:alpine

示例 1:原地升级与优雅等待

updateStrategy.type 设置为 InPlaceIfPossible,并配置 gracePeriodSeconds,可以实现优雅原地升级。控制器会先将 Pod 状态改为 NotReady,等待一段时间后,再修改 Pod 中的镜像版本,从而为流量摘除预留缓冲时间。

apiVersion: apps.kruise.io/v1alpha1
kind: CloneSet
metadata:
  name: sample
spec:
  replicas: 5
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      containers:
        - name: nginx
          image: nginx:alpine
  updateStrategy:
    type: InPlaceIfPossible
    inPlaceUpdateStrategy:
      gracePeriodSeconds: 10

示例 2:分批灰度发布

使用 partition 控制保留旧版本 Pod 的数量或百分比。以下示例保留 3 个旧版本 Pod,仅升级 2 个 Pod 到新版本。

apiVersion: apps.kruise.io/v1alpha1
kind: CloneSet
metadata:
  name: sample
spec:
  replicas: 5
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      containers:
        - name: nginx
          image: nginx:mainline
  updateStrategy:
    type: InPlaceIfPossible
    partition: 3

示例 3:最大不可用与最大弹性数量

通过配置 maxUnavailablemaxSurge,可以控制发布窗口和弹性容量,降低发布期间的服务中断风险。

apiVersion: apps.kruise.io/v1alpha1
kind: CloneSet
metadata:
  name: sample
spec:
  replicas: 5
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      containers:
        - name: nginx
          image: nginx:alpine
  updateStrategy:
    type: InPlaceIfPossible
    maxUnavailable: 20%
    maxSurge: 3

示例 4:PVC 模板

通过 volumeClaimTemplates,可以为每个 Pod 生成独享 PVC,适用于需要本地缓存的无状态应用。缩容时删除 Pod,关联 PVC 也会一并删除;原地升级时,PVC 会持续保留并复用。

apiVersion: apps.kruise.io/v1alpha1
kind: CloneSet
metadata:
  name: sample-data
spec:
  replicas: 5
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      containers:
        - name: nginx
          image: nginx:alpine
          volumeMounts:
            - name: data-vol
              mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
    - metadata:
        name: data-vol
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 20Gi

示例 5:指定缩容 Pod

缩容时可通过 podsToDelete 精确指定要删除的 Pod;也可以直接给目标 Pod 添加 apps.kruise.io/specified-delete: "true" 标签。

apiVersion: apps.kruise.io/v1alpha1
kind: CloneSet
metadata:
  name: sample
spec:
  replicas: 4
  selector:
    matchLabels:
      app: sample
  scaleStrategy:
    podsToDelete:
      - sample-9m4hp