Building Custom Kubernetes Controllers and Operators
Extend Kubernetes with custom controllers and operators to automate management of complex stateful applications beyond built-in workload types.
Custom controllers automate Kubernetes tasks that built-in controllers do not cover. A CRD defines the resource; a reconciler compares its desired state with the cluster and applies changes. Operators add application-specific procedures such as backups or failover. This guide covers controller-runtime setup, idempotent reconciliation, status, finalizers, retries, and tests against a real API server.
Building Custom Kubernetes Controllers and Operators
Kubernetes ships with built-in controllers for Deployments, StatefulSets, DaemonSets, and Jobs. These cover many use cases, but sometimes you need custom behavior. Maybe you want to manage a database that requires coordinated initialization, or an external service that needs lifecycle management. Custom controllers and operators let you extend Kubernetes to handle these scenarios.
This guide uses Kubernetes 1.37.1, controller-runtime v0.25.1, and the matching k8s.io/* v0.37.0 modules. It covers CRDs, reconciliation, status, cleanup, and testing. The version numbers are pinned because controller-runtime allows breaking changes between minor releases.
If you are new to Kubernetes, start with the Kubernetes fundamentals post. For core workload types, see the Kubernetes Workload Resources post.
Introduction
Custom controllers solve real problems, but they also add a service to operate. Before writing one, check whether a Deployment with the right configuration is enough. If it is, use that.
There are cases where a controller fits: a database that needs coordinated initialization, a certificate authority with renewal workflows, or a multi-tenant platform that creates isolated resources. Repeatedly using kubectl exec to manage state is a sign that some of the work may belong in a controller.
An operator is a controller that knows how to run a particular application. It can encode procedures such as database failover, schema migration, or backup retention that would otherwise live in runbooks.
When to skip them
Do not reach for a controller just because the pattern is interesting. A Deployment handles most stateless workloads. A Job or CronJob is simpler for scheduled or one-off work. If the task is only rendering a Helm template with fixed values, the controller adds complexity without much benefit.
The operational burden is real. Controllers run somewhere, need monitoring, can have bugs, and require updates when Kubernetes APIs change.
Before writing controller code, check whether simpler alternatives cover your use case:
| Use Case | Better Alternative |
|---|---|
| Run a batch job once | Job or CronJob |
| Manage a third-party Helm chart | Helm hooks or post-install scripts |
| Inject config into pods | ConfigMap/Secret with volume mounts |
| Liveness/readiness probes | Built-in probe handlers |
| Periodic maintenance tasks | CronJob with a dedicated ServiceAccount |
| One-time cluster setup | Init containers or Job |
If the controller would read one custom resource and write one ConfigMap, a mutating webhook or init container may be enough. A controller fits better when it manages related resources over time, recovers from failures, or maintains rules across objects.
If a Helm chart can do the whole job, use the chart.
Reconciliation Loop Flow
flowchart TD
A[Watch API Server<br/>for custom resource changes] --> B[Get current state<br/>of managed resources]
B --> C{Desired state<br/>== Current state?}
C -->|Yes| A
C -->|No| D[Reconcile:<br/>Create/Update/Delete]
D --> E[Update resource status<br/>and conditions]
E --> A
Controllers follow a declarative reconciliation loop: watch for changes, compare desired vs actual state, act to bring actual toward desired, update status, repeat.
Kubernetes Controller Pattern
A controller is a loop that watches the desired state and reconciles the actual state toward it. Kubernetes ships with many built-in controllers. The Deployment controller watches Deployments and creates ReplicaSets. The ReplicaSet controller creates Pods. The scheduler places Pods onto nodes. The kubelet on each node ensures containers are running.
The reconciliation loop follows this pattern:
watch(current_state) -> compare(desired, current) -> act(bring current to desired)
Controllers use the Kubernetes API to watch resources and create or modify other resources. If a Deployment requests 3 replicas, the controller ensures 3 pods exist. If a pod dies, the controller notices the difference and creates a replacement.
Custom Resources and CRDs
A Custom Resource Definition (CRD) extends the Kubernetes API with new resource types. Once you define a CRD, you can create instances of your custom resource just like built-in resources.
Defining a CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: databases.example.com
spec:
group: example.com
names:
kind: Database
plural: databases
shortNames:
- db
scope: Namespaced
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
engine:
type: string
enum: ["postgres"]
version:
type: string
replicas:
type: integer
minimum: 1
maximum: 5
required:
- engine
- version
- replicas
status:
type: object
properties:
observedGeneration:
type: integer
format: int64
externalID:
type: string
endpoint:
type: string
conditions:
type: array
x-kubernetes-list-type: map
x-kubernetes-list-map-keys:
- type
items:
type: object
required:
[
"type",
"status",
"reason",
"message",
"lastTransitionTime",
"observedGeneration",
]
properties:
type: { type: string }
status: { type: string }
reason: { type: string }
message: { type: string }
lastTransitionTime: { type: string, format: date-time }
observedGeneration: { type: integer, format: int64 }
subresources:
status: {}
After applying this CRD, you can create Database resources:
apiVersion: example.com/v1
kind: Database
metadata:
name: my-postgres
spec:
engine: postgres
version: "15"
replicas: 3
Without a controller, these resources sit idle. You need a controller to watch Database resources and do something with them.
Controller-Runtime Library
controller-runtime is the standard library for building Kubernetes controllers. It handles API client setup, informer caching, and reconciliation loops.
Project setup
The examples in this guide target Kubernetes 1.37.1 and Go 1.26.0. Upstream controller-runtime v0.25.1 declares k8s.io/apimachinery and k8s.io/client-go v0.37.0 in its go.mod; its compatibility table pairs controller-runtime v0.25 with the Kubernetes 0.37 modules. Pin these versions together, and check the upstream table when upgrading.
Start with a Kubebuilder scaffold or a similar project layout. A typical project keeps API types under api/, reconcilers under internal/controller/ or controllers/, and generated CRDs under config/crd/bases/.
mkdir my-operator && cd my-operator
go mod init my-operator
go get sigs.k8s.io/controller-runtime@v0.25.1
go get k8s.io/apimachinery@v0.37.0 k8s.io/client-go@v0.37.0
controller-runtime pulls in the manager, controller, reconcile, and source packages. You also need apimachinery for typed clients and client-go for Kubernetes resource types. After the setup commands, your go.mod will look something like this:
module my-operator
go 1.26.0
require (
sigs.k8s.io/controller-runtime v0.25.1
k8s.io/apimachinery v0.37.0
k8s.io/client-go v0.37.0
)
Use the scaffold’s make generate and make manifests targets after changing API types. They regenerate DeepCopy methods and CRD schemas. The Database status type used below has observedGeneration, conditions, and externalID fields, and its generated CRD enables the status subresource.
Most projects end up with this shape:
my-operator/
main.go # Manager setup and controller registration
go.mod
go.sum
api/
v1/
database_types.go # CRD type definitions
controllers/
database_controller.go # Reconcile implementation
config/
crd/
bases/
databases.example.com.yaml # Generated CRD manifest
The api/ directory is where your CRD types live. controllers/ is where the reconcile logic goes. Splitting them makes the project easier to test and maintain.
Manager and controller setup
package main
import (
"log"
ctrl "sigs.k8s.io/controller-runtime"
)
func main() {
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme, // Register the generated API and Kubernetes types.
LeaderElection: true,
LeaderElectionID: "database-controller.example.com",
})
if err != nil {
log.Fatal(err)
}
if err := (&DatabaseReconciler{
Client: mgr.GetClient(),
APIReader: mgr.GetAPIReader(),
Scheme: mgr.GetScheme(),
Remote: remoteClient,
}).SetupWithManager(mgr); err != nil {
log.Fatal(err)
}
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
log.Fatal(err)
}
}
This is manager wiring for a scaffolded project: scheme and remoteClient come from that project’s API registration and external-service setup. A reconciler can register its primary resource and the child resources it owns with the builder:
func (r *DatabaseReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&examplev1.Database{}).
Owns(&corev1.ConfigMap{}).
Complete(r)
}
Reconciliation loops and idempotency
A reconcile request is a reminder to inspect current state. It is not a durable event describing one specific change. The reconciler reads the resource again, compares the desired and actual state, then applies only the changes it owns. The same request may run more than once, so every operation needs to tolerate retries.
Reconcile path
The snippets below are API-level examples for a Kubebuilder-style project, not a standalone package. They assume a generated Database type with Spec.Engine, Spec.Version, and Spec.Replicas, plus status fields for ObservedGeneration, Conditions, and ExternalID. The imports are omitted here; the controller-runtime methods shown target v0.25.1.
const databaseFinalizer = "database.example.com/finalizer"
type DatabaseReconciler struct {
client.Client
APIReader client.Reader // Uncached reads for conflict retries.
Scheme *runtime.Scheme
Remote RemoteService
}
type RemoteService interface {
// EnsureDatabase must upsert by UID, not create a new database on every call.
EnsureDatabase(ctx context.Context, uid types.UID, spec examplev1.DatabaseSpec) (RemoteDatabase, error)
// Deleting an absent remote database must return nil.
DeleteDatabase(ctx context.Context, externalID string) error
}
type RemoteDatabase struct {
ID string
Endpoint string
}
func (r *DatabaseReconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
db := &examplev1.Database{}
if err := r.Get(ctx, req.NamespacedName, db); err != nil {
// A deleted object with no finalizer is normal; there is nothing left to do.
return reconcile.Result{}, client.IgnoreNotFound(err)
}
if !db.DeletionTimestamp.IsZero() {
return r.finalize(ctx, db)
}
if !controllerutil.ContainsFinalizer(db, databaseFinalizer) {
controllerutil.AddFinalizer(db, databaseFinalizer)
if err := r.Update(ctx, db); err != nil {
return reconcile.Result{}, err
}
// Persist the finalizer before creating anything that needs cleanup.
return reconcile.Result{}, nil
}
callCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
remote, err := r.Remote.EnsureDatabase(callCtx, db.UID, db.Spec)
cancel()
if err != nil {
return r.fail(ctx, db, "ExternalServiceFailed", err)
}
provisionedCondition := metav1.Condition{
Type: "Ready", Status: metav1.ConditionUnknown,
Reason: "ExternalDatabaseProvisioned",
Message: "External database is provisioned; applying connection config.",
ObservedGeneration: db.Generation, LastTransitionTime: metav1.Now(),
}
if err := r.writeStatus(ctx, req.NamespacedName, db.Generation, remote.ID, provisionedCondition); err != nil {
return reconcile.Result{}, err
}
if err := r.ensureConnectionConfig(ctx, db, remote.Endpoint); err != nil {
return r.fail(ctx, db, "ConnectionConfigFailed", err)
}
condition := metav1.Condition{
Type: "Ready", Status: metav1.ConditionTrue,
Reason: "ReconciliationComplete", Message: "Database resources are ready.",
ObservedGeneration: db.Generation, LastTransitionTime: metav1.Now(),
}
if err := r.writeStatus(ctx, req.NamespacedName, db.Generation, remote.ID, condition); err != nil {
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
This example provisions a managed database outside the cluster and publishes its endpoint in a ConfigMap. The ConfigMap is owned by the custom resource, so Kubernetes garbage-collects it when the resource is deleted. The finalizer below handles the remote database, which Kubernetes cannot remove itself.
CreateOrUpdate handles the GET/create/update path. Its mutate function sets the owner reference and only the fields this controller owns. Do not replace whole child objects from a hand-built struct on every pass; API defaults and fields owned by another controller can be lost or cause a stream of updates. If two reconciliations race to create the same object, let the resulting conflict or AlreadyExists error go back to the work queue.
func (r *DatabaseReconciler) ensureConnectionConfig(
ctx context.Context,
db *examplev1.Database,
endpoint string,
) error {
config := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{Name: db.Name + "-connection", Namespace: db.Namespace},
}
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, config, func() error {
if err := controllerutil.SetControllerReference(db, config, r.Scheme); err != nil {
return err
}
config.Labels = map[string]string{"app.kubernetes.io/managed-by": "database-operator"}
config.Data = map[string]string{"endpoint": endpoint}
return nil
})
return err
}
func (r *DatabaseReconciler) fail(
ctx context.Context,
db *examplev1.Database,
reason string,
cause error,
) (reconcile.Result, error) {
log.FromContext(ctx).Error(cause, "database reconciliation failed", "name", db.Name, "namespace", db.Namespace)
condition := metav1.Condition{
Type: "Ready", Status: metav1.ConditionFalse,
Reason: reason, Message: "Reconciliation failed; check controller logs.",
ObservedGeneration: db.Generation, LastTransitionTime: metav1.Now(),
}
// An empty external ID preserves the ID persisted before later reconcile steps.
statusErr := r.writeStatus(ctx, types.NamespacedName{Namespace: db.Namespace, Name: db.Name}, db.Generation, "", condition)
return reconcile.Result{}, errors.Join(cause, statusErr)
}
Status and conflicts
Store conditions and the generation they describe. observedGeneration tells a reader whether Ready=True applies to the current spec or to an earlier one. Refresh the object from the API server for each conflict retry, then write through the status subresource:
func (r *DatabaseReconciler) writeStatus(
ctx context.Context,
key types.NamespacedName,
generation int64,
externalID string,
condition metav1.Condition,
) error {
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
current := &examplev1.Database{}
if err := r.APIReader.Get(ctx, key, current); err != nil {
return client.IgnoreNotFound(err)
}
if current.Generation != generation {
// A newer spec arrived while this reconcile was running.
return nil
}
before := current.DeepCopy()
current.Status.ObservedGeneration = generation
if externalID != "" {
current.Status.ExternalID = externalID
}
meta.SetStatusCondition(¤t.Status.Conditions, condition)
if equality.Semantic.DeepEqual(before.Status, current.Status) {
return nil
}
return r.Client.Status().Update(ctx, current)
})
}
The fresh read supplies the resource version used by Status().Update; if another writer wins first, RetryOnConflict reads again and reapplies the condition to the latest object. Use the status subresource so a status write cannot replace spec. Skip the update when the status did not change, or the status write itself can trigger more reconciliations.
On a failure, set Ready=False with a useful reason, set observedGeneration to the generation you tried, and return the original error. Avoid putting credentials or raw provider responses in condition messages. A condition describes the last attempt; it does not replace logs or metrics.
External calls must also be idempotent
For an external service, derive a stable idempotency key from the Kubernetes object’s UID. Make an upsert with that key, and persist the returned external ID in status. Repeated calls then find or update the same remote object instead of creating duplicates. A delete operation should treat “already absent” as success. Put a deadline on each external request and make cleanup safe to retry.
The controller can still crash after the remote service accepts a request but before status is written. That is why the UID-based key matters: the next reconcile can repeat the request safely and recover the same external ID.
Operator pattern for stateful apps
An operator combines a controller with knowledge of one application’s lifecycle. For a database, that might include provisioning a cloud instance, rotating credentials, running an upgrade, and cleaning up the instance. Keep each step in an idempotent helper so a failed reconcile can resume safely.
For Kubernetes children, use controllerutil.CreateOrUpdate and set an owner reference with controllerutil.SetControllerReference. For external resources, use an upsert keyed by the parent UID. Owner references only apply to Kubernetes objects; they cannot remove a cloud database or another resource outside the cluster.
Client-Go Basics
client-go is the Go client library for Kubernetes. controller-runtime uses client-go under the hood, but you may need client-go directly for more control or for operators not using controller-runtime.
Direct client usage
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
kubeconfig := os.Getenv("KUBECONFIG")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
// List pods
pods, err := clientset.CoreV1().Pods("default").List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}
for _, pod := range pods.Items {
fmt.Printf("Pod: %s\n", pod.Name)
}
}
client-go provides typed clients for all Kubernetes resource types. The clientset.CoreV1().Pods() returns an interface for pod operations.
Choosing Your Approach: Trade-off Comparison
| Approach | Control | Complexity | Best For |
|---|---|---|---|
| controller-runtime | Medium | Low-Medium | Most custom controllers, standard reconciliation |
| client-go directly | High | High | Very specific needs, learning K8s internals |
| Operator SDK | Medium | Medium | Production operators with OLM packaging |
| Kubebuilder | Medium | Medium | controller-runtime projects with best practices |
controller-runtime is the default choice for most controllers. It handles caching, watching, and retry logic that you would otherwise have to write yourself. client-go directly gives you more control but more boilerplate. Operator SDK adds scaffolding on top of controller-runtime for production operators.
Production Failure Scenarios
Reconciliation Loop Falling Behind
Under heavy cluster load, the controller can fall behind its watch on the API server. This means spec changes take longer to propagate to actual resources.
The tell is resources converging slowly after a change, sometimes several minutes. You might also see the controller pod consuming more CPU than usual.
Fix this by watching your controller queue depth. If it is growing, increase worker counts or add indexing for large clusters.
API Server Timeout During Reconciliation
Network blips or API server overload cause reconciliation operations to time out. The error message is context deadline exceeded.
This can leave resources partially updated. A pod might exist but not have its final labels set. A StatefulSet might have the wrong replica count but no init containers configured. The controller moves on without ensuring the resource reached its desired state, and the next reconciliation event might be minutes away.
Use exponential backoff on retry. Start with a 1-second delay, double on each failure, cap at 5 minutes. When reconciliation finally succeeds, reset the delay to the initial interval. This gives the API server time to recover without adding load during an already-stressed period.
You can detect timeout-related partial updates by watching the controller’s error rate. A spike in context deadline exceeded errors usually means the API server is under pressure, and your controller’s retries are contributing to that pressure. If you see multiple controllers timing out simultaneously, the problem is likely the API server itself, not your controller.
The partial state problem slips through without custom metrics. Your controller marks a resource as reconciled even when it failed partway through. The fix is a status condition: type: Reconciled, status: True, reason: ReconciliationComplete when done, status: False, reason: ReconciliationFailed on timeout. Without this, users see their resource as healthy when it is actually not.
Leader Election Failures
In HA setups with multiple controller replicas, leader election failures cause two controllers to think they are both in charge. Both then try to manage the same resources.
The symptom is duplicate resources or conflicting updates appearing in quick succession.
controller-runtime has built-in leader election. Make sure your lease duration is long enough for your typical restart time.
Anti-Patterns
Ignoring Deletion
If your reconcile only handles creates and updates, deleted custom resources leave their child resources behind. The controller never cleans up.
Add the finalizer before allocating anything that needs cleanup. When deletion starts, Kubernetes sets .metadata.deletionTimestamp and keeps the object until its finalizers are removed. If the reconciler gets a request for an object that is already gone, client.IgnoreNotFound handles it. Owner references can clean up Kubernetes children; a finalizer is needed for work such as deleting an external database.
The usual delete flow is:
1. User deletes Database resource
2. Kubernetes sets .metadata.deletionTimestamp
3. Controller reconcile sees the timestamp is set
4. Controller idempotently deletes the external database
5. Controller removes its finalizer from the Database
6. Kubernetes deletes the Database resource
The finalizer itself is a deletion barrier, so set a timeout policy. This example limits each provider request to two minutes, retries cleanup every 30 seconds, and releases the finalizer after 24 hours if cleanup still fails. That bounds how long the object can remain in Terminating, but it can leave a remote database behind. Tag external resources with the Kubernetes UID, emit an alert containing the UID and external ID when the deadline expires, and put the resource in a durable cleanup queue or runbook. The delete operation must treat an already-absent external resource as success.
func (r *DatabaseReconciler) finalize(
ctx context.Context,
db *examplev1.Database,
) (reconcile.Result, error) {
if !controllerutil.ContainsFinalizer(db, databaseFinalizer) {
return reconcile.Result{}, nil
}
key := types.NamespacedName{Namespace: db.Namespace, Name: db.Name}
callCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
cleanupErr := r.Remote.DeleteDatabase(callCtx, db.Status.ExternalID)
cancel()
if cleanupErr != nil && time.Since(db.DeletionTimestamp.Time) < 24*time.Hour {
condition := metav1.Condition{
Type: "Ready", Status: metav1.ConditionFalse,
Reason: "CleanupPending", Message: "External cleanup is still being retried.",
ObservedGeneration: db.Generation, LastTransitionTime: metav1.Now(),
}
statusErr := r.writeStatus(ctx, key, db.Generation, db.Status.ExternalID, condition)
if statusErr != nil {
return reconcile.Result{}, errors.Join(cleanupErr, statusErr)
}
return reconcile.Result{RequeueAfter: 30 * time.Second}, nil
}
if cleanupErr != nil {
// This bounded-delete policy accepts a possible remote orphan after 24h.
log.FromContext(ctx).Error(cleanupErr, "cleanup timed out; releasing finalizer",
"uid", db.UID, "externalID", db.Status.ExternalID)
condition := metav1.Condition{
Type: "Ready", Status: metav1.ConditionFalse,
Reason: "CleanupTimedOut", Message: "Finalizer deadline expired; check the cleanup alert.",
ObservedGeneration: db.Generation, LastTransitionTime: metav1.Now(),
}
if err := r.writeStatus(ctx, key, db.Generation, db.Status.ExternalID, condition); err != nil {
return reconcile.Result{}, err
}
}
if err := r.removeFinalizer(ctx, key); err != nil {
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
func (r *DatabaseReconciler) removeFinalizer(ctx context.Context, key types.NamespacedName) error {
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
current := &examplev1.Database{}
if err := r.APIReader.Get(ctx, key, current); err != nil {
return client.IgnoreNotFound(err)
}
if !controllerutil.ContainsFinalizer(current, databaseFinalizer) {
return nil
}
controllerutil.RemoveFinalizer(current, databaseFinalizer)
return r.Client.Update(ctx, current)
})
}
The timeout is a policy choice, not a guarantee that remote cleanup succeeded. If your data policy forbids orphans, do not auto-release the finalizer: alert an operator and keep retrying until cleanup succeeds. For an operator uninstall, stop accepting new custom resources, delete existing Database resources, and keep the controller and CRD installed until cleanup finishes or the bounded recovery procedure has run. Inspect the finalizer and the tagged external resource before any manual force-removal; removing a finalizer blindly can leak data or infrastructure.
Skipping Status Updates
Your users have no idea what the controller actually did. Did it create the StatefulSet? Is it still trying? Did it fail?
Use .status to report what the controller knows, and write it when that state changes. Conditions give users a useful answer without turning the status subresource into another source of reconcile events.
The API should enable the status subresource and define observedGeneration and a list of conditions. Set observedGeneration to the spec generation your reconcile actually handled. Use Status().Update or a status patch; the earlier writeStatus helper shows a conflict retry that refreshes from the API server before writing. Avoid unconditional updates when the condition is unchanged.
Missing Exponential Backoff
When a reconcile returns an error, controller-runtime’s work queue rate-limits the retry with its default backoff. Return the error for transient API or provider failures and let that retry policy apply:
return reconcile.Result{}, err
Use RequeueAfter when you know the next check should happen after a fixed interval, such as polling a long-running operation or retrying deletion at a measured cadence. Do not return both an error and RequeueAfter; choose one retry path. For invalid input, set a false condition and return no error so a later spec update can trigger another reconcile. Keep provider calls bounded with a context deadline.
Security Checklist
RBAC for Controllers
Controllers need permissions to manage the resources they watch. Apply least privilege:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: database-controller-role
rules:
- apiGroups: ["example.com"]
resources: ["databases"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: ["apps"]
resources: ["statefulsets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["services"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
Never give a controller cluster-admin. If your controller only manages resources in one namespace, use a Role and RoleBinding instead of ClusterRole and ClusterRoleBinding.
Service Account for the Controller
Run your controller with a dedicated ServiceAccount:
apiVersion: v1
kind: ServiceAccount
metadata:
name: database-controller-sa
namespace: controllers
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: database-controller-rolebinding
namespace: controllers
subjects:
- kind: ServiceAccount
name: database-controller-sa
namespace: controllers
roleRef:
kind: ClusterRole
name: database-controller-role
apiGroup: rbac.authorization.k8s.io
Mount the token inside the controller pod and configure kubeconfig to use it automatically via MountableSecrets.
General Security Practices
These practices cover the runtime and supply chain dimension of controller security.
- Run controllers in a dedicated namespace, isolated from application workloads
- Do not let controllers manage their own deployment (circular dependency risk)
- Use
readOnlyRootFilesystem: truein the controller pod security context where possible - Enable RBAC audit logging to track controller permission usage
- Do not embed credentials in controller code — use ServiceAccounts or external secrets solutions
Pod security context. Controllers rarely need to write to the filesystem or open arbitrary ports. Lock them down:
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
Network policies. If your controller talks to external services, restrict egress. Kubernetes network policies default to allow-all within a namespace, so you must explicitly block outbound traffic from the controller namespace.
Image provenance. Build your controller image from a minimal base, sign it with Cosign or similar, and enforce image verification in your admission control pipeline. A compromised controller image essentially has cluster-admin access.
Controller updates. When you update a controller, the old version keeps reconciling until the new version is ready. During the transition window, both versions run simultaneously. Design your CRD schema to be backward-compatible across at least two controller versions, or use a conversion webhook to handle schema changes.
Testing Strategies
Unit Tests
Use the fake client for fast checks of reconciliation decisions. It does not reproduce every API-server behavior, so keep the test’s scope narrow and use envtest for status subresources, validation, resource versions, and admission behavior.
// Test sketch; imports and the fake RemoteService are omitted.
func TestReconcileIsIdempotent(t *testing.T) {
scheme := runtime.NewScheme()
require.NoError(t, examplev1.AddToScheme(scheme))
require.NoError(t, corev1.AddToScheme(scheme))
db := &examplev1.Database{
ObjectMeta: metav1.ObjectMeta{
Name: "test-db", Namespace: "default", UID: "test-db-uid",
Finalizers: []string{databaseFinalizer},
},
Spec: examplev1.DatabaseSpec{Engine: "postgres", Version: "17", Replicas: 1},
}
cl := fake.NewClientBuilder().
WithScheme(scheme).
WithStatusSubresource(&examplev1.Database{}).
WithObjects(db).
Build()
r := &DatabaseReconciler{
Client: cl, APIReader: cl, Scheme: scheme,
Remote: newIdempotentRemoteFake(),
}
req := reconcile.Request{
NamespacedName: types.NamespacedName{Namespace: "default", Name: "test-db"},
}
for range 2 {
_, err := r.Reconcile(context.Background(), req)
require.NoError(t, err)
}
config := &corev1.ConfigMap{}
require.NoError(t, cl.Get(context.Background(), types.NamespacedName{
Namespace: "default", Name: "test-db-connection",
}, config))
require.Equal(t, "db.example.net:5432", config.Data["endpoint"])
}
The important assertions are that repeated reconcile calls keep one child object, preserve its endpoint data, and call the remote API with the same UID key. Add cases for a missing parent, an external API error, an update to the spec, and a delete request.
Integration Tests
envtest starts etcd and a Kubernetes API server. It does not start kubelet, kube-controller-manager, or garbage collection controllers. Use it to check the real API behavior your reconciler depends on, then cover cluster-only behavior in a disposable Kubernetes cluster.
func TestReconcileAgainstAPIServer(t *testing.T) {
testEnv := &envtest.Environment{
CRDDirectoryPaths: []string{"../config/crd/bases"},
}
cfg, err := testEnv.Start()
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, testEnv.Stop()) })
cl, err := client.New(cfg, client.Options{Scheme: scheme})
require.NoError(t, err)
// Create a Database, reconcile twice, then verify its status subresource,
// ConfigMap owner reference, generation, and remote idempotency key.
// Also exercise a conflicting status update and deletion/finalizer path.
}
The test should load the generated CRD, create a Database, run the reconciler, and assert that Ready describes the current generation. Run separate cases for server-side schema rejection, a stale status write, cleanup returning success for an absent remote object, and the 24-hour timeout policy. Use an injectable clock if you test the deadline rather than waiting a day.
Set up envtest with the same Kubernetes API version as the target cluster. For this example, pin its API server binaries to 1.37.1:
make manifests generate
./bin/setup-envtest use 1.37.1 --bin-dir ./bin -p path
KUBEBUILDER_ASSETS="$(./bin/setup-envtest use 1.37.1 --bin-dir ./bin -p path)" go test ./...
Before deployment, check that Go resolved the intended module set and validate the CRD against a Kubernetes 1.37.1 API server:
go list -m -f '{{.Path}} {{.Version}}' \
sigs.k8s.io/controller-runtime k8s.io/api k8s.io/apimachinery k8s.io/client-go
# Expected: controller-runtime v0.25.1; k8s.io/* modules v0.37.0
kubectl apply --dry-run=server -f config/crd/bases/
Run the server-side check against a disposable 1.37.1 cluster, not against a local client version alone. On a staging cluster, also create a sample resource, wait for status.observedGeneration to match metadata.generation, then delete it and confirm the finalizer completes or follows the documented timeout path. Upstream’s envtest guide explains how to install and select the API server binaries; its environment does not test built-in garbage collection.
Advanced Scenarios
Leader Election
For multiple replicas, enable leader election in the manager options, as shown in the setup example. Give each independent controller deployment a unique LeaderElectionID, and grant its ServiceAccount permission to manage the lease. Set lease timings from observed failover behavior rather than copying example numbers.
Finalizers
Use the deletion flow and bounded cleanup policy shown above. Finalizers only work while a controller that understands them is running, so uninstall the controller after its custom resources have been cleaned up.
Owner References and Garbage Collection
Owner references connect an in-cluster child to its parent. Use controllerutil.SetControllerReference when creating or updating a child, and let Kubernetes garbage collection remove it after the owner is deleted:
if err := controllerutil.SetControllerReference(db, configMap, r.Scheme); err != nil {
return err
}
Owner references apply to Kubernetes objects in the same namespace or cluster scope as permitted by Kubernetes. They do not clean up external services. Use a finalizer for those, and do not assume garbage collection has finished before the parent disappears.
Interview Questions
A reconcile request is a prompt to read current state again. An idempotent reconciler can run repeatedly without creating duplicates or changing already-correct resources.
Kubernetes 1.37.1 with controller-runtime v0.25.1 and `k8s.io/*` v0.37.0. The upstream compatibility table pairs the v0.25 controller-runtime line with Kubernetes library v0.37.
A CRD registers a new resource kind and its schema with the API server. Users can then create instances with normal Kubernetes API tools. A controller watches those instances and acts on them.
A controller implements reconciliation. An operator is a controller that also knows application procedures such as backups, upgrades, or failover.
Use one when deletion requires controller work that Kubernetes cannot do, such as removing a cloud database. Add the finalizer before provisioning. Set a cleanup deadline and an explicit recovery policy so an unreachable provider cannot leave the object terminating forever.
They link an in-cluster child to its parent so Kubernetes garbage collection can remove the child. They do not clean up external resources, and they do not guarantee child deletion has finished before the parent disappears.
The fake client is useful for fast unit tests, but it does not reproduce all API-server behavior. Envtest runs etcd and an API server, so it can exercise CRD validation, status writes, and resource-version conflicts. It does not run built-in controllers or garbage collection.
Read the latest object, set `status.observedGeneration` and the condition, then update the status subresource. On a conflict, read again and reapply the status change to the newer object.
Return the error and let controller-runtime's work queue apply its rate-limited retry. Use `RequeueAfter` for a known polling interval. Make side effects idempotent so the next pass can safely resume.
It elects one active manager among replicas that share a lease identity. Enable it in manager options, set a unique `LeaderElectionID`, and grant the ServiceAccount access to the lease resource.
Give it only the verbs and resources it needs. Use a namespace Role when its scope is namespaced, and a dedicated ServiceAccount for the controller pod.
Controller-runtime supplies the manager, cache, watches, and reconcile queue for the usual controller pattern. client-go is a better fit when an application needs its lower-level clients or does not use that pattern.
Regenerate manifests, run envtest with API server 1.37.1, check that controller-runtime and `k8s.io/*` modules match the pinned versions, and run a server-side dry run of the CRD on a disposable 1.37.1 cluster.
Quick Recap Checklist
- Defined CRDs for your domain resources
- Reconciliation loop follows watch -> compare -> act
- Finalizers handle deletion of dependent resources
- Reconciliation is idempotent (calling it N times = once)
- Owner references link child resources for garbage collection
- Leader election set up for HA deployments
- Exponential backoff on reconciliation failures
- Status conditions reflect actual state
- Tested with simulated API server timeouts
- Controller queue depth monitored
Further Reading
Official Documentation
- Custom Resources Documentation — Official CRD documentation
- Controller Runtime — The standard library for building Kubernetes controllers
- Operator SDK — Framework for building production operators
- RBAC Documentation — Role-based access control reference
Articles and Guides
- Building Operators with Operator SDK — Official guide to operator development
- Writing a Kubernetes Controller in Go — Practical controller development walkthrough
- Kubebuilder Book — Framework for building Kubernetes APIs and controllers
Conclusion
Custom controllers extend Kubernetes beyond built-in workload types. CRDs define new resource types. Controllers watch those resources and reconcile actual state toward desired state. Operators encode domain knowledge to handle application-specific lifecycle management.
controller-runtime simplifies controller development by handling caching, API watching, and reconciliation loops. client-go provides the underlying client functionality for direct Kubernetes API access.
Building operators requires understanding of the controller pattern, Go, and Kubernetes internals. For teams running complex stateful applications on Kubernetes, custom operators can automate operational tasks that would otherwise require manual intervention.
For more advanced Kubernetes topics, see the Advanced Kubernetes post.
Category
Related Posts
Container Security: Image Scanning and Vulnerability Risks
Implement comprehensive container security: from scanning images for vulnerabilities to runtime security monitoring and secrets protection.
Deployment Strategies: Rolling, Blue-Green, Canary
Compare and implement deployment strategies—rolling updates, blue-green deployments, and canary releases—to reduce risk and enable safe production releases.
Developing Helm Charts: Templates, Values, and Testing
Create production-ready Helm charts with Go templates, custom value schemas, and testing using Helm unittest and ct.