Deploy Java App on Kubernetes Using Kustomize

In this article we are going to cover Deploy Java App on Kubernetes Using Kustomize.

Java applications are a cornerstone of enterprise software development, and Kubernetes offers a robust platform to host these applications at scale. In this article, we’ll explore how to deploy a Java app on Kubernetes using Kustomize. Kustomize allows you to manage Kubernetes configurations efficiently by leveraging overlays, generators, and transformers to customize resources.

Prerequisites

Before you start, ensure you have the following:

  • A Java application packaged as a JAR or WAR file.
  • Docker installed for building the application image.
  • A Kubernetes cluster (local or cloud-based).
  • kubectl and Kustomize installed on your local machine.
  • Basic understanding of Kubernetes and Java.

Java App Kustomize Directory structure

Deploy Java App on Kubernetes Using Kustomize 1

Step #1:Write a Simple Java Application

Create a simple Java application with the following code:

java-kubernetes-app/src/main/java/com/example/App.java:

package com.example;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class App {
    public static void main(String[] args) throws Exception {
        // Create an HTTP server listening on port 8080
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);

        // Create a context for the root path ("/")
        server.createContext("/", new MyHandler());

        // Set the executor to null (use default executor)
        server.setExecutor(null);

        // Start the server
        server.start();
        System.out.println("Server started on port 8080");
    }

    // Handler for the root path
    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            // Define the response message
            String response = "Hello from Java Kubernetes App!";

            // Send HTTP headers
            t.sendResponseHeaders(200, response.length());

            // Write the response to the output stream
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- Project Information -->
    <groupId>com.example</groupId>
    <artifactId>java-kubernetes-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>java-kubernetes-app</name>
    <description>A simple Java application for Kubernetes</description>

    <!-- Properties -->
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>4.13.2</junit.version> <!-- JUnit 4 version -->
    </properties>

    <!-- Dependencies -->
    <dependencies>
        <!-- JUnit 4 Dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Add other dependencies here if needed -->
        <!-- Example: Kubernetes Client Library -->
        <!--
        <dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
            <version>15.0.1</version>
        </dependency>
        -->
    </dependencies>

    <!-- Build Configuration -->
    <build>
        <plugins>
            <!-- Maven Compiler Plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>

            <!-- Maven Surefire Plugin (for running tests) -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <skipTests>false</skipTests> <!-- Set to true to skip tests -->
                </configuration>
            </plugin>

            <!-- Maven Shade Plugin (for creating an executable JAR) -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.App</mainClass> <!-- Replace with your main class -->
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Run the following command to create a JAR file:

mvn clean package
Deploy Java App on Kubernetes Using Kustomize 2

Step #2:Create a Docker Image Java App

Create a Dockerfile to containerize the Java application.

Dockerfile:

# Use an official OpenJDK runtime as a parent image
FROM openjdk:11-jre-slim

# Set the working directory
WORKDIR /app

# Copy the JAR file into the container
COPY target/java-kubernetes-app-1.0-SNAPSHOT.jar /app/java-kubernetes-app.jar

# Expose port 8080
EXPOSE 8080

# Run the application
CMD ["java", "-jar", "java-kubernetes-app.jar"]

Build the Docker image:

docker build -t harish981/java-kubernetes-app .
Deploy Java App on Kubernetes Using Kustomize 3

Log in to Docker Hub:

docker login

Push the image to Docker Hub:

docker push harish981/java-kubernetes-app:latest
Deploy Java App on Kubernetes Using Kustomize 4

This makes the image available for Kubernetes to pull from Docker Hub.

Verify the image is available on Docker Hub by visiting the Docker Hub website and checking your repository.

Deploy Java App on Kubernetes Using Kustomize 5

Step #3:Create Base Kubernetes Manifests for Java App

Set up a base configuration for your Kubernetes resources:

mkdir -p kustomize/base

Add the following YAML files in kustomize/base:

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: java-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: java-app
  template:
    metadata:
      labels:
        app: java-app
    spec:
      containers:
      - name: java-app
        image: harish981/java-kubernetes-app:latest # Use your Docker Hub image if pushed
        ports:
        - containerPort: 8080

service.yaml

apiVersion: v1
kind: Service
metadata:
name: java-app-service
spec:
selector:
app: java-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer

kustomization.yaml

resources:
- deployment.yaml
- service.yaml

Step #4:Deploy Java Application on Kubernetes using kustomize

Deploy the application to the cluster using Kustomize:

kubectl apply -k base/
Deploy Java App on Kubernetes Using Kustomize 6

Verify the deployment:

kubectl get pods
Deploy Java App on Kubernetes Using Kustomize 7

Step #5:Access Java App on Kubernetes

To access your application, use the following kubectl port-forward command:

kubectl port-forward --address 0.0.0.0 svc/java-app-service 8888:80
Deploy Java App on Kubernetes Using Kustomize 8

This command forwards traffic from your local machine’s port 8888 to the Kubernetes service’s port 3000. You can now access your application in the browser at:

http://<your-ip>:8888

Replace <your-ip> with the IP address of your server.

Deploy Java App on Kubernetes Using Kustomize 9

Step #6:Clean Up

To delete the resources:

kubectl delete deployment java-app
kubectl delete svc java-app-service

Conclusion:

Deploying a Java app on Kubernetes using Kustomize makes managing configurations easier and more flexible. It allows you to customize deployments for different environments without changing the base setup, saving time and effort.

By following this guide, you can streamline your deployment process and ensure consistency across environments. Start using Kustomize to make your Kubernetes deployments more efficient and organized.

Related Articles:

Deploy NodeJS App on Kubernetes Using Kustomize

Reference:

kustomize official page

Harish Reddy

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap