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

    • 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

Using Dekorate to generate Kubernetes manifests for Java applications

March 17, 2021
Aurea Munoz Hernandez
Related topics:
DevOpsJavaKubernetesMicroservices
Related products:
Red Hat build of OpenJDKRed Hat build of QuarkusRed Hat JBoss Enterprise Application Platform

Share:

    To deploy an application on Kubernetes or Red Hat OpenShift, you first need to create objects to allow the platform to install an application from a container image. Then, you need to launch the application using a pod and expose it as a service with a static IP address. Doing all of that can be tedious, but there are ways to simplify the process.

    Kubernetes follows a declarative model, meaning that the user declares the desired application state and the cluster adjusts to match. Developers use files called manifests to describe the desired state. Manifests are typically defined in YAML or JSON files, which are communicated to the server through its REST API endpoint.

    Object formats are complex, with many fields to manipulate. It's a good idea to use a tool to help with creating the manifests. If you’re deploying Java applications, consider using Dekorate. Not only will it simplify your work as a developer, but it will also flatten your learning curve as you adopt Kubernetes.

    In this article, we'll use Dekorate to generate Kubernetes and OpenShift manifests for a generic Java application. Our example is a simple REST API application.

    Making Java projects easier with Dekorate

    The Dekorate project offers a collection of Java annotations and processors that automatically update Kubernetes manifests during your application’s compilation. Developers can customize the manifests using either annotations or properties in configuration files, without the hassle of editing individual XML, YAML, or JSON templates.

    Each annotation field maps to a property, so anything you specify with Java annotations can also be specified with properties, like so: dekorate.[simplified-annotation-name].[kebab-cased-property-name].

    The simplified name corresponds to the annotation’s class name, set as lowercase and stripped of suffixes (for example, application). You can find a complete reference of the supported properties here.

    Dekorate works with practically any Java build tool, including Maven, Gradle, Bazel, and sbt. To make life even easier, Dekorate also detects Java frameworks such as Spring Boot, Quarkus, and Thorntail, aligning the generated manifests accordingly. See the article How to use Dekorate to create Kubernetes manifests for more details.

    Note: Try out these examples if you want to play with Dekorate and discover the power of this fantastic tool for yourself.

    A simple REST application in Java

    Dekorate was designed to work with several Java frameworks, but it works just as well with plain Java. In the next sections, we'll use Dekorate to generate Kubernetes and OpenShift manifests for a generic Java application. Our example is a simple REST API. You can find the complete source code on GitHub.

    Deployment objects

    There are three Kubernetes objects Dekorate must generate to deploy an application. Each of these objects—and their OpenShift platform equivalents—plays a different role, as described in Table 1.

    Table 1: Objects used to deploy applications on Kubernetes and OpenShift.
    Kubernetes resource OpenShift resource Purpose
    Deployment DeploymentConfig Deploy and update applications as a pod.
    Service Service Provide an endpoint to access the pod as a service.
    Ingress Route Expose the service to clients outside of the cluster.

    Next, we'll review the steps for creating manifests with Dekorate so that they include the resources listed in Table 1.

    Configuring the manifests

    The easiest way to enable Dekorate is to add the corresponding JAR file to the classpath using a Maven dependency:

    <dependency>
         <groupId>io.dekorate</groupId>
         <artifactId>kubernetes-annotations</artifactId>
         <version>0.13.6</version>
    </dependency>

    Note: To keep your projects up to date, make sure you use the latest version of Dekorate.

    We need to specify that we would like to use Dekorate during the compilation phase of the Maven build life cycle. We can do this by adding the @Dekorate annotation to our main Java class. Here, we'll use the @KubernetesApplication annotation, which provides Kubernetes-specific configuration options. Edit the App.java class and add the annotation:

    @KubernetesApplication(
           . . .
           name = "hello-world-fwless-k8s",
           ...
    )

    This configuration creates a Deployment during the Maven compile goal. Dekorate uses the name parameter value to specify the resource name and populate the corresponding Kubernetes label (app.kubernetes.io/name). The .yml and .json manifest files are created in the target/classes/META-INF/dekorate/*.{json,yml} folder.

    As I mentioned in the introduction, Dekorate has a lightweight integration with build automation systems like Maven and Gradle. As a result, it can read the information from the tool configuration without bringing the build tool itself into the classpath. In our example, Dekorate would have used the name maven artifactId by default, but we overrode it with the annotation name parameter. Dekorate will add this name as Kubernetes labels to all resources, including images, containers, deployments, and services.

    The annotation port parameter

    The next step is to add the annotation port parameter. This lets us configure the Service endpoint and specify how it should be mapped with the Java HTTP port:

    @KubernetesApplication(
         ...
         ports = @Port(name = "web", containerPort = 8080),
         ...
    )

    Configuring the annotation port parameter adds the container port within the Deployment resource. That also generates a Service resource that allows access to the endpoint inside the Kubernetes cluster. Once again, if you use a framework like Spring Boot or Quarkus, you can bypass the port definition. Dekorate will use the existing framework metadata to generate the resources.

    The Ingress resource

    Having a service or endpoint available internally within the cluster is great. But to simplify your life, we will now configure an additional Ingress resource to make the service visible from your laptop. Both resources configure the proxy application (the Ingress controller) on the cluster to redirect external traffic and internal applications.

    Add the following expose parameter to the Dekorate annotation:

    @KubernetesApplication(
         ...
         expose = true,
         ...
    )

    Note: Remember that if you modify the annotation parameters, you can verify that the change is reflected in the manifest by triggering the compilation and checking the value gathered in the manifest file.

    Next, we'll add a host parameter to specify the local IP address or DNS-resolvable hostname to access the service:

    @KubernetesApplication(
         ...
         host = "fw-app.127.0.0.1.nip.io",
         ...
    )

    The host determines the host under which the application will be exposed. The Ingress controller running on the Kubernetes cluster uses the host to add a new rule to forward the requests addressed to that host to the corresponding service (for example, fw-app).

    The Deployment controller

    Finally, we need to tell the Deployment controller how to behave when a new image is available on the container registry. Setting the ImagePullPolicy parameter to Always ensures the controller will redeploy a new application as soon as a new container image is available:

    @KubernetesApplication(
         ...
         imagePullPolicy = ImagePullPolicy.Always,
         ...
    )

    Deploying the application

    To sum up, here's the Dekorate configuration using the Java annotation parameters we've discussed:

    @KubernetesApplication(
         name = "hello-world-fwless-k8s",
         ports = @Port(name = "web", containerPort = 8080),
         expose = true,
         host = "fw-app.127.0.0.1.nip.io",
         imagePullPolicy = ImagePullPolicy.Always
    )
    

    The generated manifests will appear in the target/classes/META-INF/dekorate folder as kubernetes.yml and kubernetes.json files.

    Alternatively, you can deploy the application on OpenShift using the OpenShift-specific dependency. Edit the pom.xml and add the following:

    <dependency>
        <groupId>io.dekorate</groupId>
        <artifactId>openshift-annotations</artifactId>
        <version>0.13.6</version>
    </dependency>

    Now, edit the App.java class and add the @OpenShiftApplication annotation:

    @OpenshiftApplication(
         name = "hello-world-fwless-openshift",
         ports = @Port(name = "web", containerPort = 8080),
         expose = true,
         imagePullPolicy = ImagePullPolicy.Always
    )

    This time, the manifests are named openshift.yml and openshift.json, and they will contain the OpenShift resources listed in Table 1: DeploymentConfig, Service, and Route.

    Configuring the image build strategy

    Running applications on Kubernetes and OpenShift requires that we package them into a container image that the pod will bootstrap at launch time. The process of packaging the source code within a container image, container registry, or image name is what we call the image build strategy. Dekorate currently supports several modes, depending on whether you use Kubernetes or OpenShift.

    Let's see how to configure the image build strategy with Dekorate.

    Docker (Kubernetes and OpenShift)

    To configure the Docker image build strategy with Dekorate to use the Docker client as a build tool locally, add the following dependency to the pom.xml file:

    <dependency>
      <groupId>io.dekorate</groupId>
      <artifactId>docker-annotations</artifactId>
    </dependency>

    If no registry is specified, Docker.io will be used by default. Recompile the project using Maven or Gradle. The generated manifest file will include the container image as part of the Deployment or DeploymentConfig resource:

    image: amunozhe/hello-world-fwless:1.0-SNAPSHOT

    These parameters will be used when you launch the tool responsible for building the container image. We'll examine this in more detail later.

    If you want to use an alternative image registry, edit the App.java class to add the @DockerBuild annotation to specify the registry where the client will push the image:

    @DockerBuild(registry = "quay.io")

    Source-to-Image (S2I) (OpenShift only)

    Source-to-Image (S2I) is a tool for building Docker-formatted images on OpenShift. With S2I, an OpenShift controller performs the image build, so you don’t have to build the container image locally.

    Until recently, Dekorate only supported S2I for image builds; the S2I resource BuildConfig is generated by Dekorate out of the box when the @OpenShiftApplication annotation is used. To bypass generating the BuildConfig resource, you can use the @S2iBuild(enabled=false) parameter.

    Generating the manifests

    Once we've configured the Kubernetes or OpenShift manifests, we can execute a mvn package command to generate the actual manifests. As already mentioned, two files will be created in the target/classes/META-INF/dekorate directory: kubernetes.json and kubernetes.yml.

    Now, we are ready to build the container image according to the specified image build strategy.

    Creating and sharing the container image

    Nowadays, many technologies exist to build container images locally. This example introduces two of them: Docker and Jib.

    Docker

    A Dockerfile is a text file used to build an image with Docker or Podman. It contains instructions for containerizing your Java application. A Dockerfile is provided with the example project's source code and is available in the project's root directory.

    Note: Dekorate does not generate Dockerfiles. It also doesn’t provide internal support for performing image builds and pushes.

    If you need to install the Docker client locally, you can download it here.

    Run the following command to build the image:

    docker build -f Dockerfile -t amunozhe/hello-world-fwless:1.0-SNAPSHOT .

    This image is only available within the Docker registry on your laptop. We need to push the image to an external image registry to allow Kubernetes or OpenShift to run it. For this example, we'll push the image to Docker Hub using my Docker Hub ID (amunozhe). You can register your own ID on the Docker Hub website or use another publicly-available registry like Red Hat Quay.

    Once you’re logged in to the registry, you can finally push the image to make it available for the cluster:

    docker push amunozhe/hello-world-fwless:1.0-SNAPSHOT

    Build and push the image via Dekorate

    Instead of manually executing the commands to build and push the Java container image, you can delegate the task to Dekorate, which uses hooks to support such features. This means you can perform all of the necessary steps with a single command:

    mvn clean package -Ddekorate.build=true  -Ddekorate.push=true

    Jib

    Jib simplifies the process of creating container images by letting you avoid writing a Dockerfile. You don’t even need to have a Docker client installed to create and publish container images with Jib. Using Jib (via a Maven plugin) is also nice because it catches any changes made to the application every time you build.

    To enable Jib, replace the docker-annotations dependency with jib-annotations in the pom.xml file:

    <dependency>
       <groupId>io.dekorate</groupId>
       <artifactId>jib-annotations</artifactId>
    </dependency>

    We'll use the @JibBuild annotation instead of @DockerBuild to configure the registry. Edit the application.java class to add the annotation:

    @JibBuild(registry = "docker.io")

    Run the following command to build and push the container image, taking advantage of the Dekorate hook:

    mvn clean package -Ddekorate.push=true

    Deploying the application

    Once the Kubernetes and OpenShift manifests are generated, and the image is pushed to an image registry, we can deploy the application on the cluster under the demo namespace.

    To create your microservice on a cloud platform, you must have access to an active Kubernetes or OpenShift cluster. Here is the command to execute for Kubernetes:

    kubectl create ns demo
    kubectl apply -f target/classes/META-INF/dekorate/kubernetes.yml -n demo

    And here's the one for OpenShift:

    oc new-project demo
    oc apply -f target/classes/META-INF/dekorate/openshift.yml
    

    Wait a few moments until the pod is created and accessible through the external URL registered as an Ingress or Route resource. You can verify that the application is ready to accept the request by checking to see if the pod status is RUNNING.

    Kubernetes users should use this command:

    kubectl get pods -n demo

    For OpenShift users, it is:

    oc project demo
    oc get pods

    Next, you need to get the URL to access the application in the browser. Use the following command for Kubernetes:

    kubectl get ingress -n demo
    NAME                     CLASS   HOSTS                      ADDRESS     PORTS   AGE
    
    hello-world-fwless-k8s   <none>  fw-app.127.0.0.1.nip.io    localhost   80      147m

    As you can see in the main Application class, the /api/hello path provides the endpoint. To check if the application is accessible, open your browser and go to http://fw-app.127.0.0.1.nip.io/api/hello. You should see the following message:

    Hello From k8s FrameworkLess world!

    Here is how to check the application with OpenShift:

    oc get route -n demo
    
    NAME                          HOST/PORT                                              PATH       PORT
    
    hello-world-fwless-openshift  hello-world-fwless-openshift-demo.88.99.12.170.nip.io   /         8080

    In the browser, go to http://hello-world-fwless-openshift-demo.88.99.12.170.nip.io/api/hello. You should see the following message:

    Hello from OpenShift FrameworkLess world!

    Conclusion

    As a developer, I love creating new features, improving user experiences, and discovering ways to deploy applications quickly and painlessly. As you've seen in this article, Dekorate makes writing Kubernetes or OpenShift manifests practically effortless.

    Last updated: February 11, 2024

    Recent Posts

    • GuideLLM: Evaluate LLM deployments for real-world inference

    • Unleashing multimodal magic with RamaLama

    • Integrate Red Hat AI Inference Server & LangChain in agentic workflows

    • Streamline multi-cloud operations with Ansible and ServiceNow

    • Automate dynamic application security testing with RapiDAST

    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