Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

A Quick Intro to the Kubernetes Java Client

4 min read

Kubernetes is a popular container orchestration system that simplifies the deployment, scaling, and management of containerized applications. The Kubernetes Java Client is a powerful library that allows Java developers to interact with Kubernetes clusters programmatically, and perform a wide range of operations, including managing pods, services, deployments, and more.

In this blog post, we’ll provide a quick introduction to the Kubernetes Java Client, and show you how to use it to interact with a Kubernetes cluster.

What is the Kubernetes Java Client?

The Kubernetes Java Client is a Java library that provides a programmatic interface to interact with a Kubernetes cluster. It is a client-side library that can be used to perform various operations on Kubernetes resources, such as pods, services, deployments, and more.

The Kubernetes Java Client is built on top of the Kubernetes REST API, which means that it interacts with Kubernetes resources using the same API that is used by the kubectl CLI tool and other Kubernetes clients. This ensures that the Kubernetes Java Client is always up-to-date with the latest Kubernetes features and changes.

The Kubernetes Java Client provides a simple and intuitive API that abstracts away the complexity of interacting with Kubernetes resources. It provides a wide range of functionality, including:

  • Creating, updating, and deleting Kubernetes resources
  • Scaling up and down deployments
  • Retrieving and watching resource events
  • Executing commands inside containers

How to use the Kubernetes Java Client

To use the Kubernetes Java Client, you’ll need to add it as a dependency to your Java project. The Kubernetes Java Client is available on Maven Central, so you can add it to your project by adding the following dependency to your pom.xml file:

<dependency>
  <groupId>io.kubernetes</groupId>
  <artifactId>client-java</artifactId>
  <version>10.0.0</version>
</dependency>

Once you’ve added the Kubernetes Java Client to your project, you can start using it to interact with a Kubernetes cluster. The first step is to create a Kubernetes client object:

import io.kubernetes.client.*;
import io.kubernetes.client.apis.*;
import io.kubernetes.client.models.*;
import io.kubernetes.client.util.*;

public class KubernetesClientExample {
  public static void main(String[] args) throws Exception {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
  }
}

In this example, we’re using the Config.defaultClient() method to create a default Kubernetes client object. This method reads the Kubernetes configuration file located at ~/.kube/config, and uses the credentials and settings defined in the file to create a client object.

Once you have a client object, you can use it to create instances of Kubernetes API classes, such as CoreV1Api for interacting with the core Kubernetes resources:

CoreV1Api api = new CoreV1Api();

With the CoreV1Api object, you can interact with Kubernetes resources, such as pods, services, and namespaces. For example, to list all pods in a Kubernetes cluster, you can use the following code:

V1PodList podList = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
for (V1Pod item : podList.getItems()) {
  System.out.println(item.getMetadata().getName());
}

This code retrieves a list of all pods in the cluster and prints their names to the console.

Creating, updating, and deleting Kubernetes resources

import io.kubernetes.client.ApiException;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.models.V1Deployment;
import io.kubernetes.client.models.V1DeploymentSpec;
import io.kubernetes.client.models.V1ObjectMeta;

public class KubernetesClientExample {
    public static void main(String[] args) throws ApiException {
        CoreV1Api api = new CoreV1Api();

        // Create a new deployment
        V1Deployment deployment = new V1Deployment();
        deployment.setApiVersion("apps/v1");
        deployment.setKind("Deployment");

        V1ObjectMeta metadata = new V1ObjectMeta();
        metadata.setName("my-deployment");
        deployment.setMetadata(metadata);

        V1DeploymentSpec spec = new V1DeploymentSpec();
        spec.setReplicas(3);
        // ... set other spec properties

        deployment.setSpec(spec);

        api.createNamespacedDeployment("default", deployment, null, null, null);

        // Update the deployment
        spec.setReplicas(5);
        api.replaceNamespacedDeployment("my-deployment", "default", deployment, null, null);

        // Delete the deployment
        api.deleteNamespacedDeployment("my-deployment", "default", null, null, null, null, null, null);
    }
}

This code creates a new deployment with three replicas, updates it to have five replicas, and then deletes it.

Scaling up and down deployments:

import io.kubernetes.client.ApiException;
import io.kubernetes.client.apis.AppsV1Api;
import io.kubernetes.client.models.V1Scale;
import io.kubernetes.client.models.V1ScaleSpec;

public class KubernetesClientExample {
    public static void main(String[] args) throws ApiException {
        AppsV1Api api = new AppsV1Api();

        // Scale up the deployment
        V1Scale scale = new V1Scale();
        scale.setApiVersion("apps/v1");
        scale.setKind("Scale");
        scale.setMetadata(deployment.getMetadata());

        V1ScaleSpec spec = new V1ScaleSpec();
        spec.setReplicas(5);
        scale.setSpec(spec);

        api.replaceNamespacedDeploymentScale("my-deployment", "default", scale, null, null);

        // Scale down the deployment
        spec.setReplicas(3);
        api.replaceNamespacedDeploymentScale("my-deployment", "default", scale, null, null);
    }
}

This code scales up a deployment to five replicas, and then scales it back down to three replicas.

Retrieving and watching resource events

import io.kubernetes.client.ApiException;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.models.V1EventList;
import io.kubernetes.client.util.Watch;
import io.kubernetes.client.util.Watch.Response;

public class KubernetesClientExample {
    public static void main(String[] args) throws ApiException {
        CoreV1Api api = new CoreV1Api();

        // Retrieve events
        V1EventList eventList = api.listNamespacedEvent("default", null, null, null, null, null, null, null, null);
        for (V1Event event : eventList.getItems()) {
            System.out.println(event.getMetadata().getName() + ": " + event.getMessage());
        }

        // Watch events
        Watch<V1Event> watch = Watch.createWatch(
            api,
            api.listNamespacedEventCall("default", null, null, null, null,
        null, null, Boolean.TRUE, null, null),
        new TypeToken<Response<V1Event>>(){}.getType());
    for (Response<V1Event> response : watch) {
        V1Event event = response.object;
        System.out.println(event.getMetadata().getName() + ": " + event.getMessage());
    }
}
}

This code retrieves all events in the “default” namespace, and then watches for new events and prints out their messages.

Executing commands inside containers

import io.kubernetes.client.ApiException;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.models.V1ExecAction;
import io.kubernetes.client.models.V1Container;
import io.kubernetes.client.models.V1Pod;
import io.kubernetes.client.models.V1PodExecOptions;
import io.kubernetes.client.util.Exec;
import java.util.Arrays;

public class KubernetesClientExample {
    public static void main(String[] args) throws ApiException, InterruptedException {
        CoreV1Api api = new CoreV1Api();

        // Get the first pod in the "default" namespace
        V1Pod pod = api.listNamespacedPod("default", null, null, null, null, null, null, null, null, null).getItems().get(0);

        // Create an exec command
        String containerName = pod.getSpec().getContainers().get(0).getName();
        String[] command = new String[] {"sh", "-c", "echo hello"};
        V1ExecAction exec = new V1ExecAction();
        exec.setCommand(Arrays.asList(command));

        V1PodExecOptions options = new V1PodExecOptions();
        options.setCommand(Arrays.asList(command));
        options.setContainer(containerName);
        options.setStdin(Boolean.FALSE);
        options.setStdout(Boolean.TRUE);
        options.setStderr(Boolean.TRUE);

        // Execute the command
        Exec.exec(api, pod, exec, options, null, System.out, System.err);
    }
}

This code gets the first pod in the “default” namespace, creates an exec command to run echo hello inside the pod’s container, and then executes the command and prints the output to the console.

The Kubernetes Java Client provides many more features, including support for multiple Kubernetes API versions, authentication and authorization, custom resource definitions, and more. Check out the client’s documentation for more information and examples.

Conclusion

In this blog post, we’ve provided a quick introduction to the Kubernetes Java Client, and shown you how to use it to interact with a Kubernetes cluster. The Kubernetes Java Client is a powerful library that simplifies the management of Kubernetes resources.

Resources

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).
Join our Discord Server
Index