Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

入门

本指南创建一个示例项目以演示其工作方式。该示例:

  • 对 Memcached CR 进行调整 - 该 CR 表示在集群上部署/管理的 Memcached 实例
  • 使用 Memcached 镜像创建一个部署
  • 不允许超过 CR 中定义的 size 的实例数
  • 更新 Memcached CR 状态

创建一个项目

首先,创建并导航到你的项目目录。然后,使用 kubebuilder 初始化它:

mkdir $GOPATH/memcached-operator
cd $GOPATH/memcached-operator
kubebuilder init --domain=example.com

创建 Memcached API(CRD)

接下来,创建负责在集群上部署并管理 Memcached 实例的 API。

kubebuilder create api --group cache --version v1alpha1 --kind Memcached

理解API

该命令的主要目的是为 Memcached Kind 生成自定义资源(CR)与自定义资源定义(CRD)。它创建 group 为 cache.example.com、version 为 v1alpha1 的 API,唯一标识 Memcached Kind 的新 CRD。借助 Kubebuilder,您可以定义代表这些平台上解决方案的 API 与对象。

本示例只添加一种 Kind 资源,但您可以按需拥有任意数量的 Groups 与 Kinds。为便于理解,可将 CRD 视为自定义对象的定义,而 CR 是它们的实例。

定义我们的 API

定义 Spec

现在定义集群上每个 Memcached 资源实例可取的值。本例中,配置允许用如下方式设置实例数量:

type MemcachedSpec struct {
	...
	// +kubebuilder:validation:Minimum=0
	// +required
	Size *int32 `json:"size,omitempty"`
}

创建 Status 定义

控制器还需要跟踪为管理 Memcached CR 所执行操作的状态。这样可以核验自定义资源对 API 的描述,并判断是否全部成功或是否遇到错误,方式与处理任何 Kubernetes API 资源相同。

// MemcachedStatus 定义了 Memcached 的观察状态
type MemcachedStatus struct {
    // +listType=map
    // +listMapKey=type
    // +optional
    Conditions []metav1.Condition `json:"conditions,omitempty"`
}

标记和验证

此外,应对 CustomResource 中的取值进行校验以确保有效。为此可使用标记,例如 +kubebuilder:validation:Minimum=1。

现在,请查看我们完全完成的示例。

../getting-started/testdata/project/api/v1alpha1/memcached_types.go
Apache License

Copyright 2026 The Kubernetes authors.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Imports
package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

// 请编辑本文件!这是供您拥有的脚手架代码!
// 注意:需要 json 标签。新增字段必须带有 json 标签才能被序列化。
// MemcachedSpec 定义 Memcached 的期望状态
type MemcachedSpec struct {
	// 在此插入额外 SPEC 字段 — 集群期望状态
	// 重要:修改本文件后请运行 "make" 重新生成代码
	// 下列标记将使用 OpenAPI v3 schema 校验取值
	// 更多信息: https://book.kubebuilder.io/reference/markers/crd-validation.html

	// size 定义 Memcached 实例数量
	// 下列标记将使用 OpenAPI v3 schema 校验取值
	// 更多信息: https://book.kubebuilder.io/reference/markers/crd-validation.html
	// +kubebuilder:validation:Minimum=1
	// +kubebuilder:validation:Maximum=3
	// +kubebuilder:validation:ExclusiveMaximum=false
	// +optional
	Size *int32 `json:"size,omitempty"`
}

// MemcachedStatus 定义 Memcached 的观测状态.
type MemcachedStatus struct {
	// 插入额外的状态字段 - 定义集群的观察状态
	// 重要:在修改此文件后,请运行 "make" 以重新生成代码

	// Kubernetes API 约定参见:
	// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties

	// conditions 表示 Memcached 资源的当前状态。
	// 每个 condition 有唯一类型,反映资源某一方面的状态。
	//
	// Standard condition types include:
	// - "Available": the resource is fully functional
	// - "Progressing": the resource is being created or updated
	// - "Degraded": the resource failed to reach or maintain its desired state
	//
	// The status of each condition is one of True, False, or Unknown.
	// +listType=map
	// +listMapKey=type
	// +optional
	Conditions []metav1.Condition `json:"conditions,omitempty"`
}

// +kubebuilder:object:root=true
// +kubebuilder:subresource:status

// Memcached 是 memcacheds API 的 Schema
type Memcached struct {
	metav1.TypeMeta `json:",inline"`

	// metadata 是标准对象元数据
	// +optional
	metav1.ObjectMeta `json:"metadata,omitzero"`

	// spec 定义 Memcached 的期望状态
	// +required
	Spec MemcachedSpec `json:"spec"`

	// status 定义 Memcached 的观测状态
	// +optional
	Status MemcachedStatus `json:"status,omitzero"`
}

// +kubebuilder:object:root=true

// MemcachedList 包含 Memcached 的列表
type MemcachedList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitzero"`
	Items           []Memcached `json:"items"`
}

func init() {
	SchemeBuilder.Register(func(s *runtime.Scheme) error {
		s.AddKnownTypes(SchemeGroupVersion, &Memcached{}, &MemcachedList{})
		return nil
	})
}

生成具有规格和验证的清单

生成所有所需的文件:

  1. 运行 make generate,会在 api/v1alpha1/zz_generated.deepcopy.go 文件中添加深度拷贝(DeepCopy)内容。

  2. 然后运行 make manifests,在 config/crd/bases 下生成 CRD 清单,并在 config/samples 下生成示例。

这两个命令都使用 controller-gen 工具,但是用于代码和清单生成的标志会有所不同。

config/crd/bases/cache.example.com_memcacheds.yaml: Our Memcached CRD
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  annotations:
    controller-gen.kubebuilder.io/version: v0.22.0
  name: memcacheds.cache.example.com
spec:
  group: cache.example.com
  names:
    kind: Memcached
    listKind: MemcachedList
    plural: memcacheds
    singular: Memcached
  scope: Namespaced
  versions:
  - name: v1alpha1
    schema:
      openAPIV3Schema:
        description: Memcached 是 memcacheds API 的 Schema
        properties:
          apiVersion:
            description: |-
              APIVersion defines the versioned schema of this representation of an object.
              Servers should convert recognized schemas to the latest internal value, and
              may reject unrecognized values.
              More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
            type: string
          kind:
            description: |-
              Kind is a string value representing the REST resource this object represents.
              Servers may infer this from the endpoint the client submits requests to.
              Cannot be updated.
              In CamelCase.
              More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
            type: string
          metadata:
            type: object
          spec:
            description: spec defines the desired state of Memcached
            properties:
              size:
                description: |-
                  size defines the number of Memcached instances
                  The following markers will use OpenAPI v3 schema to validate the value
                  More info: https://book.kubebuilder.io/reference/markers/crd-validation.html
                format: int32
                maximum: 3
                minimum: 1
                type: integer
            type: object
          status:
            description: status defines the observed state of Memcached
            properties:
              conditions:
                description: |-
                  conditions represent the current state of the Memcached resource.
                  Each condition has a unique type and reflects the status of a specific aspect of the resource.

                  Standard condition types include:
                  - "Available": the resource is fully functional
                  - "Progressing": the resource is being created or updated
                  - "Degraded": the resource failed to reach or maintain its desired state

                  The status of each condition is one of True, False, or Unknown.
                items:
                  description: Condition contains details for one aspect of the current
                    state of this API Resource.
                  properties:
                    lastTransitionTime:
                      description: |-
                        lastTransitionTime is the last time the condition transitioned from one status to another.
                        This should be when the underlying condition changed.  If that is not known, then using the time when the API field changed is acceptable.
                      format: date-time
                      type: string
                    message:
                      description: |-
                        message is a human readable message indicating details about the transition.
                        This may be an empty string.
                      maxLength: 32768
                      type: string
                    observedGeneration:
                      description: |-
                        observedGeneration represents the .metadata.generation that the condition was set based upon.
                        For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date
                        with respect to the current state of the instance.
                      format: int64
                      minimum: 0
                      type: integer
                    reason:
                      description: |-
                        reason contains a programmatic identifier indicating the reason for the condition's last transition.
                        Producers of specific condition types may define expected values and meanings for this field,
                        and whether the values are considered a guaranteed API.
                        The value should be a CamelCase string.
                        This field may not be empty.
                      maxLength: 1024
                      minLength: 1
                      pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$
                      type: string
                    status:
                      description: status of the condition, one of True, False, Unknown.
                      enum:
                      - "True"
                      - "False"
                      - Unknown
                      type: string
                    type:
                      description: type of condition in CamelCase or in foo.example.com/CamelCase.
                      maxLength: 316
                      pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$
                      type: string
                  required:
                  - lastTransitionTime
                  - message
                  - reason
                  - status
                  - type
                  type: object
                type: array
                x-kubernetes-list-map-keys:
                - type
                x-kubernetes-list-type: map
            type: object
        required:
        - spec
        type: object
    served: true
    storage: true
    subresources:
      status: {}

自定义资源示例

在 config/samples 目录下的清单,可以应用于集群的自定义资源示例。在这个例子中,通过将给定的资源应用于集群,我们将生成一个实例大小为1的部署(请参见 size: 1)。

apiVersion: cache.example.com/v1alpha1
kind: Memcached
metadata:
  labels:
    app.kubernetes.io/name: project
    app.kubernetes.io/managed-by: kustomize
  name: memcached-sample
spec:
  # TODO(用户):编辑以下值以确保您的操作数在集群中的 Pod/实例数量
 size: 1

协调过程

简单来说,Kubernetes 允许声明系统期望状态,控制器持续观察集群并采取行动,使实际状态与期望状态一致。自定义 API 与控制器的过程类似。请记住,您是在扩展 Kubernetes 行为及其 API 以满足特定需求。

在控制器中,我们实现协调过程。

本质上, reconciliation 过程作为一个循环运行,不断检查条件并执行必要的操作,直到达到所需的状态。该过程将持续运行,直到系统中的所有条件与我们实施中定义的所需状态一致。

这是一个伪代码示例来说明这一点:

reconcile App {

  // 检查应用的 Deployment 是否存在,若不存在则创建
  // 若出错,则从协调过程开头重新开始
  if err != nil {
    return reconcile.Result{}, err
  }

  // 检查应用的 Service 是否存在,若不存在则创建
  // 若出错,则从协调过程开头重新开始
  if err != nil {
    return reconcile.Result{}, err
  }

  // 查找 Database CR/CRD
  // 检查 Database Deployment 的副本数
  // 若 deployment.replicas 与 cr.size 不匹配, then update it
  // Then, requeue the reconciliation to ensure the desired state is reached. For example, by returning `reconcile.Result{RequeueAfter: time.Minute}, nil`.
  if err != nil {
    return reconcile.Result{RequeueAfter: time.Minute}, nil
  }
  ...

  // 若循环结束时:
  // 全部执行成功,协调可以停止
  return reconcile.Result{}, nil

}

在我们例子的背景下。

将示例自定义资源(CR)应用到集群时(即 kubectl apply -f config/sample/cache_v1alpha1_memcached.yaml),确保控制器为 Memcached 镜像创建 Deployment,且副本数与 CR 中定义一致。

为此,首先实现检查集群上是否已有该 Memcached 实例的 Deployment 的操作;若不存在,控制器再创建。因此协调过程必须包含用于持续维持该期望状态的操作,例如:

	// 检查部署是否已经存在,如果不存在则创建一个新部署。
	found := &appsv1.Deployment{}
	err = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)
	if err != nil && apierrors.IsNotFound(err) {
		// 定义新的部署 
		dep := r.deploymentForMemcached()
		// 在集群上创建部署
		if err = r.Create(ctx, dep); err != nil {
            log.Error(err, "无法创建新的部署",
            "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
            return ctrl.Result{}, err
        }
		...
	}

接下来注意,deploymentForMemcached() 需要定义并返回应在集群上创建的 Deployment。该函数应按必要规格构造 Deployment 对象,如下例所示:

    dep := &appsv1.Deployment{
		Spec: appsv1.DeploymentSpec{
			Replicas: &replicas,
			Template: corev1.PodTemplateSpec{
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{{
						Image:           "memcached:1.6.26-alpine3.19",
						Name:            "memcached",
						ImagePullPolicy: corev1.PullIfNotPresent,
						Ports: []corev1.ContainerPort{{
							ContainerPort: 11211,
							Name:          "memcached",
						}},
						Command: []string{"memcached", "--memory-limit=64", "-o", "modern", "-v"},
					}},
				},
			},
		},
	}

此外,实现机制以校验集群上 Memcached 副本数是否与 Custom Resource(CR)中的期望数量一致。若不一致,协调必须更新集群以保持一致。这意味着每当创建或更新 Memcached Kind 的 CR 时,控制器会持续协调,直到实际副本数与期望一致。下例说明该过程:

	...
	size := memcached.Spec.Size
	if *found.Spec.Replicas != size {
		found.Spec.Replicas = &size
		if err = r.Update(ctx, found); err != nil {
			log.Error(err, "Failed to update Deployment",
				"Deployment.Namespace", found.Namespace, "Deployment.Name", found.Name)
            return ctrl.Result{}, err
        }
    ...

现在,您可以查看负责管理 Memcached 类型自定义资源的完整控制器。该控制器确保集群中维持所需状态,确保我们的 Memcached 实例继续运行,并保持用户指定的副本数量。

internal/controller/memcached_controller.go: Our Controller Implementation
/*
Copyright 2026 The Kubernetes authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"context"
	"fmt"
	"time"

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"

	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	logf "sigs.k8s.io/controller-runtime/pkg/log"

	cachev1alpha1 "example.com/memcached/api/v1alpha1"
)

// 管理状态条件的定义
const (
	// typeAvailableMemcached 表示部署调整的状态
	typeAvailableMemcached = "Available"
)

const memcachedContainerName = "memcached"

// MemcachedReconciler 负责调整 Memcached 对象。
type MemcachedReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups=cache.example.com,resources=memcacheds,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=cache.example.com,resources=memcacheds/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=cache.example.com,resources=memcacheds/finalizers,verbs=update
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch

// Reconcile 是主 kubernetes 协调循环的一部分,其目标是
// 使集群当前状态更接近期望状态。
// It is essential for the controller's reconciliation loop to be idempotent. By following the Operator
// pattern you will create Controllers which provide a reconcile function
// responsible for synchronizing resources until the desired state is reached on the cluster.
// Breaking this recommendation goes against the design principles of controller-runtime.
// and may lead to unforeseen consequences such as resources becoming stuck and requiring manual intervention.
// For further info:
// - About Operator Pattern: https://kubernetes.io/docs/concepts/extend-kubernetes/operator/
// - About Controllers: https://kubernetes.io/docs/concepts/architecture/controller/
//
// 更多细节参见 Reconcile 及其 Result:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.25.0/pkg/reconcile
func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	log := logf.FromContext(ctx)

	// 获取 Memcached 实例
	// 目的是检查 Kind Memcached 的自定义资源是否
	// 已在集群上应用,如果没有,我们返回 nil 以停止对账过程
	memcached := &cachev1alpha1.Memcached{}
	err := r.Get(ctx, req.NamespacedName, memcached)
	if err != nil {
		if apierrors.IsNotFound(err) {
			// 如果未找到自定义资源,通常意味着它已被删除或未创建
			// 这样,我们将停止调整过程
			log.Info("Memcached resource not found. Ignoring since object must be deleted")
			return ctrl.Result{}, nil
		}
		// 读取对象时出错 - 重新排队请求。
		log.Error(err, "Failed to get memcached")
		return ctrl.Result{}, err
	}

	// 当没有可用状态时,我们将状态设置为未知。
	if len(memcached.Status.Conditions) == 0 {
		meta.SetStatusCondition(&memcached.Status.Conditions, metav1.Condition{Type: typeAvailableMemcached, Status: metav1.ConditionUnknown, Reason: reasonReconciling, Message: "Starting reconciliation"})
		if err = r.Status().Update(ctx, memcached); err != nil {
			log.Error(err, "Failed to update Memcached status")
			return ctrl.Result{}, err
		}

		// 在更新状态后,让我们重新获取 memcached 自定义资源
		// 这样我们就可以获得集群中资源的最新状态,避免
		// 引发错误"对象已被修改,请将
		// 您的更改应用于最新版本并重试",这将在后续操作中
		// 如果我们再次尝试更新它,将重新触发对账过程
		if err := r.Get(ctx, req.NamespacedName, memcached); err != nil {
			log.Error(err, "Failed to re-fetch memcached")
			return ctrl.Result{}, err
		}
	}

	// 检查部署是否已经存在,如果不存在则创建一个新部署。
	found := &appsv1.Deployment{}
	err = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)
	if err != nil && apierrors.IsNotFound(err) {
		// 定义新的部署 
		dep, err := r.deploymentForMemcached(memcached)
		if err != nil {
			log.Error(err, "Failed to define new Deployment resource for Memcached")

			// 以下实现将更新状态
			meta.SetStatusCondition(&memcached.Status.Conditions, metav1.Condition{Type: typeAvailableMemcached,
				Status: metav1.ConditionFalse, Reason: reasonReconciling,
				Message: fmt.Sprintf("Failed to create Deployment for the custom resource (%s): (%s)", memcached.Name, err)})

			if err := r.Status().Update(ctx, memcached); err != nil {
				log.Error(err, "Failed to update Memcached status")
				return ctrl.Result{}, err
			}

			return ctrl.Result{}, err
		}

		log.Info("Creating a new Deployment",
			"Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
		if err = r.Create(ctx, dep); err != nil {
			log.Error(err, "无法创建新的部署",
				"Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
			return ctrl.Result{}, err
		}

		// 部署成功创建
		// 我们将重新排队调整,以确保状态
		// 并继续进行下一步操作
		return ctrl.Result{RequeueAfter: time.Minute}, nil
	} else if err != nil {
		log.Error(err, "Failed to get Deployment")
		// 让我们返回错误,以便重新触发对账。
		return ctrl.Result{}, err
	}

	// 若 Custom Resource 未定义 size,则将期望副本数设为 0
	var desiredReplicas int32 = 0
	if memcached.Spec.Size != nil {
		desiredReplicas = *memcached.Spec.Size
	}

	// CRD API 定义了 Memcached 类型具有一个 MemcachedSpec.Size 字段
	// 用于设置集群中部署实例的数量到所需状态。
	// 因此,以下代码将确保部署的大小与我们正在对账的
	// 自定义资源的 Size 规格中定义的相同。
	if found.Spec.Replicas == nil || *found.Spec.Replicas != desiredReplicas {
		found.Spec.Replicas = new(desiredReplicas)
		if err = r.Update(ctx, found); err != nil {
			log.Error(err, "Failed to update Deployment",
				"Deployment.Namespace", found.Namespace, "Deployment.Name", found.Name)

			// 在更新状态之前重新获取 memcached 自定义资源,
			// 以便我们能够获得集群中资源的最新状态,并避免
			// 引发错误"对象已被修改,请将您的更改应用于
			// 最新版本并重试",这将重新触发调整。
			if err := r.Get(ctx, req.NamespacedName, memcached); err != nil {
				log.Error(err, "Failed to re-fetch memcached")
				return ctrl.Result{}, err
			}

			// 以下实现将更新状态
			meta.SetStatusCondition(&memcached.Status.Conditions, metav1.Condition{Type: typeAvailableMemcached,
				Status: metav1.ConditionFalse, Reason: "Resizing",
				Message: fmt.Sprintf("Failed to update the size for the custom resource (%s): (%s)", memcached.Name, err)})

			if err := r.Status().Update(ctx, memcached); err != nil {
				log.Error(err, "Failed to update Memcached status")
				return ctrl.Result{}, err
			}

			return ctrl.Result{}, err
		}

		// 现在我们更新了大小,我们想要重新排队对账
		// 以便确保在更新之前我们拥有资源的最新状态。
		// 此外,它还将有助于确保集群上的期望状态。
		return ctrl.Result{RequeueAfter: time.Minute}, nil
	}

	// 以下实现将更新状态
	meta.SetStatusCondition(&memcached.Status.Conditions, metav1.Condition{Type: typeAvailableMemcached,
		Status: metav1.ConditionTrue, Reason: reasonReconciling,
		Message: fmt.Sprintf("自定义资源(%s)部署成功,创建了 %d 个副本", memcached.Name, desiredReplicas)})

	if err := r.Status().Update(ctx, memcached); err != nil {
		log.Error(err, "Failed to update Memcached status")
		return ctrl.Result{}, err
	}

	return ctrl.Result{}, nil
}

// SetupWithManager 将控制器与管理器进行设置。
func (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&cachev1alpha1.Memcached{}).
		Owns(&appsv1.Deployment{}).
		Named("memcached").
		Complete(r)
}

// deploymentForMemcached 返回一个 Memcached 部署对象。
func (r *MemcachedReconciler) deploymentForMemcached(
	memcached *cachev1alpha1.Memcached) (*appsv1.Deployment, error) {
	image := "memcached:1.6.26-alpine3.19"

	dep := &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      memcached.Name,
			Namespace: memcached.Namespace,
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: memcached.Spec.Size,
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{"app.kubernetes.io/name": "project"},
			},
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{"app.kubernetes.io/name": "project"},
				},
				Spec: corev1.PodSpec{
					SecurityContext: &corev1.PodSecurityContext{
						RunAsNonRoot: new(true),
						SeccompProfile: &corev1.SeccompProfile{
							Type: corev1.SeccompProfileTypeRuntimeDefault,
						},
					},
					Containers: []corev1.Container{{
						Image:           image,
						Name:            memcachedContainerName,
						ImagePullPolicy: corev1.PullIfNotPresent,
						// 确保容器的限制性上下文
						// 详细信息请参考: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted
						SecurityContext: &corev1.SecurityContext{
							RunAsNonRoot:             new(true),
							RunAsUser:                new(int64(1001)),
							AllowPrivilegeEscalation: new(false),
							Capabilities: &corev1.Capabilities{
								Drop: []corev1.Capability{
									"ALL",
								},
							},
						},
						Ports: []corev1.ContainerPort{{
							ContainerPort: 11211,
							Name:          memcachedContainerName,
						}},
						Command: []string{"memcached", "--memory-limit=64", "-o", "modern", "-v"},
					}},
				},
			},
		},
	}

	// 设置 Deployment 的 ownerRef
	// 更多信息: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
	if err := ctrl.SetControllerReference(memcached, dep, r.Scheme); err != nil {
		return nil, err
	}
	return dep, nil
}

深入控制器实现

配置 Manager 监视资源

整个想法是关注对控制器重要的资源。当控制器感兴趣的资源发生变化时,Watch 会触发控制器的对账循环,确保资源的实际状态与控制器逻辑中定义的期望状态相匹配。

注意如何配置 Manager,以监视 Memcached Kind 自定义资源(CR)的创建、更新或删除,以及控制器所管理并拥有的 Deployment 的任何变更:

// SetupWithManager 将控制器与管理器设置起来。
// 部署也会被监视以确保其
// 在集群中的期望状态。
func (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).
		// 监视 Memcached 自定义资源,并在其
		//创建、更新或删除时触发协调
		For(&cachev1alpha1.Memcached{}).
		// 监视由 Memcached 控制器管理的 Deployment。若 Deployment 发生任何变更
        // owned and managed by this controller, it triggers reconciliation, ensuring that the cluster
        // state aligns with the desired state.
		Owns(&appsv1.Deployment{}).
		Complete(r)
    }

但是,Manager 如何知道哪些资源归它所有?

控制器不应监视集群上任意 Deployment 并触发协调循环,而应仅在运行 Memcached 实例的特定 Deployment 发生变化时触发。例如,若有人误删 Deployment 或更改副本数,应触发协调以恢复期望状态。

Manager 知道应观察哪个 Deployment,是因为设置了 ownerRef(所有者引用):

if err := ctrl.SetControllerReference(memcached, dep, r.Scheme); err != nil {
    return nil, err
}

授予权限

务必确保控制器对其管理的资源具备必要权限(例如 create、get、update、list)。

通过 RBAC 标记 配置 RBAC 权限,controller-gen 据此生成并更新 config/rbac/ 中的清单。可在各控制器的 Reconcile() 方法上找到(并应定义)这些标记,参见示例实现:

// +kubebuilder:rbac:groups=cache.example.com,resources=memcacheds,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=cache.example.com,resources=memcacheds/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=cache.example.com,resources=memcacheds/finalizers,verbs=update
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch

修改控制器后,运行 make manifests。这将让 controller-gen 刷新 config/rbac 下的文件。

config/rbac/role.yaml: Our RBAC Role generated
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: manager-role
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - apps
  resources:
  - deployments
  verbs:
  - create
  - delete
  - get
  - list
  - patch
  - update
  - watch
- apiGroups:
  - cache.example.com
  resources:
  - memcacheds
  verbs:
  - create
  - delete
  - get
  - list
  - patch
  - update
  - watch
- apiGroups:
  - cache.example.com
  resources:
  - memcacheds/finalizers
  verbs:
  - update
- apiGroups:
  - cache.example.com
  resources:
  - memcacheds/status
  verbs:
  - get
  - patch
  - update
- apiGroups:
  - events.k8s.io
  resources:
  - events
  verbs:
  - create
  - patch

监控程序 (main.go)

cmd/main.go 文件中的 Manager 负责管理您应用程序中的控制器。

cmd/main.go: Our main.go
/*
Copyright 2026 The Kubernetes authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"crypto/tls"
	"flag"
	"os"

	// 导入所有 Kubernetes 客户端身份验证插件(例如 Azure、GCP、OIDC 等)
	// 确保 exec-entrypoint 和 run 可以使用它们。
	_ "k8s.io/client-go/plugin/pkg/client/auth"

	"k8s.io/apimachinery/pkg/runtime"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/healthz"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"
	"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
	metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
	"sigs.k8s.io/controller-runtime/pkg/webhook"

	cachev1alpha1 "example.com/memcached/api/v1alpha1"
	"example.com/memcached/internal/controller"
	// +kubebuilder:scaffold:imports
)

var (
	scheme   = runtime.NewScheme()
	setupLog = ctrl.Log.WithName("setup")
)

func init() {
	utilruntime.Must(clientgoscheme.AddToScheme(scheme))

	utilruntime.Must(cachev1alpha1.AddToScheme(scheme))
	// +kubebuilder:scaffold:scheme
}

// nolint:gocyclo
func main() {
	var metricsAddr string
	var metricsCertPath, metricsCertName, metricsCertKey string
	var webhookCertPath, webhookCertName, webhookCertKey string
	var webhookPort int
	var enableLeaderElection bool
	var probeAddr string
	var secureMetrics bool
	var enableHTTP2 bool
	var tlsOpts []func(*tls.Config)
	flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
		"使用 :8443 进行 HTTPS,使用 :8080 进行 HTTP,或者保持为 0 以禁用指标服务。")
	flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
	flag.BoolVar(&enableLeaderElection, "leader-elect", false,
		"Enable leader election for controller manager. "+
			"启用此功能将确保只有一个活动的控制管理器。")
	flag.BoolVar(&secureMetrics, "metrics-secure", true,
		"如果设置,指标端点将通过 HTTPS 安全提供。请使用 --metrics-secure=false 以改为使用 HTTP。")
	flag.StringVar(&webhookCertPath, "webhook-cert-path", "", "The directory that contains the webhook certificate.")
	flag.StringVar(&webhookCertName, "webhook-cert-name", "tls.crt", "The name of the webhook certificate file.")
	flag.StringVar(&webhookCertKey, "webhook-cert-key", "tls.key", "The name of the webhook key file.")
	flag.IntVar(&webhookPort, "webhook-port", 9443, "Port the webhook server listens on. "+
		"Defaults to 9443. Set -1 to disable the webhook server.")
	flag.StringVar(&metricsCertPath, "metrics-cert-path", "",
		"The directory that contains the metrics server certificate.")
	flag.StringVar(&metricsCertName, "metrics-cert-name", "tls.crt", "The name of the metrics server certificate file.")
	flag.StringVar(&metricsCertKey, "metrics-cert-key", "tls.key", "The name of the metrics server key file.")
	flag.BoolVar(&enableHTTP2, "enable-http2", false,
		"If set, HTTP/2 will be enabled for the metrics and webhook servers")
	opts := zap.Options{
		Development: true,
	}
	opts.BindFlags(flag.CommandLine)
	flag.Parse()

	ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

	// 如果 enable-http2 标志为 false(默认值),则应禁用 http/2
	// 由于其存在的漏洞。更具体地说,禁用 http/2 将
	// 防止受到 HTTP/2 流取消和
	// 快速重置 CVE 的漏洞影响。有关更多信息,请参见:
	// - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
	// - https://github.com/advisories/GHSA-4374-p667-p6c8
	disableHTTP2 := func(c *tls.Config) {
		setupLog.Info("Disabling HTTP/2")
		c.NextProtos = []string{"http/1.1"}
	}

	if !enableHTTP2 {
		tlsOpts = append(tlsOpts, disableHTTP2)
	}

	// 初始Webhook TLS选项
	webhookTLSOpts := tlsOpts
	webhookServerOptions := webhook.Options{
		TLSOpts: webhookTLSOpts,
		Port:    webhookPort,
	}

	if len(webhookCertPath) > 0 {
		setupLog.Info("使用提供的证书初始化 Webhook 证书监视器",
			"webhook-cert-path", webhookCertPath, "webhook-cert-name", webhookCertName, "webhook-cert-key", webhookCertKey)

		webhookServerOptions.CertDir = webhookCertPath
		webhookServerOptions.CertName = webhookCertName
		webhookServerOptions.KeyName = webhookCertKey
	}

	webhookServer := webhook.NewServer(webhookServerOptions)

	// Metrics 端点已在 'config/default/kustomization.yaml'. Metrics 选项用于配置服务器。
	// 更多信息:
	// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.25.0/pkg/metrics/server
	// - https://book.kubebuilder.io/reference/metrics.html
	metricsServerOptions := metricsserver.Options{
		BindAddress:   metricsAddr,
		SecureServing: secureMetrics,
		TLSOpts:       tlsOpts,
	}

	if secureMetrics {
		// FilterProvider 用于通过认证/鉴权保护 metrics 端点。
		// These configurations ensure that only authorized users and service accounts
		// can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info:
		// https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.25.0/pkg/metrics/filters#WithAuthenticationAndAuthorization
		metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
	}

	// 如果未指定证书,controller-runtime 将自动
	// 为指标服务器生成自签名证书。虽然对于开发和测试来说很方便,
	// 但这种设置不建议用于生产环境。
	//
	// TODO(用户):如果您启用 certManager,请取消注释以下行:
	// - [METRICS-WITH-CERTS] 在 config/default/kustomization.yaml 中生成并使用
	// 由 cert-manager 管理的指标服务器证书。
	// - [PROMETHEUS-WITH-CERTS] 在 config/prometheus/kustomization.yaml 中用于 TLS 认证。
	if len(metricsCertPath) > 0 {
		setupLog.Info("使用提供的证书初始化指标证书监视器",
			"metrics-cert-path", metricsCertPath, "metrics-cert-name", metricsCertName, "metrics-cert-key", metricsCertKey)

		metricsServerOptions.CertDir = metricsCertPath
		metricsServerOptions.CertName = metricsCertName
		metricsServerOptions.KeyName = metricsCertKey
	}

	mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
		Scheme:                 scheme,
		Metrics:                metricsServerOptions,
		WebhookServer:          webhookServer,
		HealthProbeBindAddress: probeAddr,
		LeaderElection:         enableLeaderElection,
		LeaderElectionID:       "4b13cc52.example.com",
		// LeaderElectionReleaseOnCancel 定义了当管理器结束时,领导者是否应自愿辞职
		// 当管理器停止时,这要求二进制文件立即结束,否则这个设置是不安全的。设置这个可以显著
		// 加快自愿领导者的过渡,因为新的领导者不必首先等待
		// LeaseDuration 时间。
		//
		// 在提供的默认脚手架中,程序会在
		// 管理器停止后立即结束,因此启用此选项是可以的。不过,
		// 如果您正在进行或打算在管理器停止后执行任何操作,如执行清理,
		// 那么使用它可能是不安全的。
		// LeaderElectionReleaseOnCancel: true,
	})
	if err != nil {
		setupLog.Error(err, "Failed to start manager")
		os.Exit(1)
	}

	if err := (&controller.MemcachedReconciler{
		Client: mgr.GetClient(),
		Scheme: mgr.GetScheme(),
	}).SetupWithManager(mgr); err != nil {
		setupLog.Error(err, "Failed to create controller", "controller", "memcached")
		os.Exit(1)
	}
	// +kubebuilder:scaffold:builder

	if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
		setupLog.Error(err, "Failed to set up health check")
		os.Exit(1)
	}
	if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
		setupLog.Error(err, "Failed to set up ready check")
		os.Exit(1)
	}

	setupLog.Info("Starting manager")
	if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
		setupLog.Error(err, "Failed to run manager")
		os.Exit(1)
	}
}

使用 Kubebuilder 插件脚手架附加选项

在更好理解如何创建自有 API 与控制器后,让我们在本项目中脚手架插件 autoupdate.kubebuilder.io/v1-alpha,以便项目能跟进最新 Kubebuilder 发行版的脚手架变更,从而采用生态中的改进。

kubebuilder edit --plugins="autoupdate/v1-alpha"

查看 .github/workflows/auto-update.yml 文件以了解其工作方式。

检查集群中运行的项目

此时,您可以通过查看快速入门中定义的步骤来检查在集群上验证项目的步骤,请参见:在集群上运行。

后续步骤

  • 若要更深入地开发解决方案,可继续阅读 CronJob 教程
  • 有关优化您方法的见解,请参阅最佳实践文档。