CRDs and operators

Kubernetes · lesson 25 of 32 · 4 min read

Teach the API server a new kind of object, then let a controller operate it for you.

Open this lesson in the learning hub

Key points

  • A CustomResourceDefinition adds a new kind to the API. After that kubectl get postgresclusters simply works.
  • A CRD alone is only validated storage. Nothing at all happens until some controller watches that kind.
  • An operator is that controller. It encodes the operational runbook: provision, back up, fail over, upgrade.
  • Its reconcile loop is level-triggered - it reads the whole desired state each pass, so a missed event is not a disaster.
  • Prefer a mature operator to a homegrown one for databases. Backups and failover are where all the real effort hides.
  • You already run custom resources: cert-manager Certificates, Argo CD Applications, Prometheus ServiceMonitors.

Example

# the operator ships the CRD; you only ever write the custom resource
apiVersion: postgres.acme.io/v1
kind: PostgresCluster
metadata:
  name: orders-db
spec:
  instances: 3
  version: "16"
  storage: 100Gi
  backup:
    schedule: "0 1 * * *"
    retentionDays: 14
---
# what the operator creates and keeps correct on your behalf:
#   StatefulSet orders-db          3 pods, one PVC each
#   Service     orders-db-primary  follows whichever pod is primary
#   Service     orders-db-replica  read-only endpoints
#   CronJob     orders-db-backup   nightly, retained 14 days
#
# kubectl get postgresclusters
# kubectl describe postgrescluster orders-db

A CRD is a new noun. The operator is the expert that keeps that noun true.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Kubernetes course, and every lesson in it is listed on the Kubernetes contents page.