How to Run Java Microservices on OpenShift Using Source-2-Image

<strong>With Source-2-Image (S2I), you don't have to provide Kubernetes YAML templates or build Docker images, OpenShift will do it for you. Read on to see how it works!</strong>

With Source-2-Image (S2I), you don't have to provide Kubernetes YAML templates or build Docker images, OpenShift will do it for you. Read on to see how it works!

One of the reasons you might prefer OpenShift over of Kubernetes is the simplicity of running new applications. When working with plain Kubernetes you need to provide an already built image together with the set of descriptor templates used for deploying it. OpenShift introduces the Source-2-Image feature, which is used for building reproducible Docker images from application source code. With S2I, you don’t have to provide any Kubernetes YAML templates or build Docker images by yourself, OpenShift will do it for you. Let’s see how it works. The best way to test it locally is via Minishift. But the first step is to prepare our sample application’s source code.

1. Prepare the Application Code

I have already described how to run your Java applications on Kubernetes in one of my previous articles Quick Guide to Microservices with Kubernetes, Spring Boot 2.0 and Docker. We will use the same source code we used in that article, so you can to compare the different approaches. Our source code is available on GitHub in the **sample-spring-microservices-new **repository. We will modify the version used in Kubernetes a little by removing the Spring Cloud Kubernetes library and including some additional resources. The current version is available in the openshift branch.

Our sample system consists of three microservices which communicate with each other and use a Mongo database on the backend. Here’s the diagram that illustrates our architecture.

Every microservice is a Spring Boot application, which uses Maven as a build tool. After including spring-boot-maven-plugin it is able to generate a single fat jar with all the necessary dependencies, which is required by the source-2-image builder.


Every application includes starters for Spring Web, Spring Actuator, and Spring Data MongoDB for integration with our Mongo database. We will also include libraries for generating Swagger API documentation, and Spring Cloud OpenFeign for these applications, which calls REST endpoints exposed by other microservices.


Every Spring Boot application exposes a REST API for simple CRUD operations on a given resource. The Spring Data repository bean is injected into the controller.

public class EmployeeController {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeController.class);

    EmployeeRepository repository;

    public Employee add(@RequestBody Employee employee) {"Employee add: {}", employee);

    public Employee findById(@PathVariable("id") String id) {"Employee find: id={}", id);
        return repository.findById(id).get();

    public Iterable<Employee> findAll() {"Employee find");
        return repository.findAll();

    public List<Employee> findByDepartment(@PathVariable("departmentId") Long departmentId) {"Employee find: departmentId={}", departmentId);
        return repository.findByDepartmentId(departmentId);

    public List<Employee> findByOrganization(@PathVariable("organizationId") Long organizationId) {"Employee find: organizationId={}", organizationId);
        return repository.findByOrganizationId(organizationId);


The application expects to have environment variables pointing to the database name, user, and password.

    name: employee

Inter-service communication is realized through the OpenFeign declarative REST client. It is included in thedepartment and organization microservices.

@FeignClient(name = "employee", url = "${microservices.employee.url}")
public interface EmployeeClient {

    List<Employee> findByOrganization(@PathVariable("organizationId") String organizationId);


The address of the target service accessed by the Feign client is set inside the application.ymlfile. The communication is realized via OpenShift/Kubernetes services. The name of each service is also injected through an environment variable.

    name: organization
    url: http://${EMPLOYEE_SERVICE}:8080
    url: http://${DEPARTMENT_SERVICE}:8080

2. Running Minishift

To run Minishift locally you just have to download it from that site, copy minishift.exe (for Windows) to your PATH directory, and start using the minishift start command. For more details, you may refer to my previous article about OpenShift and Java applications, A Quick Guide to Deploying Java Apps on OpenShift. The current version of Minishift used during writing this article is 1.29.0.

After starting Minishift, we need to run some additional oc commands to enable source-2-image for Java apps. First, we add some privileges to user admin to be able to access the openshiftproject. In this project, OpenShift stores all the built-in templates and image streams used, for example as S2I builders. Let’s begin from enable admin-useraddon.

$ minishift addons apply admin-user

Thanks to that plugin we are able to login to Minishift as cluster admin. Now, we can grant role cluster-admin to user admin.

$ oc login -u system:admin
$ oc adm policy add-cluster-role-to-user cluster-admin admin
$ oc login -u admin -p admin

After that, you can login to web console using credentials admin/admin. You should be able to see the openshiftproject. But that’s not all. The image used for building runnable Java apps (openjdk18-openshift) is not available by default with Minishift. We can import it manually from Red Hat registry using the oc import-imagecommand or just enable ot and apply the xpaasplugin. I prefer the second option.

$ minishift addons apply xpaas

Now, you can go to the Minishift web console (for me, it’s available at the address, select the openshift project and then navigate to Builds -> Images. You should see the image stream redhat-openjdk18-openshift on the list.

The newest version of that image is 1.3. Surprisingly, it is not the newest version on OpenShift Container Platform. There you have version 1.5. However, the newest versions of builder images have been moved to, which requires authentication.

3. Deploying a Java App Using S2I

We are finally able to deploy our app on Minishift with S2I builder. The application source code is ready, and the same with the Minishift instance. The first step is to deploy an instance of MongoDB. It is very easy with OpenShift, because the Mongo template is available in a built-in service catalog. We can provide our own configuration settings or left default values. What’s important for us, OpenShift generates a secret which is, by default, available under the name mongodb.

The S2I builder image provided by OpenShift may be used through the image stream redhat-openjdk18-openshift. This image is intended for use with Maven-based Java standalone projects that are run via the main class, for exam,ple Spring Boot applications. If you would not provide any builder while creating a new app, the type of application is auto-detected by OpenShift and the source code written Java it will be deployed on the WildFly server. The current version of the Java S2I builder image supports OpenJDK 1.8, Jolokia 1.3.5, and Maven 3.3.9-2.8.

Let’s create our first application on OpenShift. We begin from the employee microservice. Under normal circumstances, each microservice would be located in a separate Git repository. In our sample, all of them are placed in the single repository, so we have to provide the location of the current app by setting the parameter as --context-dir. We will also override the default branch to openshift, which has been created for the purposes of this article.

$ oc new-app redhat-openjdk18-openshift:1.3~ --name=employee --context-dir=employee-servic

All our microservices are connecting to the Mongo database, so we also have to inject connection settings and credentials into the application pod. This can be achieved by injecting a mongodb secret into theBuildConfigobject.

$ oc set env bc/employee --from="secret/mongodb" --prefix=MONGO_

BuildConfig is one of the OpenShift objects created after running the command, oc new-app. It also creates DeploymentConfig with a deployment definition, Service, and ImageStream with the newest Docker image of the application. After creating the application, a new build is running. First, it downloads the source code from the Git repository, then it builds it using Maven, assembles the build results into the Docker image, and, finally, saves the image in the registry.

Now, we can create the next application, department. For simplification, all three microservices are connecting to the same database, which is not recommended under normal circumstances. In that case, the only difference between the department and employee apps is the environment variable EMPLOYEE_SERVICE is set as a parameter on the oc new-app command.

$ oc new-app redhat-openjdk18-openshift:1.3~ --name=department --context-dir=department-service -e EMPLOYEE_SERVICE=employee

Here we do the same as before: we inject the mongodb secret into the BuildConfig object.

$ oc set env bc/department --from="secret/mongodb" --prefix=MONGO_

A build is started just after we create the new application, but we can also start it manually by executing the following command:

$ oc start-build department

Finally, we are deploying the last microservice. Here are the appropriate commands.

$ oc new-app redhat-openjdk18-openshift:1.3~ --name=organization --context-dir=organization-service -e EMPLOYEE_SERVICE=employee -e DEPARTMENT_SERVICE=department
$ oc set env bc/organization --from="secret/mongodb" --prefix=MONGO_

4. Deep Look Into the OpenShift Objects We Created

The list of builds may be displayed on the web console under the section Builds -> Builds. As you can see in the picture below, there are three BuildConfig objects available, one for each application. The same list can be displayed using the oc command, oc get bc.

You can take a look at the build history by selecting one of the elements from the list. You can also start a new one by clicking the  Start Build button, as shown below.

We can always display the YAML configuration file with the BuildConfig definition. But it is also possible to perform a similar action using the web console. The following picture shows the list of environment variables injected from the mongodb secret into the the BuildConfig object.

Every build generates a Docker image with the application and saves it in a Minishift internal registry. This Minishift internal registry is available under the address The list of available image streams is available under the section Builds -> Images.

Every application is automatically exposed on ports 8080 (HTTP), 8443 (HTTPS), and 8778 (Jolokia) via services. You can also expose these services outside Minishift by creating an OpenShift Route using the oc exposecommand.

5. Testing the Sample System

To proceed with the tests, we should first expose our microservices outside Minishift. To do that, just run the following commands:

$ oc expose svc employee
$ oc expose svc department
$ oc expose svc organization

After that, we can access applications atthe address [http://${APP_NAME}-${PROJ_NAME}.${MINISHIFT_IP}](http://${APP_NAME}-${PROJ_NAME}.${MINISHIFT_IP} "http://${APP_NAME}-${PROJ_NAME}.${MINISHIFT_IP}"), as shown below.

Each microservice provides Swagger2 API documentation available at swagger-ui.html. Thanks to that, we can easily test every single endpoint exposed by the service.

It’s worth noting that every application is making use of three approaches to inject environment variables into the pod:

  1. It stores the version number in the source code repository inside the file .s2i/environment. The S2I builder reads all the properties defined inside that file and sets them as environment variables for the builder pod, and then the application pod. Our property name is VERSION, which is injected using Spring @Value, and set for the Swagger API (the code is below).
  2. I have already set the names of dependent services as the ENV vars while executing the command oc new-app for the department and organization apps.
  3. I have also inject the MongoDB secret into every BuildConfig object using the oc set env command.
String version;

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

public Docket swaggerApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(new ApiInfoBuilder().version(version).title("Department API").description("Documentation Department API v" + version).build());


Today, I’ve shown you that deploying your applications on OpenShift may be a very simple thing. You don’t have to create any YAML descriptor files or build Docker images by yourself to run your app. It is built directly from your source code. You can compare it with deployment on Kubernetes described in one of my previous articles A Quick Guide to Microservices with Kubernetes, Spring Boot 2.0 and Docker.

Originally published by Piotr Mińkowski at

Learn More

☞ Two Java Beginner Coding Tips

☞ Complete Java Masterclass

☞ Complete Step By Step Java For Testers

☞ Java Web Service Complete Guide - SOAP + REST + Buide App

☞ Selenium WebDriver with Java - Basics to Advanced& Interview

☞ Java Persistence: Hibernate and JPA Fundamentals

☞ Java Swing (GUI) Programming: From Beginner to Expert

☞ Java Basics: Learn to Code the Right Way

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language. This is the first course where we will study the Fundamentals of Java, and we will take you step by step until you acquire the bases of the Java language and you can start to study more advanced Java topics.

The content is divided into perfectly structured levels, each level supported by the previous one, with the aim of adding Java knowledge incrementally and so you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

We will also offer support for any doubts about the didactic material included in this Java Fundamentals course.

We manage a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to be studied, complemented by eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since As we know we can not do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises that will allow you to accelerate your eLearning learning. No loss of time in videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the Java professional and working world.

The Java Fundamentals course includes the following topics for study:

Lesson 1 - Starting with Java Technology

The amazing world of Java programming

What is Java technology (from a practical approach)

Our first Java program from scratch

Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for

Types of Data in Java and how they are classified

Management and Classification of operators in Java

Lesson 3 - Control statements in Java

Using the if-else structure and where to use it

Handling the switch structure and when applying it

Lesson 4 - Handling Loops in Java

Use of the for loop and its use

Using the while loop and how to apply it

Use of the do-while loop and when to use it

Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)

Handling Classes in Java

Use of Objects in Java

Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java

Use and call of functions in Java

Lesson 7 - Data Management in Java

Using Arrays in Java

Management of Matrices in Java

Lesson 8 - Inheritance in Java

Inheritance Management in Java

Use of superclasses and subclasses in Java

Final Level Laboratory

Final Exercise where everything learned in this Level is integrated

At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you on the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn how to program in Java
Basic knowledge
Basic knowledge of PC use
Basic management of an operating system such as Windows, Mac or Linux
It is not necessary to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Manage the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn the Control Statements and Loops in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrays in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To know more:

Java Microservices: Code Examples, Tutorials, and More

Java Microservices: Code Examples, Tutorials, and More

Microservices are replacing monoliths every day. So, let's explore how Java devs can put them to work with the help of their favorite frameworks

Originally published by Angela Stringfellow

Microservices are increasingly used in the development world as developers work to create larger, more complex applications that are better developed and managed as a combination of smaller services that work cohesively together for larger, application-wide functionality. Tools are rising to meet the need to think about and build apps using a piece-by-piece methodology that is, frankly, less mind-boggling than considering the whole of the application at once. Today, we’ll take a look at microservices, the benefits of using this capability, and a few code examples.

What Are Microservices?

Microservices are a form of service-oriented architecture style (one of the most important skills for Java developers) wherein applications are built as a collection of different smaller services rather than one whole app. Instead of a monolithic app, you have several independent applications that can run on their own and may be created using different coding or programming languages. Big and complicated applications can be made up of simpler and independent programs that are executable by themselves. These smaller programs are grouped together to deliver all the functionalities of the big, monolithic app.

Microservices captures your business scenario, answering the question “What problem are you trying to solve?” It is usually developed by an engineering team with only a few members and can be written in any programming language as well as utilize any framework. Each of the involved programs is independently versioned, executed, and scaled. These microservices can interact with other microservices and can have unique URLs or names while being always available and consistent even when failures are experienced.

What Are the Benefits of Microservices?

There are several benefits to using microservices. For one, because these smaller applications are not dependent on the same coding language, the developers can use the programming language that they are most familiar with. That helps developers come up with a program faster with lower costs and fewer bugs. The agility and low costs can also come from being able to reuse these smaller programs on other projects, making it more efficient.

Examples of Microservices Frameworks for Java

There are several microservices frameworks that you can use for developing for Java. Some of these are:

  • Spring Boot: This is probably the best Java microservices framework that works on top of languages for Inversion of Control, Aspect Oriented Programming, and others.
  • Jersey: This open-source framework supports JAX-RS APIs in Java is very easy to use.
  • Swagger: Helps you in documenting API as well as gives you a development portal, which allows users to test your APIs.

Others that you can consider include: Dropwizard, Ninja Web Framework, Play Framework, RestExpress, Restlet, Restx, and Spark Framework.

How to Create Using DropWizard

DropWizard pulls together mature and stable Java libraries in lightweight packages that you can use for your own applications. It uses Jetty for HTTP, Jersey for REST, and Jackson for JSON, along with Metrics, Guava, Logback, Hibernate Validator, Apache HttpClient, Liquibase, Mustache, Joda Time, and Freemarker.

You can setup Dropwizard application using Maven. How?

In your POM, add in a dropwizard.version property using the latest version of DropWizard.

    <dropwizard.version>LATEST VERSION</dropwizard.version>
<!--Then list the dropwizard-core library:-->

This will set up a Maven project for you. From here, you can create a configuration class, an application class, a representation class, a resource class, or a health check, and you can also build Fat JARS, then run your application.

Check out the Dropwizard user manual at this link. The GitHub library is here.

Sample code:

package com.example.helloworld;
import com.yammer.dropwizard.config.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
public class HelloWorldConfiguration extends Configuration {
    private String template;
    private String defaultName = "Stranger";
    public String getTemplate() {
        return template;
    public String getDefaultName() {
        return defaultName;
Microservices With Spring Boot

Spring Boot gives you Java application to use with your own apps via an embedded server. It uses Tomcat, so you do not have to use Java EE containers. A sample Spring Boot tutorial is at this link.

You can find all Spring Boot projects here, and you will realize that Spring Boot has all the infrastructures that your applications need. It does not matter if you are writing apps for security, configuration, or big data; there is a Spring Boot project for it.

Spring Boot projects include:

  • Spring IO Platform: Enterprise-grade distribution for versioned applications.
  • Spring Framework: For transaction management, dependency injection, data access, messaging, and web apps.
  • Spring Cloud: For distributed systems and used for building or deploying your microservices.
  • Spring Data: For microservices that are related to data access, be it map-reduce, relational or non-relational.
  • Spring Batch: For high levels of batch operations.
  • Spring Security: For authorization and authentication support.
  • Spring REST Docs: For documenting RESTful services.
  • Spring Social: For connecting to social media APIs.
  • Spring Mobile: For mobile Web apps.

Sample code:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
public class Example {
    String home() {
        return "Hello World!";
    public static void main(String[] args) throws Exception {, args);

Jersey RESTful framework is open source, and it is based on JAX-RS specification. Jersey’s applications can extend existing JAX-RS implementations and add features and utilities that would make RESTful services simpler, as well as making client development easier.

The best thing about Jersey is that it has great documentation that is filled with examples. It is also fast and has extremely easy routing.

The documentation on how to get started with Jersey is at this link, while more documentation can be found here.

A sample code that you can try:

package org.glassfish.jersey.examples.helloworld;
public class HelloWorldResource {
    public static final String CLICHED_MESSAGE = "Hello World!";
    public String getHello() {
        return CLICHED_MESSAGE;

Jersey is very easy to use with other libraries, such as Netty or Grizzly, and it supports asynchronous connections. It does not need servlet containers. It does, however, have an unpolished dependency injection implementation.

Play Framework

Play Framework gives you an easier way to build, create and deploy Web applications using Scala and Java. Play Framework is ideal for RESTful application that requires you to handle remote calls in parallel. It is also very modular and supports async. Play Framework also has one of the biggest communities out of all microservices frameworks.

Sample code you can try:

package controllers;
import play.mvc.*;
public class Application extends Controller {
    public static void index() {
    public static void sayHello(String myName) {

Restlet helps developers create fast and scalable Web APIs that adhere to the RESTful architecture pattern. It has good routing and filtering, and available for Java SE/EE, OSGi, Google AppEngine (part of Google Compute), Android, and other major platforms.

Restlet comes with a steep learning curve that is made worse by a closed community, but you can probably get help from people at StackOverflow.

Sample code:

package firstSteps;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
 * Resource which has only one representation. 
public class HelloWorldResource extends ServerResource {
    public String represent() {
        return "hello, world";

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Microservices

What is Microservices?

Build Spring Microservices and Dockerize Them for Production

Best Java Microservices Interview Questions In 2019

Build a microservices architecture with Spring Boot and Spring Cloud

Java and MicroProfile: Building microservices in style

Java and MicroProfile: Building microservices in style

Learn the steps required to design, build, deploy, and orchestrate a cloud native microservice architecture using Java and Eclipse MicroProfile. We’ll use Red Hat’s MicroProfile (former WildFly Swarm) implementation known as Thorntail, optimized for deployment to OpenShift and integrated with Azure services.

Thanks for watching

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Java Programming Masterclass for Software Developers

Selenium WebDriver with Java -Basics to Advanced+Frameworks

Java In-Depth: Become a Complete Java Engineer!

Best Java Microservices Interview Questions In 2019

Introduction to Java String Interview Questions and Answers

.NET or Java for Web Development

Built a simple word game in Java using JavaFX

Simplification and Automation in Java: Yesterday, Today and Tomorrow