テックカリキュラム

Custom Controller(Operator)の設計 ── Kubernetesで独自リソースを自動制御する実践ガイド

Custom Controller(Operator)の設計 ── Kubernetesで独自リソースを自動制御する実践ガイド

はじめに

Kubernetesは標準リソース(Pod、Deploymentなど)だけでなく、独自のリソースを定義し、それを自動制御する仕組みを持っています。それがCustom Controller(Operator)です。

Operatorを使うことで、以下のような高度な運用自動化が可能になります:

  • データベースの自動構築・バックアップ
  • アプリケーションのライフサイクル管理
  • 障害時の自動復旧

本記事では、Operatorの設計思想から実装までを体系的に解説します。


1. Operatorとは何か?

Operatorとは、Kubernetesのコントローラーパターンを拡張し、特定のアプリケーションやシステムの運用知識をコード化したものです。

構成要素

  • CRD(Custom Resource Definition)
  • Custom Controller(Reconcile処理)

つまり:

Custom Resource(定義) ↓ Controller(監視・制御) ↓ 実際のリソース(Pod / Serviceなど)

2. CRDの設計

まずは独自リソースを定義します。

apiVersion: example.com/v1 kind: MyApp metadata: name: sample-app spec: replicas: 3 image: nginx:1.25 

CRD定義

apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: myapps.example.com spec: group: example.com names: kind: MyApp plural: myapps versions: - name: v1 served: true storage: true schema: openAPIV3Schema: type: object properties: spec: type: object properties: replicas: type: integer image: type: string 

3. Reconciliation Loop(中核ロジック)

Controllerは「望ましい状態」と「現在の状態」を比較し、差分を解消します。

Desired State(spec) vs Current State(cluster)

基本フロー

Watch Event ↓ Reconcile() ↓ 差分検出 ↓ リソース作成/更新/削除

4. Controller実装(Go / controller-runtime)

func (r *MyAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { var myapp examplev1.MyApp if err := r.Get(ctx, req.NamespacedName, &myapp); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } // Deployment生成 deployment := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: myapp.Name, }, Spec: appsv1.DeploymentSpec{ Replicas: &myapp.Spec.Replicas, }, } err := r.Create(ctx, deployment) return ctrl.Result{}, err }

この関数がOperatorの中核です。


5. WatchとEvent駆動

Controllerは以下を監視します:

  • Custom Resource(MyApp)
  • 関連リソース(Deploymentなど)
ctrl.NewControllerManagedBy(mgr). For(&examplev1.MyApp{}). Owns(&appsv1.Deployment{}). Complete(r)

6. 設計パターン(重要)

① Declarative設計

specにすべての状態を記述し、副作用を持たない設計にする

② Idempotency(冪等性)

何度Reconcileが実行されても同じ結果になる

③ Status管理

status: phase: Running readyReplicas: 3

現在の状態はstatusに書く


7. エラーハンドリングと再試行

return ctrl.Result{RequeueAfter: time.Minute}, err
  • エラー時は再試行
  • バックオフ戦略を活用

8. スケーラビリティ設計

  • WorkQueueで並列処理
  • Controllerのレプリカ分散(Leader Election)
mgr, err := ctrl.NewManager(cfg, ctrl.Options{ LeaderElection: true, })

9. セキュリティ設計(RBAC)

apiVersion: rbac.authorization.k8s.io/v1 kind: Role rules: - apiGroups: ["apps"] resources: ["deployments"] verbs: ["get","list","create","update","delete"]

最小権限を徹底します。


10. 実務での設計ベストプラクティス

  • CRDはシンプルに保つ
  • 外部依存(DBなど)は分離
  • ログとメトリクスを必ず出力
  • Prometheus連携を前提に設計

11. Operatorのユースケース

  • MySQL Operator
  • Kafka Operator
  • Redis Cluster管理
  • CI/CDパイプライン制御

まとめ

  • OperatorはKubernetesの拡張コントローラー
  • CRD + Reconcile Loopが中核
  • 冪等性・宣言的設計が重要
  • Controllerはイベント駆動で動作

Operatorを使いこなすことで、Kubernetesは単なるコンテナ基盤から自動化された運用プラットフォームへ進化します。