Skip to main content
AI
  • Get started with AI

    • Red Hat AI

      Accelerate the development and deployment of enterprise AI solutions.

    • AI learning hub

      Explore learning materials and tools, organized by task.

    • AI interactive demos

      Click through scenarios with Red Hat AI, including training LLMs and more.

    • AI/ML learning paths

      Expand your Red Hat OpenShift AI knowledge using these learning resources.

    • AI quickstarts

      Focused AI use cases designed for fast deployment on Red Hat AI platforms.

    • No-cost AI training

      Foundational Red Hat AI training.

  • Featured resources

    • Red Hat OpenShift AI
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

Red Hat AI Factory with NVIDIA

Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.

Learn
  • Self-guided

    • Documentation

      Find answers, get step-by-step guidance, and learn how to use Red Hat products.

    • Learning paths

      Explore curated walkthroughs for common development tasks.

    • Guided learning

      Receive custom learning paths powered by our AI assistant.

    • See all learning
  • Hands-on

    • Developer Sandbox

      Spin up Red Hat's products and technologies without setup or configuration.

    • Interactive labs

      Learn by doing in these hands-on, browser-based experiences.

    • Interactive demos

      Click through product features in these guided tours.

  • Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics
  • Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
Build
  • Get started

    • Red Hat build of Podman Desktop

      A downloadable, local development hub to experiment with our products and builds.

    • Developer Sandbox

      Spin up Red Hat's products and technologies without setup or configuration.

  • Download products

    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products
  • Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset
  • References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
Community
  • Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions
  • Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github
  • Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

Join the Red Hat Developer program

Download Red Hat products and project builds, access support documentation, learning content, and more.

ConsoleDocsSupport Search
New For you

Recommended

We'll recommend resources you may like as you browse. Try these suggestions for now.

  • Product downloads
  • Cheat sheets
  • Red Hat Developer learning portal
  • Developer blog
  • E-books
  • Developer Sandbox
Log in

Get more with a Red Hat Developer account

  • Product downloads
  • Console access
  • Event registration
  • Training & trials
Explore more account benefitsLog in or register

A subscription may be required for some services.

Contact us

How to use Fabric8 Java Client with Kubernetes

January 4, 2023
Rohan Kumar
Related topics:
GoJavaKubernetes
Related products:
Red Hat OpenShift

    The last few years have seen a rise in containers-based development, with more programmers coming to understand the benefits of using containers rather than traditional VMs or just bare metal. Kubernetes arose to help scale containers for enterprise use cases and has established itself as the most popular container orchestrating platform. From the beginning of the Kubernetes project, the community of users and contributors has grown fast. As of this publication, it is one of the most popular projects on Github.

    I recently read the book Programming Kubernetes, which gives an overview of programming Kubernetes with Golang. As a contributor to the Fabric8 Kubernetes Client, I was inspired to write a blog series that covers similar topics from a Java developer's perspective.

    Red Hat Developer has presented Fabric8 Java Client before in several articles, including:

    • Getting started with the Fabric8 Kubernetes Java client
    • What's new in Fabric8 Kubernetes client version 5.5.0
    • New HTTP clients, a Java generator, and more in Fabric8 6.0.0

    This article is the first installment in my series focusing on topics from a developer's perspective.

    • Part 1: How to use Fabric8 Java Client with Kubernetes
    • Part 2: Programming Kubernetes custom resources in Java
    • Part 3: How to use Kubernetes dynamic client with Fabric8
    • Part 4: How to generate code using Fabric8 Kubernetes Client
    • Part 5: How to write tests with Fabric8 Kubernetes Client

    Why program Kubernetes in Java?

    Kubernetes is written in Golang, as are most of the tools and libraries built around it. So why would it be a good idea to program Kubernetes in a language like Java?

    Well, if you don't have a Golang background, it would take some time to learn the language—an effort that might be unnecessary if you don't plan to use Golang elsewhere in your organization.

    Kubernetes exposes most of its operations via its REST API. Even a tool like kubectl contacts the Kubernetes Server API via its REST API. You can see this by checking kubectl verbose logs:

    ~ : $ kubectl get pods -v=6
    
    I0716 15:32:51.736643    8647 loader.go:372] Config loaded from file:  /home/rokumar/.kube/config
    
    I0716 15:32:51.746201    8647 round_trippers.go:454] GET https://[::1]:37775/api/v1/namespaces/default/pods?limit=500 200 OK in 6 milliseconds
    
    NAME                                     READY   STATUS    RESTARTS   AGE
    
    nginx-deploymentwt9x9-5d59d67564-dlndq   1/1     Running   3          19h
    
    nginx-deploymentwt9x9-5d59d67564-pjm97   1/1     Running   3          19h
    
    nginx-deploymentwt9x9-5d59d67564-qsfp7   1/1     Running   3          19h

    At the time of this article, Kubernetes 1.25 is the latest stable release. Read the Kubernetes API reference document for more information. You can interact with the REST API with any programming language. Java is still one of the most popular programming languages, and many companies still use it.

    Currently, there are multiple Java libraries for Kubernetes, the most popular being the Fabric8 Kubernetes Client and the Official Kubernetes client. We will focus on Fabric8 because it provides a fluent DSL for interacting with the Kubernetes API, a mock testing framework for writing Kubernetes Java tests, and extension hooks to create your KubernetesClient extensions.

    Fabric8 Kubernetes Client provides excellent support for interacting with Kubernetes programmatically via Java. In this series, we will develop Java applications that interact with Kubernetes APIs to perform an operation.

    How to Obtain Fabric8 Kubernetes Client

    The Fabric8 Kubernetes Client library should be available on Maven Central. If you are using Maven, you should be able to add it as a dependency in your project by adding the following to the dependencies section of your pom.xml file:

    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>kubernetes-client</artifactId>
      <version>6.1.1</version>
    </dependency>

    Gradle users should add this line to build.gradle:

    implementation 'io.fabric8:kubernetes-client:6.1.1'

    How to use the Fabric8 Kubernetes Client

    Once you have added the kubernetes-client dependency to your project, you can start using it.

    First, initialize a KubernetesClient object:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
    
    }
    

    This would automatically create an opinionated KubernetesClient object by reading configuration either from the local ~/.kube/config file or from the currently mounted ServiceAccount (in case it's inside a pod).

    It's also possible to provide your own configuration to the client:

    try (KubernetesClient client = new KubernetesClientBuilder()
        .withConfig(new ConfigBuilder()
            .withMasterUrl("https://api.sandbox.x8i5.example.com:6443")
            .withOauthToken("sha256~secret")
            .withNamespace("default")
            .withCaCertFile("/home/foo/.minikube/ca.crt")
            .withClientCertFile("/home/foo/.minikube/profiles/minikube/client.crt")
            .withClientKeyFile("/home/foo/.minikube/profiles/minikube/client.key")
            .withClientKeyAlgo("RSA")
            .build())
        .build()) {
    
    }
    

    Another option is to configure Fabric8 Kubernetes Client using properties. Table 1 lists properties you can use to tune the client's behavior.

    Table 1. Properties for configuring Fabric8 Kubernetes Client
    Property Description
    kubernetes.master URL of OpenShift cluster
    kubernetes.auth.token OpenShift API token received from the Copy Login command
    kubernetes.namespace Preferred namespace
    kubernetes.auth.tryServiceAccount Determines whether to check for a mounted service account
    kubernetes.auth.tryKubeConfig Determines whether to check for a KubeConfig file

    You can read the complete list of properties in the Fabric8 Kubernetes Client documentation.

    Create, read, update, and delete operations with Fabric8 Kubernetes Client

    Fabric8 Kubernetes Client provides a fluent DSL, so it is easy to do basic create, read, update, and delete (CRUD) operations on built-in resources.

    Here's an example:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      // Load the Service resource definition from a file
      Service svc = client.services()
          .load(CreateReadUpdateDeleteDemo.class.getResourceAsStream("/test-svc.yaml"))
          .get();
    
      // Create a Service
      client.services()
          .inNamespace("default")
          .resource(svc)
          .create();
    
      // List Services
      ServiceList svcList = client.services().inNamespace("default").list();
      logger.info("Found {} Services", svcList.getItems().size());
    
    
      // Update Service
      svc.getMetadata().setLabels(Collections.singletonMap("foo", "bar"));
      client.services()
          .inNamespace("default")
          .resource(svc)
          .replace();
    
      // Delete Service
      client.services()
          .inNamespace("default")
          .resource(svc)
          .delete();
    }
    

    Create objects using builders

    Fabric8 Kubernetes Client also provides fluent builders for Kubernetes resource objects so that you can create these complex objects inline.

    Consider a scenario in which you have this Deployment:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-deployment
      labels:
        app: nginx
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
          - name: nginx
            image: nginx:1.7.9
            ports:
            - containerPort: 80
    

    You can create the same object using a fluent builder provided by the Fabric8 Kubernetes Client model.

    Here is an example:

    Deployment deployment = new DeploymentBuilder()
            .withNewMetadata()
                .withName("nginx-deployment")
                .addToLabels("app", "nginx")
            .endMetadata()
            .withNewSpec()
                .withReplicas(1)
                .withNewSelector()
                    .addToMatchLabels("app", "nginx")
                .endSelector()
            .withNewTemplate()
                .withNewMetadata()
                    .addToLabels("app", "nginx")
                .endMetadata()
                .withNewSpec()
                    .addNewContainer()
                        .withName("nginx")
                        .withImage("nginx:1.7.9")
                        .addNewPort()
                            .withContainerPort(80)
                        .endPort()
                    .endContainer()
                .endSpec()
            .endTemplate()
            .endSpec()
        .build();
    

    How the watch operation functions

    Fabric8 Kubernetes Client also provides watch functionality that you can use to observe all the events related to a particular resource. KubernetesClient uses the WebSocket protocol to create watch connections:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      Watch watch = client.services()
          .inNamespace("default")
          .watch(new Watcher<>() {
            @Override
            public void eventReceived(Action action, Service service) {
              logger.info("{} {}", action.name(), service.getMetadata().getName());
            }
    
            @Override
            public void onClose(WatcherException e) {
              logger.info("Watch closing {}", e.getMessage());
            }
          });
    
      Thread.sleep(10 * 1000L);
    
      watch.close();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new RuntimeException(e);
    }
    

    Although Fabric8 Kubernetes Client's watch functionality is quite robust, I recommend using informers while creating applications that tend to monitor the state of Kubernetes objects for a long time (e.g., Kubernetes Operators). We will discuss this in more detail in a future article in this series.

    Use patch operations to update objects

    It is also possible to update existing Kubernetes objects using a patch operation. Fabric8 Kubernetes Client provides patch operations using Java objects and plain JSON strings.

    For example:

    try (KubernetesClient client = new KubernetesClientBuilder().build()) {
      client.services()
          .inNamespace("default")
          .withName("my-service")
          .patch(PatchContext.of(PatchType.STRATEGIC_MERGE), "{\"metadata\":{\"annotations\":{\"foo\":\"bar\"}}}");
    }
    

    Learn more about programming Kubernetes in Java

    This article demonstrated how to use Fabric8 Kubernetes Client and basic operations. You can find the code in this GitHub repository. The next article, Programming Kubernetes custom resources in Java, describes how to interact with Kubernetes custom resources using its REST API in Java and the Fabric8 Kubernetes Java client.

    For more information, check out the Fabric8 Kubernetes Client GitHub page or read the cheat sheet. Feel free to follow the project on these channels:

    • StackOverflow
    • Twitter
    • Gitter Chat
    Last updated: January 20, 2023

    Related Posts

    • What's your favorite Kubernetes feature? Hear from the experts

    • Kubectl: Developer tips for the Kubernetes command line

    • What's new in Fabric8 Kubernetes Java client 4.12.0

    Recent Posts

    • A day in the life of an NVIDIA H100 on Red Hat OpenShift 5

    • Migrate BuildConfigs to builds for Red Hat OpenShift with one plug-in install

    • Run Red Hat Enterprise Linux CoreOS on NVIDIA BlueField DPUs

    • Agent harness engineering: Separating model capabilities from enforcement

    • What's new for developers in Red Hat Enterprise Linux 10.3 and 9.9

    What’s up next?

    This ebook will show you how to modernize traditional, monolithic Java-based applications into cloud-native models with Kubernetes.

    Get the e-book
    Red Hat Developers logo

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    Red Hat Developer

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility
    Ask AI