Try running a Kubernetes Job from Java


In fact, a Java wrapper library that calls the Kubernetes API is officially prepared, and you can operate Kubernetes relatively easily from a Java application.

This time, let's create a REST API that starts Job with Spring Boot.


Specifications of this app

  1. Execute the Job sample that calculates the pi in Official Documents
  2. Read Job definition from YAML file --client-java assumes JSON (GSON), so YAML-> JSON conversion and binding
  3. Add a date so that the Job name is unique
  4. Authentication uses the service account kubernetes config


Creating a project

curl -s \
    -d baseDir=k8s-job-sample \
    -d type=gradle-project \
    -d javaVersion=1.8 \
    -d dependencies=web,lombok | tar -xzvf -

Add dependency to build.gradle


Set up Job manifest


apiVersion: batch/v1
kind: Job
  name: pi
      - name: pi
        image: perl
        command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(100)"]
      restartPolicy: Never
  backoffLimit: 4

Bean definition

package com.example.demo;

import io.kubernetes.client.ApiClient;
import io.kubernetes.client.apis.BatchV1Api;
import io.kubernetes.client.util.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

public class DemoApplication {

    public static void main(String[] args) {, args);

    public Gson gson() {
        return new Gson();

    public Yaml yaml() {
        return new Yaml(new SafeConstructor());

    public ApiClient apiClient() throws IOException {
        return Config.fromConfig("/path/to/k8s-config.yaml");

    public BatchV1Api batchV1Api(ApiClient apiClient) {
        return new BatchV1Api(apiClient);



package com.example.demo;

import io.kubernetes.client.ApiException;
import io.kubernetes.client.apis.BatchV1Api;
import io.kubernetes.client.models.V1Job;
import io.kubernetes.client.models.V1ObjectMeta;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.Yaml;

public class JobController {
    private final BatchV1Api batchApi;
    private final ResourceLoader resourceLoader;
    private final Gson gson;
    private final Yaml yaml;
    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    public V1Job executeJob(@RequestParam(required = false, defaultValue = "default") String nameSpace)
            throws IOException, ApiException {

        V1Job job = loadJobFromYaml("job.yaml");

        V1ObjectMeta metaData = job.getMetadata();
        metaData.setName(String.format("%s-%s", metaData.getName(), dateTimeFormatter.format(;

        return batchApi.createNamespacedJob(nameSpace, job, null);

    private V1Job loadJobFromYaml(String fileName) throws IOException {
        Map jobManifest = (Map) yaml.load(
                resourceLoader.getResource(ResourceLoader.CLASSPATH_URL_PREFIX + fileName).getInputStream());

        return gson.fromJson(gson.toJson(jobManifest), V1Job.class);

Operation check

$ curl -X POST http://localhost:8080/jobs?nameSpace=develop

Recommended Posts

Try running a Kubernetes Job from Java
Run a batch file from Java
Try running Selenuim 3.141.59 in eclipse (java)
Try running Spring Boot on Kubernetes
Try running AWS X-Ray in Java
Try making a calculator app in Java
Try calling Nim from Java via JNI
If a person from Java learns PHP
GetInstance () from a @Singleton class in Groovy from Java
To become a programmer from a Java shop
Try Java 8 Stream
Try to create a bulletin board in Java
Try calling the CORBA service from Spring (Java)
I tried hitting a Java method from ABCL
Programming beginners learn PHP from a Java perspective-variables-
Create Scala Seq from Java, make Scala Seq a Java List
Try accessing the dataset from Java using JZOS
[Java] Get a random value from an array
Roughly try Java 9
Try debugging a Java program with VS Code
I tried running Java on a Mac terminal
Ssh connect using SSHJ from a Java 6 app
Try calling synchronized methods from multiple threads in Java
Submit a job to AWS Batch with Java (Eclipse)
How to jump from Eclipse Java to a SQL file
Call a method with a Kotlin callback block from Java
Try Easy Ramdom, a PropertyBase Testing tool for java
Try calling IBM Watson Assistant 2018-07-10 from the Java SDK.
Using the database (SQL Server 2014) from a Java program 2018/01/04
[Note] Create a java environment from scratch with docker
[Java] How to erase a specific character from a character string
I made a Wrapper that calls KNP from Java
Try to solve a restricted FizzBuzz problem in Java
Call a program written in Swift from Processing (Java)
Create a JAVA WEB application and try OMC APM
Try to build a Java development environment using Docker
Try building Java into a native module with GraalVM
A survey of the Kubernetes native Java framework Quarkus
Call Java from JRuby
java build a triangle
Access API.AI from Java
From Java to Ruby !!
Try sending a notification.
Try Java return value
Resolve CreateProcess error = 206 when running Java in a Windows environment
[Beginner] Try to make a simple RPG game with Java ①
[Java] How to convert a character string from String type to byte type
Run R from a tomcat-powered Java process on Amazon Linux
How to store a string from ArrayList to String in Java (Personal)
Easily get an integer from a system property in Java
Try developing a containerized Java web application with Eclipse + Codewind
Try Hello World using plain Java on a Docker container
Take a look at Kotlin from an Effective Java perspective
Get a non-empty collection from an Optional stream in java