What are operators in Kubernetes and what pattern do they use?
sobes.tech AI
Answer from AI
Operators are methods of packaging, deploying, and managing applications on Kubernetes. They extend the functionality of the Kubernetes API, acting as controllers specific to particular software.
The main pattern used by operators is the Controller pattern. A controller in Kubernetes continuously monitors the current state of the cluster and compares it with the desired state. If the states differ, the controller takes necessary actions to bring the current state in line with the desired state.
In the case of operators, they automate operational tasks that are usually performed by humans: backup, update, scaling, managing the lifecycle of specific applications and their dependencies. They do this by reacting to events in the cluster and manipulating custom resources (Custom Resources - CR) and custom resource definitions (Custom Resource Definitions - CRD), which extend the Kubernetes API.
Working principle:
- Definition of Custom Resource (CRD): A new resource type is defined to represent an application or service.
- Creation of Custom Resource (CR): The user creates an instance of this new resource, describing the desired state of the application.
- Operator as a controller: The operator constantly monitors the creation, update, and deletion of CRs of this type.
- Comparison of states: The operator compares the current state of the application (e.g., number of running pods, software version, configuration) with the desired state described in the CR.
- Execution of actions: If the states differ, the operator performs necessary actions through the standard Kubernetes API (creating/updating/deleting Deployment, StatefulSet, Service, PVC, etc.) to bring the current state to the desired one.
Example: A PostgreSQL database operator can provide a CR PostgresqlDatabase. The user creates such a CR with the desired version, storage size, and replication settings. The PostgreSQL operator, observing this CR, will create the necessary StatefulSet, PersistentVolumeClaim, Service, and configure replication, ensuring the achievement and maintenance of the desired state.
# Example of a Custom Resource for a hypothetical PostgreSQL Operator
apiVersion: postgresql.database.example.com/v1
kind: PostgresqlDatabase
metadata:
name: my-prod-db
spec:
version: "14.5"
storageSize: "100Gi"
replicas: 3
backup:
enabled: true
schedule: "0 2 * * *"
Thus, operators encapsulate deep operational knowledge about a specific application into code that runs on Kubernetes, automating routine tasks and increasing the reliability and scalability of deployments.