Kubernetes operators in Java with Spring Boot
An operator is a program that keeps something in a Kubernetes cluster the way a custom resource describes it, by comparing what should exist with what does and fixing the difference, over and over. This page explains that reconcile loop, runs a model of it and the health probes an operator pod needs, and shows the Java Operator SDK code for a Spring Boot 4 operator.
Contents
What an operator is
Kubernetes manages built-in resources such as Deployments and Services with controllers: programs that watch a kind of resource and make the cluster match what it describes. A Deployment says "three pods of this image", and its controller creates, replaces or deletes pods until that is true. An operator applies the same pattern to your own kind of resource. You define a custom resource, for example a ShopShop
The heart of every operator is the reconcile loop, and three properties make it robust:
- Level-triggered: the reconciler is told only "this resource may need attention". It then reads the complete current state and works out what to do, instead of acting on what an event said changed. A missed or repeated event therefore does no harm.
- Idempotent: running the reconciler twice on the same state does nothing the second time. Kubernetes and the operator framework both deliver events more than once, and resynchronise periodically.
- Status reporting: the reconciler writes what it observed to the resource's
, includingstatus , so users and tools can tell whether the latest spec has been applied.observedGeneration
| Piece | Provided by | Role |
|---|---|---|
| Custom resource definition (CRD) | YAML, generated from a Java class | Registers the new resource kind with the API server |
| Custom resource class | fabric8 Kubernetes client 7 | Java type with specstatus |
Reconciler | Java Operator SDK 5 | Your reconcile logic, called on every relevant event |
Dependent resources and @Workflow | Java Operator SDK 5 | Declarative management of the resources an operator owns |
| Spring Boot starter | operator-framework-spring-boot-starter | Registers reconciler beans, configures the client, starts the operator |
| Probes and metrics | Spring Boot Actuator | Liveness, readiness and metrics for the operator's own pod |
The Java Operator SDK (JOSDK) is a CNCF project from the Operator Framework. Its Spring Boot starter 6.6 is built on Spring Boot 4.1, JOSDK 5.5 and the fabric8 client 7.8, according to its parent POM. No Kubernetes cluster and none of these libraries are available where this page was built, so the JOSDK examples are marked as not run; they were checked against the JOSDK documentation. The two programs shown running are a plain-Java model of the reconcile logic and the Spring Boot health probes that the operator's pod uses.
The reconcile loop, modelled
The reconcile logic decides everything else, and it can be written and tested as plain Java. This model keeps the "cluster" in a map and reconciles a Shop
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
// A plain-Java model of a reconciler: compare desired state with actual state and act on
// the difference. It is NOT the Kubernetes API; it shows the logic an operator implements.
public class ReconcileModel {
record Spec(String image, int replicas) {
}
record Deployment(String name, String image, int replicas) {
}
// what the cluster holds: deployments by name, as the API server would return them
static final Map<String, Deployment> cluster = new TreeMap<>();
static long generation = 1; // metadata.generation: bumped on every spec change
static long observedGeneration; // status.observedGeneration: written by the operator
// the reconciler: reads the WHOLE current state every time, never the event's delta
static List<String> reconcile(String name, Spec spec) {
List<String> actions = new ArrayList<>();
Deployment desired = new Deployment(name + "-web", spec.image(), spec.replicas());
Deployment actual = cluster.get(desired.name());
if (actual == null) {
cluster.put(desired.name(), desired);
actions.add("create " + desired);
} else if (!Objects.equals(actual, desired)) {
cluster.put(desired.name(), desired);
actions.add("update " + actual + " -> " + desired);
}
observedGeneration = generation;
return actions.isEmpty() ? List.of("nothing to do") : actions;
}
static void run(String why, String name, Spec spec) {
System.out.println(why);
reconcile(name, spec).forEach(a -> System.out.println(" " + a));
System.out.println(" status: observedGeneration " + observedGeneration
+ " of generation " + generation);
}
public static void main(String[] args) {
Spec spec = new Spec("shop:1.4", 2);
run("1. custom resource created", "shop", spec);
run("2. same event delivered again (or a periodic resync)", "shop", spec);
spec = new Spec("shop:1.5", 3);
generation++;
System.out.println("3. spec changed: generation " + generation
+ ", observedGeneration still " + observedGeneration + " until reconciled");
run(" reconcile", "shop", spec);
cluster.put("shop-web", new Deployment("shop-web", "shop:1.5", 1));
run("4. someone scaled the deployment to 1 by hand (drift)", "shop", spec);
cluster.remove("shop-web");
run("5. someone deleted the deployment", "shop", spec);
}
}
1. custom resource created
create Deployment[name=shop-web, image=shop:1.4, replicas=2]
status: observedGeneration 1 of generation 1
2. same event delivered again (or a periodic resync)
nothing to do
status: observedGeneration 1 of generation 1
3. spec changed: generation 2, observedGeneration still 1 until reconciled
reconcile
update Deployment[name=shop-web, image=shop:1.4, replicas=2] -> Deployment[name=shop-web, image=shop:1.5, replicas=3]
status: observedGeneration 2 of generation 2
4. someone scaled the deployment to 1 by hand (drift)
update Deployment[name=shop-web, image=shop:1.5, replicas=1] -> Deployment[name=shop-web, image=shop:1.5, replicas=3]
status: observedGeneration 2 of generation 2
5. someone deleted the deployment
create Deployment[name=shop-web, image=shop:1.5, replicas=3]
status: observedGeneration 2 of generation 2
- Step 1: no Deployment existed, so the reconciler created
with 2 replicas ofshop-web and recordedshop:1.4 .observedGeneration 1 - Step 2: the same input again found the Deployment already right and did nothing. This is the idempotence that makes repeated events and periodic resyncs safe.
- Step 3: the spec change raised
to 2, which Kubernetes does on every spec change. Until the reconcile ran,metadata.generation was still 1, which is how a client knows the change is not applied yet. Afterwards both were 2.observedGeneration - Step 4: someone scaled the Deployment to 1 by hand. The reconciler did not need an event describing that change; it compared the whole desired state with the whole actual state and set the replicas back to 3.
- Step 5: the Deployment was deleted, and the next reconcile simply created it again.
Steps 4 and 5 are why level-triggered design matters. An operator that only reacted to "spec changed" events would never notice drift. In a real operator, the framework triggers a reconcile when the custom resource changes, when an owned resource such as the Deployment changes, and at a regular interval, and the reconciler always does the same comparison.
The custom resource (not run)
The resource kind is a Java class extending fabric8's CustomResource
@Group("shop.example.com")
@Version("v1")
public class Shop extends CustomResource<ShopSpec, ShopStatus> implements Namespaced {
}
public class ShopSpec {
private String image;
private int replicas = 1;
// getters and setters
}
public class ShopStatus {
private long observedGeneration;
private String phase; // for example Ready or Progressing
private String message;
// getters and setters
}
apiVersion: shop.example.com/v1
kind: Shop
metadata:
name: shop
namespace: retail
spec:
image: registry.example.com/shop:1.5
replicas: 3
The CRD itself, the YAML that registers shops.shop.example.com
A reconciler with Java Operator SDK (not run)
The reconciler receives the current custom resource, already read from a local cache, and returns what to update on it. Resources the operator owns are declared as dependent resources, and JOSDK creates, updates and deletes them to match their desired
@ControllerConfiguration
@Workflow(dependents = @Dependent(type = ShopDeployment.class))
@Component
public class ShopReconciler implements Reconciler<Shop>, Cleaner<Shop> {
@Override
public UpdateControl<Shop> reconcile(Shop shop, Context<Shop> context) {
// the workflow has already reconciled ShopDeployment when this runs
Deployment deployment = context.getSecondaryResource(Deployment.class).orElseThrow();
boolean ready = Objects.equals(deployment.getStatus().getReadyReplicas(),
shop.getSpec().getReplicas());
ShopStatus status = new ShopStatus();
status.setObservedGeneration(shop.getMetadata().getGeneration());
status.setPhase(ready ? "Ready" : "Progressing");
shop.setStatus(status);
return UpdateControl.patchStatus(shop);
}
@Override
public DeleteControl cleanup(Shop shop, Context<Shop> context) {
// release anything outside Kubernetes, such as a database schema
return DeleteControl.defaultDelete();
}
}
public class ShopDeployment extends CRUDKubernetesDependentResource<Deployment, Shop> {
@Override
protected Deployment desired(Shop shop, Context<Shop> context) {
return new DeploymentBuilder()
.withNewMetadata()
.withName(shop.getMetadata().getName() + "-web")
.withNamespace(shop.getMetadata().getNamespace())
.endMetadata()
.withNewSpec()
.withReplicas(shop.getSpec().getReplicas())
// selector, labels and pod template with shop.getSpec().getImage()
.endSpec()
.build();
}
}
describes the target, exactly like the model'sdesired Deployment. JOSDK compares it with the actual Deployment, applies the difference with server-side apply, and sets thedesired as its owner, so Kubernetes garbage-collects the Deployment when theShop is deleted.Shop- Owned resources are watched as well. When someone edits or deletes
, the change triggers a reconcile of itsshop-web , which is how the drift in steps 4 and 5 of the model is detected.Shop writes only the status.UpdateControl.patchStatus writes nothing, andUpdateControl.noUpdate() asks for another reconcile later, for example while waiting for an external system.rescheduleAfter(Duration)- Implementing
makes JOSDK add a finalizer to eachCleaner . Kubernetes then keeps a deletedShop untilShop has run, which is the place to release resources outside the cluster that owner references cannot remove.cleanup - An exception from
is retried with exponential backoff by default. Throwing is the right answer to a temporary failure, such as an unreachable registry.reconcile
With the Spring Boot starter, a reconciler that is a Spring bean is registered with the operator automatically, and it can inject other beans like any Spring component. The starter also configures the fabric8 KubernetesClient~/.kube/config
Health probes for the operator pod
The operator is itself a Deployment in the cluster, and Kubernetes needs to know whether its pod is alive and whether it should take traffic. Spring Boot exposes both as health groups. This program shows how they react to the application's availability state:
package demo.operator.probes;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.LivenessState;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
public class OperatorProbes {
@SpringBootApplication
static class OperatorApplication {
}
static void probe(HttpClient http, int port, String path) throws Exception {
HttpResponse<String> response = http.send(HttpRequest.newBuilder(
URI.create("http://localhost:" + port + path)).build(),
HttpResponse.BodyHandlers.ofString());
System.out.println(" GET " + path + " -> " + response.statusCode() + " "
+ response.body());
}
static void both(HttpClient http, int port) throws Exception {
probe(http, port, "/actuator/health/liveness");
probe(http, port, "/actuator/health/readiness");
}
public static void main(String[] args) throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
OperatorApplication.class, "--server.port=0", "--spring.main.banner-mode=off",
"--logging.level.root=WARN",
// switched on automatically when Spring Boot detects Kubernetes
"--management.endpoint.health.probes.enabled=true")) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
HttpClient http = HttpClient.newHttpClient();
System.out.println("After start-up:");
both(http, port);
// e.g. this replica lost leader election and should receive no traffic
AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC);
System.out.println("After ReadinessState.REFUSING_TRAFFIC:");
both(http, port);
// e.g. the reconcile loop is stuck: let Kubernetes restart the pod
AvailabilityChangeEvent.publish(context, LivenessState.BROKEN);
System.out.println("After LivenessState.BROKEN:");
both(http, port);
}
}
}
After start-up:
GET /actuator/health/liveness -> 200 {"status":"UP"}
GET /actuator/health/readiness -> 200 {"status":"UP"}
After ReadinessState.REFUSING_TRAFFIC:
GET /actuator/health/liveness -> 200 {"status":"UP"}
GET /actuator/health/readiness -> 503 {"status":"OUT_OF_SERVICE"}
After LivenessState.BROKEN:
GET /actuator/health/liveness -> 503 {"status":"DOWN"}
GET /actuator/health/readiness -> 503 {"status":"OUT_OF_SERVICE"}
- After start-up, both
and/actuator/health/liveness answered 200/actuator/health/readiness .UP - Publishing
turned readiness into 503ReadinessState.REFUSING_TRAFFIC , while liveness stayedOUT_OF_SERVICE . Kubernetes stops sending traffic to such a pod, for example to its webhook or metrics endpoint, but does not restart it.UP - Publishing
turned liveness into 503LivenessState.BROKEN . Kubernetes restarts a pod whose liveness probe keeps failing, which is the right response to a reconcile loop that is stuck.DOWN
The program enables the probe endpoints with management.endpoint.health.probes.enabled=truelivenessProbereadinessProbe
Running the operator in the cluster (not run)
The operator needs permission to read and write its own resources and the resources it manages. A service account with a role like this one is the minimum for the Shop
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: shop-operator
rules:
- apiGroups: ["shop.example.com"]
resources: ["shops", "shops/status", "shops/finalizers"]
verbs: ["get", "list", "watch", "patch", "update"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch", "create", "patch", "update", "delete"]
- apiGroups: ["coordination.k8s.io"]
resources: ["leases"] # for leader election
verbs: ["get", "create", "update"]
- Leader election: with two or more replicas for availability, only one may reconcile at a time, or both would fight over the same resources. JOSDK supports leader election through a Kubernetes
; the other replicas wait until the leader's lease expires.Lease - Watched namespaces: an operator can watch all namespaces or a list of them. Fewer namespaces need fewer permissions, a
instead of aRole , and less memory for the informer caches.ClusterRole - Memory: informers keep a copy of every watched resource in memory. Watching all pods or all secrets of a large cluster can need far more heap than the reconcile logic itself.
- Container image: build it with
or a Dockerfile, as the./mvnw spring-boot:build-imageSpring Docker page shows.
Testing an operator
- Reconcile logic as plain Java: as the model shows, the comparison of desired and actual state needs no cluster. Keep it in methods that take and return plain objects, and test them with unit tests.
- Desired state: test each dependent resource's
method by calling it with adesired and asserting on the returned Deployment.Shop - API server tests: fabric8's mock server, or a real API server in a container started with Testcontainers, run the reconciler against Kubernetes APIs without a full cluster. JOSDK ships JUnit extensions that start the operator against such a server.
- End-to-end tests: a local cluster such as kind or minikube, with the CRD and the operator image installed, checks RBAC, leader election and real Deployments.
Choosing whether to write an operator
| Situation | Better choice |
|---|---|
| Deploying an application with fixed configuration | Plain manifests, Kustomize or a Helm chart |
| Many similar deployments that differ in a few values | A Helm chart, or an operator if the set changes at run time |
| Ongoing operational work: backups, upgrades, failover | An operator |
| Kubernetes resources tied to resources outside the cluster | An operator with a finalizer |
| A team that already writes Spring and Java | Java Operator SDK with its Spring Boot starter |
| A small, fast operator image with few dependencies | JOSDK without Spring, or a Go operator |
An operator earns its complexity when it encodes operational knowledge that would otherwise be a runbook. Keep the reconcile logic small, level-triggered and idempotent, and report honest status. For the probes and metrics of the operator itself, see the