Skip to content

Creating Jobs with the Kubernetes Java Client

Interactive Diagram

새 탭 ↗

When an application calls the Kubernetes API, the important part is not assembling YAML as strings. It is representing the desired state with Java objects. The Kubernetes Java Client provides models such as ApiClient, BatchV1Api, V1Job, V1JobSpec, and V1PodSpec so that a Job request can be expressed in code.

Configure the client: in-cluster and local paths

Section titled “Configure the client: in-cluster and local paths”

The code here targets io.kubernetes:client-java 20.x. This library changes API method signatures across major versions, so pin the version before writing anything against it.

There are two ways to build an ApiClient, and confusing them means discovering an authentication failure only after deployment.

The in-cluster path is the production default. When the Scheduler itself runs as a Kubernetes Pod, use ClientBuilder.cluster(). That builder reads the ServiceAccount token automatically mounted at /var/run/secrets/kubernetes.io/serviceaccount/token, the CA certificate at .../ca.crt, and the KUBERNETES_SERVICE_HOST / KUBERNETES_SERVICE_PORT environment variables to derive the API Server address and credentials. No kubeconfig file and no separately managed token are required. The token is refreshed through a projected volume, so let the client re-read the file rather than caching its contents forever.

The kubeconfig path is for local development and CI, where the caller lives outside the cluster. Only then does the application load a kubeconfig and explicitly select a context.

ApiClient apiClient;
if (runningInCluster) {
// production: reads the ServiceAccount token and CA from the Pod filesystem
apiClient = ClientBuilder.cluster().build();
} else {
// local/dev: explicitly select a context from kubeconfig
KubeConfig kubeConfig = KubeConfig.loadKubeConfig(
Files.newBufferedReader(Path.of(kubeConfigPath)));
kubeConfig.setContext(contextName);
apiClient = ClientBuilder.kubeconfig(kubeConfig).build();
}
apiClient.setHttpClient(apiClient.getHttpClient().newBuilder()
.readTimeout(Duration.ofSeconds(30))
.build());

Decide runningInCluster from the presence of KUBERNETES_SERVICE_HOST or from an application profile. ClientBuilder.standard() picks a path automatically, but it does not make the chosen credential visible in logs, so an explicit branch is easier to diagnose in production.

PlantUML Diagram

A context and a namespace are different values. A context selects a cluster and user-authentication combination, while a namespace scopes resources inside that cluster. On the in-cluster path there is no context at all (the ServiceAccount plays that role) but the namespace still has to be supplied. Do not hard-code either value in source; inject them through environment-specific configuration.

A Job is assembled from these objects.

  • V1ObjectMeta: labels, name, or generateName
  • V1JobSpec: backoffLimit, ttlSecondsAfterFinished, and the Pod template
  • V1PodTemplateSpec: Pod metadata and Pod spec
  • V1PodSpec: containers, restartPolicy, nodeSelector, and tolerations
  • V1Container: image, environment, and resources
Map<String, String> labels = Map.of(
"app", "integration-job",
"interfaceId", ifId,
"jobExecutionId", String.valueOf(jobExecutionId));
V1Container container = new V1Container()
.name("integration-worker")
.image("registry.example.invalid/integration/worker:2024.03")
.addEnvItem(new V1EnvVar().name("IF_ID").value(ifId))
.addEnvItem(new V1EnvVar().name("JAVA_TOOL_OPTIONS")
.value("-XX:MaxRAMPercentage=70.0"))
.resources(new V1ResourceRequirements()
.putRequestsItem("cpu", new Quantity("250m"))
.putRequestsItem("memory", new Quantity("512Mi"))
.putLimitsItem("cpu", new Quantity("1"))
.putLimitsItem("memory", new Quantity("1Gi")));
V1PodSpec podSpec = new V1PodSpec()
.addContainersItem(container)
.restartPolicy("Never");
V1Job job = new V1Job()
.apiVersion("batch/v1")
.kind("Job")
.metadata(new V1ObjectMeta()
.labels(labels)
.generateName("integration-job-"))
.spec(new V1JobSpec()
.backoffLimit(0)
.ttlSecondsAfterFinished(86400)
.template(new V1PodTemplateSpec()
// the Pod needs the same labels to be findable by selector
.metadata(new V1ObjectMeta().labels(labels))
.spec(podSpec)));

Three of those settings are deliberate.

The Pod template’s metadata().labels() is easy to omit and painful to live without. Labels placed on the Job stay on the Job object; they are not propagated to the Pod. The job-name and controller-uid labels the Job controller injects are not enough to find a Pod by Interface ID or execution ID. To list Pods by label selector and collect their logs, the Pod template needs the same labels.

backoffLimit(0) means the Job controller will not retry a failed Pod. For an Integration batch that writes to external systems, Kubernetes cannot know how far the Pod got before dying, so an automatic retry can duplicate work. It is safer to leave retry decisions to the batch’s own duplicate prevention and resume point, or to the Control Plane above it. A bounded backoffLimit is reasonable only when the input is immutable and the work is fully idempotent.

Memory is specified alongside CPU. Without a memory limit the Pod becomes an eviction candidate at an unpredictable moment when node memory runs short; without a memory request the scheduler places the Pod with no idea of its real footprint. Because the JVM is container-aware, prefer -XX:MaxRAMPercentage (a ratio of the limit) over a hard-coded -Xmx. Leave headroom well below 100%, since metaspace, thread stacks, direct buffers, and the code cache all consume native memory outside the heap.

The registry and image are documentation placeholders. Prefer an immutable version or digest over a mutable latest tag.

Once the object is assembled, create the Job in a namespace. This is where the version difference shows most clearly. Through client-java 19.x, every optional parameter was a positional argument.

// client-java 19.x and earlier: positional parameters (pretty, dryRun, fieldManager, fieldValidation)
BatchV1Api api = new BatchV1Api(apiClient);
V1Job created = api.createNamespacedJob(namespace, job, null, null, null, null);
V1Job current = api.readNamespacedJob(jobName, namespace, null);

From 20.x onward the API returns a fluent request builder: set only the optional parameters you need and finish with execute(). There is no row of null placeholders to miscount.

// client-java 20.x and later: fluent builder plus execute()
BatchV1Api api = new BatchV1Api(apiClient);
V1Job created = api.createNamespacedJob(namespace, job)
.fieldManager("integration-scheduler")
.execute();
String jobName = created.getMetadata().getName();
V1Job current = api.readNamespacedJob(jobName, namespace)
.execute();

When generateName is used, the API Server decides the final name, so the response’s getMetadata().getName() must be stored. The name is simply not known at request time.

A successful create response does not mean the business work succeeded. HTTP 201 only means the desired state was persisted to etcd; scheduling and container startup have not happened yet. Store the returned Job name and labels with the execution ID, then use readNamespacedJob or a watch API to observe active, succeeded, and failed status.

Labels matter more than a human-readable Job name. These values can connect Kubernetes state to Integration Trace.

ValuePurpose
interfaceIdSearch for the Interface execution
correlationIdConnect the Job to its parent request
jobExecutionIdConnect Batch execution to the Kubernetes Job
imageVersionIdentify the code that actually ran
createdByDistinguish API and Scheduler creation

Do not put personal information or secrets in labels. Do not put the complete payload into Job environment variables; use a secret reference or a restricted object-storage reference instead.

Independently setting Java heap and Kubernetes memory resources can cause OOM failures. If -Xms and -Xmx are passed to the process, the heap plus native memory must stay below the container memory limit. When the two are hard to keep in sync, tie the heap to the limit with -XX:MaxRAMPercentage. Exceeding the limit produces a kernel OOM kill and exit code 137, not a JVM OutOfMemoryError, and no stack trace at all.

  • Requests affect scheduling and the minimum reserved amount.
  • Limits define the container upper bound.
  • Set both CPU and memory. Setting only one distorts either scheduling or eviction priority.
  • restartPolicy: Never lets the Job controller count failures.
  • backoffLimit defines Pod retry attempts. Keep it at 0 for side-effecting batches and decide retries at a higher layer.
  • ttlSecondsAfterFinished controls cleanup timing. Too short and the Job disappears before its status can be read.
  • activeDeadlineSeconds bounds a Job that would otherwise hang indefinitely.
  • Use nodeSelector and tolerations only when selecting a governed worker pool.

Node pinning is coupled to cluster policy, so public examples should use neutral label keys and values.

Separate authentication errors, namespace authorization errors, validation errors, and API timeouts. Convert ApiException status and response details into the platform error model, and do not blindly create another Job for every failure.

The ServiceAccount should have only the Job create/read permissions required in the target namespace. Do not grant cluster-wide access or arbitrary Pod exec by default. Never put kubeconfig or tokens in an image, source file, or log.

The Kubernetes Java Client flow is building an ApiClient appropriate to where the code runs (ClientBuilder.cluster() in production, a kubeconfig context locally), BatchV1Api invocation, V1Job object composition, and Job status observation. Separating create success from business success, and designing labels, resources, retries, TTL, and RBAC together turns a Scheduler from a thin API wrapper into an operational Control Plane.