What Is Operator in Kubernetes: Simple Explanation and Example
Operator in Kubernetes is a method to automate managing complex applications by extending Kubernetes with custom logic. It acts like a smart controller that knows how to deploy, configure, and maintain an app using Custom Resources.How It Works
Think of an operator as a helpful robot inside Kubernetes that watches over a special kind of resource called a Custom Resource. This robot knows the rules and steps needed to keep an application running smoothly, like installing updates or fixing problems automatically.
Just like a thermostat controls your home's temperature by sensing changes and adjusting the heater or cooler, an operator watches the state of your app and makes changes to keep it healthy. It uses code to understand what "healthy" means and how to fix issues without you doing it manually.
Example
This example shows a simple custom resource definition (CRD) and a basic operator logic in Go that watches for changes and prints a message. It demonstrates how an operator can react to resource changes.
package main import ( "context" "fmt" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" "k8s.io/client-go/tools/clientcmd" ) func main() { // Load kubeconfig config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile) if err != nil { panic(err) } // Create dynamic client dynClient, err := dynamic.NewForConfig(config) if err != nil { panic(err) } // Define GVR for custom resource gvr := schema.GroupVersionResource{ Group: "example.com", Version: "v1", Resource: "foos", } // Watch for changes for { list, err := dynClient.Resource(gvr).Namespace("default").List(context.TODO(), metav1.ListOptions{}) if err != nil { panic(err) } fmt.Printf("Found %d Foo resources\n", len(list.Items)) time.Sleep(10 * time.Second) } }
When to Use
Use an operator when you want Kubernetes to manage complex applications that need special steps beyond simple deployment. For example, databases, caches, or monitoring tools often require setup, backups, scaling, and recovery that operators can automate.
Operators help reduce manual work, avoid mistakes, and keep apps running reliably by encoding expert knowledge into code that Kubernetes understands.
Key Points
- An operator extends Kubernetes with custom logic to manage apps.
- It uses custom resources to represent app-specific configurations.
- Operators automate tasks like deployment, scaling, and healing.
- They help keep complex apps running smoothly without manual intervention.