Microservices are often built with the Spring Boot framework and deployed with Docker. This paper looks at two common options for Dockerizing Spring Boot applications. Throughout we will use a simple REST application as a running example.

We will use Spring Tool Suite to build the application, though neither the IDE nor the application matter all that much, as long as we have the pom file. We will assume that the reader has minimal knowledge of Docker, though as we shall see one of the options we will discuss, requires no knowledge of Docker. Here then is the REST controller:

Java

package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Application {
    @RequestMapping("/")
    public String home() {
        return "Hello from Spring Boot in Docker";
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

We build this into a fat jar in the target directory. The simplest way to Dockerize it is to stuff the fat jar into a container:

Dockerfile

FROM adoptopenjdk:11-jre-hotspot
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"

This turns out to be a very bad idea. To see why recall that every instruction of the Docker file creates a layer in the image. In this case, our application and all its dependencies are put in one layer. If we keep changing the application then the image is rebuilt from scratch every time even though the dependency jars rarely change. This leads to slow builds.

A better option is to observe the old software design principle and separate what changes from what stays the same. We can do this by putting the dependencies in the bottom layer and the application layer on top. Docker will then cache the dependency layer and every time we change the application and rebuild the image, the dependency layer will be retrieved from cache leading to faster builds.

So much for the throat clearing. For our first option, we consider a very traditional organization where the development team and the build team are separate; the developers don’t know anything about Docker and don’t want to know. The development team builds applications and give it to the build team to manage the builds and deployment.

dev and build team

#java #tutorial #microservices #docker #spring boot 2 #devops and microservices #dockerize

Two Ways to Dockerize Spring Boot Applications
3.40 GEEK