Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat 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
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud 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

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • 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

    • Migrating Ansible Automation Platform 2.4 to 2.5

    • Multicluster resiliency with global load balancing and mesh federation

    • Simplify local prototyping with Camel JBang infrastructure

    • Smart deployments at scale: Leveraging ApplicationSets and Helm with cluster labels in Red Hat Advanced Cluster Management for Kubernetes

    • How to verify container signatures in disconnected OpenShift

    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
    © 2025 Red Hat

    Red Hat legal and privacy links

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

    Report a website issue