Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Getting started with the fabric8 Kubernetes Java client

May 20, 2020
Rohan Kumar
Related topics:
JavaCI/CDDevOpsKubernetes

Share:

    Fabric8 has been available as a Java client for Kubernetes since 2015, and today is one of the most popular client libraries for Kubernetes. (The most popular is client-go, which is the client library for the Go programming language on Kubernetes.) In recent years, fabric8 has evolved from a Java client for the Kubernetes REST API to a full-fledged alternative to the kubectl command-line tool for Java-based development.

    Fabric8 is much more than a simple Java Kubernetes REST client. Its features include a rich domain-specific language (DSL), a model for advanced code handling and manipulation, extension hooks, a mock server for testing, and many client-side utilities. In addition to hooks for building new extensions, the fabric8 Kubernetes Java client has extensions for Knative, Tekton, Kubernetes Service Catalog, Red Hat OpenShift Service Catalog, and Kubernetes Assertions.

    Kubernetes client

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

    OpenShift client

    <dependency>  
      <groupId>io.fabric8</groupId>  
      <artifactId>openshift-client</artifactId>
      <version>4.10.3</version>
    </dependency>
    

    Tekton client

    <dependency>  
      <groupId>io.fabric8</groupId>  
      <artifactId>tekton-client</artifactId>
      <version>4.10.3</version>
    </dependency>
    

    Knative client 

    <dependency>  
      <groupId>io.fabric8</groupId>  
      <artifactId>knative-client</artifactId>
      <version>4.10.3</version>
    </dependency>
    

    Istio client

    <dependency>  
      <groupId>me.snowdrop</groupId>
      <artifactId>istio-client</artifactId>  
      <version>1.6.5-Beta2</version>
    </dependency>
    
    Service Catalog client
    <dependency> 
      <groupId>io.fabric8</groupId>  
      <artifactId>servicecatalog-client</artifactId>  
      <version>4.10.3</version>  
      <type>bundle</type>
    </dependency>
    

    Note: The Istio client is not a direct part of the fabric8 repository, but is based on fabric8).

    Also, many popular projects use fabric8 Kubernetes client extensions, including Quarkus, Apache Camel, Apache Spark, and many more. See which projects work with this Kubernetes and OpenShift Java client here.

    Using fabric8 with Kubernetes

    Using fabric8 is straightforward, especially because it offers an API for accessing Kubernetes resources. To get started with the Java client, you just add it as a dependency in your Maven pom.xml:

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

    Alternatively, you could use build.gradle:

    dependencies {
        compile 'io.fabric8:kubernetes-client:4.10.3'
    }
    

    Next, we'll look at a couple of common examples.

    Example 1: Listing pods in a namespace

    Here's an example of listing all of the client pods in a namespace:

    try (KubernetesClient client = new DefaultKubernetesClient()) {
    
        client.pods().inNamespace("default").list().getItems().forEach(
                pod -> System.out.println(pod.getMetadata().getName())
        );
    
    } catch (KubernetesClientException ex) {
        // Handle exception
        ex.printStackTrace();
    }
    

    Example 2: Server authentication

    When you use DefaultKubernetesClient, it will try to read the ~/.kube/config file in your home directory and load information required for authenticating with the Kubernetes API server. You can override this configuration with the system property KUBECONFIG.

    If you are using DefaultKubernetesClient from inside a Pod, it will load ~/.kube/config from the ServiceAccount volume mounted inside the Pod. For a more complex configuration, you can simply pass a Config object inside DefaultKubernetesClient, like this:

    Config config = new ConfigBuilder()
            .withMasterUrl("https://api.rh-idev.openshift.com:443")
            .build();
    try (KubernetesClient client = new DefaultKubernetesClient(config)) {
    
        client.pods().inNamespace("default").list().getItems().forEach(
                pod -> System.out.println(pod.getMetadata().getName())
        );
    
    } catch (KubernetesClientException ex) {
        // Handle exception
        ex.printStackTrace();
    }
    

    Example 3: Creating a Simple Deployment:

    Suppose you want to build up a quick Deployment object and apply it onto Kubernetes Cluster. You can easily leverage on rich builder classes provided by fabric8 to construct your Kubernetes resources on the fly. Here is an example of building up a simple NginxDeployment:

    try (KubernetesClient client = new DefaultKubernetesClient()) {
        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();
    
        client.apps().deployments().inNamespace("default").createOrReplace(deployment);
    }
    

     

    Example 4: Loading your Kubernetes resource YAMLs into Java Objects:

    With Fabric8 Kubernetes Client, you can easily load your resource manifests into Java objects provided by it's Kubernetes Model. Suppose you have a ServiceYAML like this one:

    apiVersion: v1
    kind: Service
    metadata:
      name: my-service
    spec:
      selector:
        app: MyApp
      ports:
        - protocol: TCP
          port: 80
          targetPort: 9376

    Now in order to load this YAML object into a Kubernetes Service object. You need to do something like this:

    Service service = client.services()
            .load(LoadServiceYaml.class.getResourceAsStream("/test-svc.yml"))
            .get();

    Example 5: Doing CRUD operations for Kubernetes resource using Client:

    You can easily create, replace, edit, or delete your Kubernetes resources using Fabric8 Kubernetes Client API. We provide a rich DSL to achieve these operations. Here is an example of basic CRUD operations of a Deployment object:

        // Create
        client.apps().deployments().inNamespace("default").create(deployment);
    
        // Get
        Deployment deploy = client.apps().deployments()
                .inNamespace("default")
                .withName("deploy1")
                .get();
    
        // Update, adding dummy annotation
        Deployment updatedDeploy = client.apps().deployments()
                .inNamespace("default")
                .withName("deploy1")
                .edit()
                .editMetadata().addToAnnotations("foo", "bar").endMetadata()
                .done();
    
        // Deletion
        Boolean isDeleted = client.apps().deployments()
                .inNamespace("default")
                .withName("deploy1")
                .delete();
    
        // Deletion with some propagation policy
        Boolean bDeleted = client.apps().deployments()
                .inNamespace("default")
                .withName("deploy1")
                .withPropagationPolicy(DeletionPropagation.BACKGROUND)
                .delete();
    

     

    Learn more about fabric8

    Fabric8's development team consists of mostly Java developers, so a Java developer's perspective heavily influences this client. In this article, I've demonstrated just a few of fabric8's features for using Kubernetes APIs in a Java environment. For more examples, see the Kubernetes Java client examples repository. And for a deep dive into using fabric8, visit the Fabric8 Kubernetes Java Client Cheat Sheet.

    Last updated: July 17, 2020

    Recent Posts

    • How to run AI models in cloud development environments

    • How Trilio secures OpenShift virtual machines and containers

    • How to implement observability with Node.js and Llama Stack

    • How to encrypt RHEL images for Azure confidential VMs

    • How to manage RHEL virtual machines with Podman Desktop

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    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

    Red Hat legal and privacy links

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

    Report a website issue