Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:


1. Introduction

In this tutorial, we’ll show how to use the Kubernetes API from Java applications using its official client library.

2. Why Use the Kubernetes API?

Nowadays, it is safe to say that Kubernetes became the de facto standard for managing containerized applications. It offers a rich API that allows us to deploy, scale and monitor applications and associated resources, such as storage, secrets, and environment variables. In fact, one way to think about this API is the distributed analog of the system calls available in a regular operating system.

Most of the time, our applications can ignore the fact that they’re running under Kubernetes. This is a good thing, as it allows us to develop them locally and, with a few commands and YAML incantations, quickly deploy them to multiple cloud providers with just minor changes.

However, there are some interesting use cases where we need to talk to the Kubernetes API to achieve specific functionality:

  • Start an external program to perform some task and, later on, retrieve its completion status
  • Dynamically create/modify some service in response to some customer request
  • Create a custom monitoring dashboard for a solution running across multiple Kubernetes clusters, even across cloud providers

Granted, those use-cases are not that common but, thanks to its API, we’ll see that they’re quite straightforward to achieve.

Furthermore, since the Kubernetes API is an open specification, we can be quite confident that our code will run without any modifications on any certified implementation.

3. Local Development Environment

The very first thing we need to do before we move on to create an application is to get access to a functioning Kubernetes cluster. While we can either use a public cloud provider for this, a local environment usually provides more control on all the aspects of its setup.

There are a few lightweight distributions that are suitable for this task:

The actual setup steps are beyond the scope of this article but, whatever option you choose, just make sure kubectl runs fine before starting any development.

4. Maven Dependencies

First, let’s add the Kubernetes Java API dependency to our project’s pom.xml:


The latest version of client-java can be downloaded from Maven Central.

5. Hello, Kubernetes

Now, let’s create a very simple Kubernetes application that will list the available nodes, along with some information about them.

Despite its simplicity, this application illustrates the necessary steps we must go through to connect to a running cluster and perform an API call. Regardless of which API we use in a real application, those steps will always be the same.

5.1. ApiClient Initialization

The ApiClient class one of the most important classes in the API since it contains all the logic to perform a call to the Kubernetes API server. The recommended way to create an instance of this class is using one of the available static methods from the Config class. In particular, the easiest way of doing that is using the defaultClient() method:

ApiClient client = Config.defaultClient();

Using this method ensures that our code will work both remotely and in-cluster scenarios. Also, it will automatically follow the same steps used by the kubectl utility to locate the configuration file

  • Config file defined by KUBECONFIG environment variable
  • $HOME/.kube/config file
  • Service account token under /var/run/secrets/
  • Direct access to http://localhost:8080

The third step is the one that makes it possible for our app to run inside the cluster as part of any pod, as long the appropriate service account is made available to it.

Also, notice that if we have multiple contexts defined in the config file, this procedure will pick the “current” context, as defined using the kubectl config set-context command.

5.2. Creating an API Stub

Once we’ve got hold of an ApiClient instance, we can use it to create a stub for any of the available APIs. In our case, we’ll use the CoreV1Api class, which contains the method we need to list the available nodes:

CoreV1Api api = new CoreV1Api(client);

Here, we’re using the already existing ApiClient to create the API stub.

Notice that there’s also a no-args constructor available, but in general, we should refrain from using it. The reasoning for not using it is the fact that, internally, it will use a global ApiClient that must be previously set through Configuration.setDefaultApiClient(). This creates an implicit dependency on someone calling this method before using the stub, which, in turn, may lead to runtime errors and maintenance issues.

A better approach is to use any dependency injection framework to do this initial wiring, injecting the resulting stub wherever needed.

5.3. Calling a Kubernetes API

Finally, let’s get into the actual API call that returns the available nodes. The CoreApiV1 stub has a method that does precisely this, so this becomes trivial:

V1NodeList nodeList = api.listNode(null, null, null, null, null, null, null, null, 10, false);
  .forEach((node) -> System.out.println(node));

In our example, we pass null for most of the method’s parameters, as they’re optional. The last two parameters are relevant for all listXXX calls, as they specify the call timeout and whether this is a Watch call or not. Checking the method’s signature reveals the remaining arguments:

public V1NodeList listNode(
  String pretty,
  Boolean allowWatchBookmarks,
  String _continue,
  String fieldSelector,
  String labelSelector,
  Integer limit,
  String resourceVersion,
  String resourceVersionMatch,
  Integer timeoutSeconds,
  Boolean watch) {
    // ... method implementation

For this quick intro, we’ll just ignore the paging, watch and filter arguments. The return value, in this case, is a POJO with a Java representation of the returned document. For this API call, the document contains a list of V1Node objects with several pieces of information about each node. Here’s a typical output produced on the console by this code:

class V1Node {
    metadata: class V1ObjectMeta {
        labels: {
            // ... other labels omitted
        name: rancher-template
        resourceVersion: 29218
        selfLink: null
        uid: ac21e09b-e3be-49c3-9e3a-a9567b5c2836
    // ... many fields omitted
    status: class V1NodeStatus {
        addresses: [class V1NodeAddress {
            type: InternalIP
        }, class V1NodeAddress {
            address: rancher-template
            type: Hostname
        allocatable: {
            cpu=Quantity{number=1, format=DECIMAL_SI},
            ephemeral-storage=Quantity{number=18945365592, format=DECIMAL_SI},
            hugepages-1Gi=Quantity{number=0, format=DECIMAL_SI},
            hugepages-2Mi=Quantity{number=0, format=DECIMAL_SI},
            memory=Quantity{number=8340054016, format=BINARY_SI}, 
            pods=Quantity{number=110, format=DECIMAL_SI}
        capacity: {
            cpu=Quantity{number=1, format=DECIMAL_SI},
            ephemeral-storage=Quantity{number=19942490112, format=BINARY_SI}, 
            hugepages-1Gi=Quantity{number=0, format=DECIMAL_SI}, 
            hugepages-2Mi=Quantity{number=0, format=DECIMAL_SI}, 
            memory=Quantity{number=8340054016, format=BINARY_SI}, 
            pods=Quantity{number=110, format=DECIMAL_SI}}
        conditions: [
            // ... node conditions omitted
        nodeInfo: class V1NodeSystemInfo {
            architecture: amd64
            kernelVersion: 4.15.0-135-generic
            kubeProxyVersion: v1.20.2+k3s1
            kubeletVersion: v1.20.2+k3s1
            operatingSystem: linux
            osImage: Ubuntu 18.04.5 LTS
            // ... more fields omitted

As we can see, there’s quite a lot of information available. For comparison, this is the equivalent kubectl output with default settings:

root@rancher-template:~# kubectl get nodes
NAME               STATUS   ROLES                  AGE   VERSION
rancher-template   Ready    control-plane,master   24h   v1.20.2+k3s1

6. Conclusion

In this article, we’ve presented a quick intro to the Kubernetes API for Java. In future articles, we’ll dig deeper into this API and explore some of its additional features:

  • Explain the difference between the available API call variants
  • Using Watch to monitor cluster events in realtime
  • How to use paging to efficiently retrieve a large volume of data from a cluster

As usual, the full source code of the examples can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.