Cloud Native 17 min read

Kubernetes Java Client Initialization and DSL Usage Guide

This article demonstrates how to initialize a Kubernetes Java client, configure it with default or custom kubeconfig, and provides comprehensive DSL examples for managing Pods, Services, Deployments, ReplicaSets, including creation, listing, updating, watching, port forwarding, and cleanup, with full code snippets throughout.

FunTester
FunTester
FunTester
Kubernetes Java Client Initialization and DSL Usage Guide

Initialize Kubernetes Client

Before using Kubernetes, you need to initialize a client. The default client reads the ~/.kube/config file or the path defined by the KUBECONFIG environment variable. You can also provide a custom Config object to the builder.

try (final KubernetesClient client = new KubernetesClientBuilder().build()) {
    // use client for operations
}

Custom configuration example:

Config kubeConfig = new ConfigBuilder()
    .withMasterUrl("https://192.168.42.20:8443/")
    .build();
try (final KubernetesClient client = new KubernetesClientBuilder().withConfig(kubeConfig).build()) {
    // use client for operations
}

Kubernetes Client DSL Usage

The DSL provides fluent access to all supported resources. Below are representative snippets for Pods, Services, Deployments, and ReplicaSets.

Pods

Access pods via client.pods() . Common operations include loading from YAML, listing, creating, editing, retrieving logs, watching, port‑forwarding, and cleanup.

Pod myPod = client.pods().load(new FileInputStream("some-pod.yml")).item();
PodList podList = client.pods().inNamespace("FunTester").list();
PodList podList = client.pods().inAnyNamespace().list();
PodList podList = client.pods().inNamespace("FunTester").withLabel("foo", "bar").list();
Pod myPod = client.pods().inNamespace("FunTester").withName("nginx-pod").get();
Pod aPod = new PodBuilder().withNewMetadata().withName("demo-pod1").endMetadata()
    .withNewSpec()
    .addNewContainer().withName("nginx").withImage("nginx:1.7.9")
    .addNewPort().withContainerPort(80).endPort()
    .endContainer()
    .endSpec()
    .build();
client.pods().inNamespace("FunTester").resource(aPod).create();
client.pods().inNamespace("FunTester").resource(pod).serverSideApply();
client.pods().inNamespace("FunTester").withName("nginx").edit(p -> new PodBuilder(p).editOrNewMetadata().addToLabels("new", "label").endMetadata().build());
String log = client.pods().inNamespace("FunTester").withName("test-pod").getLog();
LogWatch watch = client.pods().inNamespace(namespace).withName(podName).tailingLines(10).watchLog(System.out);
client.pods().inNamespace("FunTester").withName("nginx").delete();
client.resourceList(pod1, pod2).inNamespace("FunTester").delete();
client.pods().inNamespace("FunTester").withName("nginx").waitUntilReady(5, TimeUnit.MINUTES);
client.pods().inNamespace("FunTester").withName("nginx").waitUntilCondition(pod -> pod.getStatus().getPhase().equals("Succeeded"), 1, TimeUnit.MINUTES);
int containerPort = client.pods().inNamespace("FunTester").withName("testpod").get().getSpec().getContainers().get(0).getPorts().get(0).getContainerPort();
LocalPortForward portForward = client.pods().inNamespace("FunTester").withName("testpod").portForward(containerPort, 8080);

Service

Access services via client.services() . Typical operations include loading from YAML, retrieving, creating, applying, listing, deleting, and watching.

Service aService = client.services().load(new FileInputStream("service.yml")).item();
Service service = client.services().inNamespace("FunTester").withName("some-service").get();
Service createdSvc = client.services().inNamespace("FunTester").resource(svc).create();
client.services().inNamespace("FunTester").resource(svc).serverSideApply();
ServiceList svcList = client.services().inNamespace("FunTester").list();
ServiceList svcList = client.services().inAnyNamespace().list();
ServiceList svcList = client.services().inNamespace("FunTester").withLabel("foo", "bar").list();
client.services().inNamespace("FunTester").withName("some-svc").delete();
client.services().inNamespace("FunTester").watch(new Watcher<>() {
    @Override public void eventReceived(Action action, Service resource) { /* handle */ }
    @Override public void onClose(WatcherException cause) { }
});

Deployment

Access deployments via client.apps().deployments() . Operations cover loading, retrieving, creating, applying, scaling, editing, updating images, rolling restart, pause/resume, undo, delete, and watch.

Deployment aDeployment = client.apps().deployments().load(new FileInputStream("test-deployments.yml")).item();
Deployment deploy = client.apps().deployments().inNamespace("FunTester").withName("deploy-1").get();
Deployment deployment1 = new DeploymentBuilder()
    .withNewMetadata().withName("FunTesterdeployment1").addToLabels("test", "deployment").endMetadata()
    .withNewSpec().withReplicas(1)
    .withNewTemplate().withNewMetadata().addToLabels("app", "httpd").endMetadata()
    .withNewSpec().addNewContainer().withName("busybox").withImage("busybox").withCommand("sleep", "36000").endContainer().endSpec().endTemplate()
    .withNewSelector().addToMatchLabels("app", "httpd").endSelector().endSpec().build();
client.apps().deployments().inNamespace("FunTester").resource(deployment1).create();
client.apps().deployments().inNamespace("FunTester").resource(deployObj).serverSideApply();
DeploymentList aDeploymentList = client.apps().deployments().inNamespace("FunTester").list();
DeploymentList aDeploymentList = client.apps().deployments().inAnyNamespace().list();
DeploymentList aDeployList = client.apps().deployments().inNamespace("FunTester").withLabel("foo", "bar").list();
Deployment updatedDeploy = client.apps().deployments().inNamespace("FunTester").withName("deployment1").edit(d -> new DeploymentBuilder(d).editSpec().withReplicas(2).endSpec().build());
client.apps().deployments().inNamespace("FunTester").withName("ngix-controller").updateImage("docker.io/nginx:latest");
Map
containerToImageMap = new HashMap<>();
containerToImageMap.put("nginx", "nginx:perl");
containerToImageMap.put("sidecar", "someImage:someVersion");
client.apps().deployments().inNamespace("FunTester").withName("nginx-deployment").updateImage(containerToImageMap);
client.apps().deployments().inNamespace("FunTester").withName("nginx-deployment").rolling().restart();
client.apps().deployments().inNamespace("FunTester").withName("nginx-deployment").rolling().pause();
client.apps().deployments().inNamespace("FunTester").withName("nginx-deployment").rolling().resume();
client.apps().deployments().inNamespace("FunTester").withName("nginx-deployment").rolling().undo();
client.apps().deployments().inNamespace("FunTester").withName("foo").delete();
client.apps().deployments().inNamespace("FunTester").watch(new Watcher<>() {
    @Override public void eventReceived(Action action, Deployment resource) { /* handle */ }
    @Override public void onClose(WatcherException cause) { }
});
client.apps().deployments().inNamespace("FunTester").withName("nginx-deployment").scale(1);
client.apps().deployments().inNamespace("FunTester").withName("nginx").watchLog(System.out);

ReplicaSet

Access replica sets via client.apps().replicaSets() . The guide shows loading, retrieving, creating, applying, listing, scaling, updating images, deleting, and watching.

ReplicaSet replicaSet = client.apps().replicaSets().inNamespace("FunTester").load(new FileInputStream("test-replicaset.yml")).item();
ReplicaSet rs = client.apps().replicaSets().inNamespace("FunTester").withName("rs1").get();
ReplicaSet replicaset1 = new ReplicaSetBuilder()
    .withNewMetadata().withName("replicaset1").addToLabels("app", "guestbook").addToLabels("tier", "frontend").endMetadata()
    .withNewSpec().withReplicas(1)
    .withNewSelector().withMatchLabels(Collections.singletonMap("tier", "frontend")).endSelector()
    .withNewTemplate().withNewMetadata().addToLabels("app", "guestbook").addToLabels("tier", "frontend").endMetadata()
    .withNewSpec().addNewContainer().withName("busybox").withImage("busybox").withCommand("sleep", "36000").endContainer().endSpec().endTemplate()
    .endSpec().build();
client.apps().replicaSets().inNamespace("FunTester").resources(replicaset1).create();
client.apps().replicaSets().inNamespace("FunTester").resource(replicaSet).serverSideApply();
ReplicaSetList rsList = client.apps().replicaSets().inNamespace("FunTester").list();
ReplicaSetList rsList = client.apps().replicaSets().inAnyNamespace().list();
ReplicaSetList rsList = client.apps().replicaSets().inNamespace("FunTester").withLabel("foo", "bar").list();
client.apps().replicaSets().inNamespace("FunTester").withName("rs1").delete();
client.apps().replicaSets().inNamespace("FunTester").watch(new Watcher<>() {
    @Override public void eventReceived(Action action, ReplicaSet resource) { /* handle */ }
    @Override public void onClose(WatcherException e) { }
});
client.apps().replicaSets().inNamespace("FunTester").withName("nginx-rs").scale(3);
client.apps().replicaSets().inNamespace("FunTester").withName("soaktestrs").updateImage("nickchase/soaktest");
Map
containerToImageMap = new HashMap<>();
containerToImageMap.put("c1", "image1");
containerToImageMap.put("c2", "image2");
client.apps().replicaSets().inNamespace("FunTester").withName("soaktestrs").updateImage(containerToImageMap);

Show You Code

The following script puts the previous concepts together: it creates a namespace, deploys an Nginx pod, creates a LoadBalancer service, waits for the pod to become ready, prints its logs, and finally deletes the namespace and all resources.

import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.*;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import io.fabric8.kubernetes.client.dsl.PodResource;
import java.util.concurrent.TimeUnit;

public class KubernetesFunTesterDemo {
    public static void main(String[] args) {
        // Initialize Kubernetes client
        try (KubernetesClient client = new KubernetesClientBuilder().build()) {
            String namespace = "fun-tester";
            // 1. Create namespace
            Namespace ns = new NamespaceBuilder()
                .withNewMetadata().withName(namespace).endMetadata()
                .build();
            client.namespaces().resource(ns).create();
            System.out.println("命名空间 " + namespace + " 创建成功!");
            // 2. Deploy Nginx Pod
            Pod nginxPod = new PodBuilder()
                .withNewMetadata().withName("nginx-pod").addToLabels("app", "nginx").endMetadata()
                .withNewSpec()
                .addNewContainer().withName("nginx-container").withImage("nginx:1.21.0")
                .addNewPort().withContainerPort(80).endPort()
                .endContainer()
                .endSpec()
                .build();
            client.pods().inNamespace(namespace).resource(nginxPod).create();
            System.out.println("Nginx Pod 创建成功!");
            // 3. Create Service
            Service nginxService = new ServiceBuilder()
                .withNewMetadata().withName("nginx-service").endMetadata()
                .withNewSpec()
                .addNewPort().withPort(80).withTargetPort(new IntOrString(80)).endPort()
                .withSelector(nginxPod.getMetadata().getLabels())
                .withType("LoadBalancer")
                .endSpec()
                .build();
            client.services().inNamespace(namespace).resource(nginxService).create();
            System.out.println("Nginx Service 创建成功!");
            // 4. Wait for Pod ready
            PodResource
podResource = client.pods().inNamespace(namespace).withName("nginx-pod");
            Pod readyPod = podResource.waitUntilReady(5, TimeUnit.MINUTES);
            System.out.println("Nginx Pod 已准备就绪,状态为: " + readyPod.getStatus().getPhase());
            // 5. Get Pod logs
            String podLog = podResource.getLog();
            System.out.println("Nginx Pod 日志如下:");
            System.out.println(podLog);
            // 6. Cleanup
            client.namespaces().withName(namespace).delete();
            System.out.println("命名空间 " + namespace + " 及其所有资源已删除!");
        } catch (KubernetesClientException e) {
            System.err.println("Kubernetes 操作失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Notes

Ensure a local Kubernetes cluster (Minikube, Kind, etc.) is running and kubectl works.

If the cluster does not support LoadBalancer , change the Service type to NodePort .

The wait timeout (5 minutes) can be adjusted based on your environment.

Javacloud nativekubernetesDevOpsClientFabric8
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.