Orchestrating in Kubernetes using Spring Boot

W Chandra
3 min readFeb 22, 2022

This article is relevant to those who want to create and deploy docker images as Kubernetes deployments and services, dynamically.

Let’s assume you want to achieve multitenancy in your application. You have a codebase which you want to run for different scenarios, with different configurations and different databases. Kubernetes APIs can be a way to handle such scenarios.

Kubernetes APIs

Kubernetes API server is part of the control plane in Kubernetes architecture. It lets people execute commands and implement configurations such as a deployment, by making API calls. If the orchestrating application is inside the Kubernetes environment, it becomes very easy to create a deployment on the fly.

Kubernetes API using Spring Boot

Spring boot helps in reaching the K8 APIs via different libraries. One such library is fabric8io kubernetes-client. It is an opensource library which can be added to your spring boot project as maven dependency.

Creating a deployment using kubernetes-clinet

A K8 deployment configuration instance can be created using the DeploymentBuilder class of kubernetes-client dependency and an existing image.

Similarly a K8 service can be created using the ServiceBuilder instance

Now these deployment and service instances can be deployed in K8 environment using the DefaultKubernetesClient instance assuming we dare deploying in the same cluster where our orchestration application is running. We need to create the client instance, and apply the above created service and deployments

Creating new Docker image dynamically

Above mentioned Deployment and Service creation requires a pre existing docker image. If the image is not already present and needs to be created dynamically, another maven dependency, docker-java, can be used.

Creating an image using DockerClientBuilder needs a docker file available locally, that can be created dynamically as per requirement by editing the file. We need to refer this dynamically created Dockerfile while building the image. This image can be then referred in above deployment creation.

It is advised to take care of security while communicating with a docker daemon over internet using authentication as well as encryption.

Conclusion

Above mentioned maven dependencies provide a host of other features apart from running a service in K8 dynamically like monitoring and destruction of services for example. If multitenancy needs to be achieved with minimal code change, fabric8io kubernetes-client along with dockerjava can be a solution.

Links

https://github.com/docker-java/docker-java

--

--