How to Dockerize Your Spring Boot Application

How to Dockerize Your Spring Boot Application

This video explains how to dockerize your Spring Boot application (step by step) and run it in a container.

WordPress in Docker. Part 1: Dockerization

WordPress in Docker. Part 1: Dockerization

This entry-level guide will tell you why and how to Dockerize your WordPress projects.

This entry-level guide will tell you why and how to Dockerize your WordPress projects.

Spring Boot: Run and Build in Docker

Spring Boot: Run and Build in Docker

Spring Boot: Run and Build in Docker - We take a look at how to create Java and Spring Boot-based applications in a Docker container. It's gonna be a whale of a time!

Spring Boot: Run and Build in Docker - We take a look at how to create Java and Spring Boot-based applications in a Docker container. It's gonna be a whale of a time!

There are a lot of guides on “Docker for Java developers,” but most of them do not take care of small and efficient Docker images.

I have combined many resources on how to make a simple and fast Docker image containing any Spring Boot-like application.

My goals:

  • Create a single and portable Dockerfile (as general as possible).
  • Make Maven build inside Docker (no need to have Maven locally).
  • Don’t download any Maven dependencies repeatedly, if no changes in pom.xml (rebuilding image as fast as possible).
  • The final Docker image should contain only application itself (no source codes, no Maven dependencies required by Maven build, etc.)
  • The final image should be as small as possible (no full JDK required).
  • The application inside Docker should remain configurable as much as possible (with all Spring Boot configuration options).
  • Possibility to enable debugging (on demand).
  • Possibility to see log files.

The final image is designed for development purposes, but it does not contain any no-go production parts and it is fully configurable.

To see a working example, see  my GitHub project.
To fulfill a single portable Dockerfile requirement, I need to use Docker multi-stage builds.

It will have two main parts (stages):

  • Create a single and portable Dockerfile (as general as possible).
  • Make Maven build inside Docker (no need to have Maven locally).
  • Don’t download any Maven dependencies repeatedly, if no changes in pom.xml (rebuilding image as fast as possible).
  • The final Docker image should contain only application itself (no source codes, no Maven dependencies required by Maven build, etc.)
  • The final image should be as small as possible (no full JDK required).
  • The application inside Docker should remain configurable as much as possible (with all Spring Boot configuration options).
  • Possibility to enable debugging (on demand).
  • Possibility to see log files.
The Building Part of the Dockerfile
### BUILD image
FROM maven:3-jdk-11 as builder
# create app folder for sources
RUN mkdir -p /build
WORKDIR /build
COPY pom.xml /build
#Download all required dependencies into one layer
RUN mvn -B dependency:resolve dependency:resolve-plugins
#Copy source code
COPY src /build/src
# Build application
RUN mvn package

I have started from the official Maven image, so you may change this as you wish. The most interesting part is this:

RUN mvn -B dependency:resolve dependency:resolve-plugins

It downloads all dependencies required either by your application or by plugins called during a build process. Then all dependencies are a part of one layer. That layer does not change until any changes are found in the pom.xml file.

So the rebuilding is very fast and does not include downloading all the dependencies again and again.

The second option, how to download required dependencies, comes from the official Docker Maven site (when you have some problems with the previous variant):

RUN mvn -B -e -C -T 1C org.apache.maven.plugins:maven-dependency-plugin:3.0.2:go-offline

How to Customize Maven Settings

There are many situations where you need to change a default Maven setting for your customized build. To do that, you need to copy your settings.xml file into the image before you provide the builder image definition, For example:

FROM maven:3-jdk-11 as builder
#Copy Custom Maven settings
COPY settings.xml /root/.m2/

The Runtime Part of the Dockerfile
FROM openjdk:11-slim as runtime
EXPOSE 8080
#Set app home folder
ENV APP_HOME /app
#Possibility to set JVM options (https://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html)
ENV JAVA_OPTS=""

#Create base app folder
RUN mkdir $APP_HOME
#Create folder to save configuration files
RUN mkdir $APP_HOME/config
#Create folder with application logs
RUN mkdir $APP_HOME/log

VOLUME $APP_HOME/log
VOLUME $APP_HOME/config

WORKDIR $APP_HOME
#Copy executable jar file from the builder image
COPY --from=builder /build/target/*.jar app.jar

ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar app.jar" ]
#Second option using shell form:
#ENTRYPOINT exec java $JAVA_OPTS -jar app.jar $0 [email protected]

The runtime part starts with some necessary steps, i.e. exposing ports, setting up environments, and creating some useful folders. The most interesting part is related to copying a previously created jar file into our new image:

#Copy executable jar file from the builder image
COPY --from=builder /build/target/*.jar app.jar

I am copying from the builder image, see the param –from. For more information about copying files from other images, see the Docker documentation page.

As for the Spring Boot application, the created jar file is executable, so it is possible to run our application with the single command:

ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar app.jar" ]

To reduce Tomcat startup time there is a system property pointing to /dev/urandom.

There are other options for runing a Spring Boot application inside Docker. For more info, visit the official Spring guide.

How to Build and Run Spring Boot Application in Docker in One Step
docker build -t <image_tag> . &amp;&amp; docker run -p 8080:8080 <image_tag>

The above command will build your application with Maven and start it without any delay. This is the simplest way without any customizations. The file may come with some specific requirements, so here’s a couple of them.

Now you can visit the URL to get response from my GitHub example:

http://localhost:8081/customer/10

How to Debug?

My example uses Java 11, so there are some JVM options to enable debug mode:

docker build -t <image_tag> . && docker run -p 8080:8080 -p 5005:5005 --env JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 <image_tag>

You need to add the Docker environment variable, JAVA_OPTS, with JVM options and map the internal debugging port to the outside of the container: -p 5005:5005.

For Java 5-8 containers, use this JAVA_OPTS parameter:

JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

How to Setup Logging

The runtime container contains a folder called app/app/log with all the log files. This path could be easily mounted into your host:

docker build -t <image_tag> . && docker run -p 8080:8080 -v /opt/spring-boot/test/log:/app/log <image_tag>

How to Change the Application Configuration

The jar file contains the default configuration. To selectively override those values, you have many options. I will show you some of them.

Please note that all of the configurations are possible when using the exec form of the ENTRYPOINT. When using the shell form of the ENTRYPOINT, you need to pass all command line arguments manually:

ENTRYPOINT exec java $JAVA_OPTS -jar app.jar $0 [email protected]

Command Line Arguments

Spring Boot automatically accepts all command line arguments and these arguments are passed into the run command inside Docker:

docker build -t <image_tag> . && docker run -p 8080:8080 <image_tag> --logging.level.org.springframework=debug

System Properties

A similar way is using regular system properties:

docker build -t <image_tag> . && docker run -p 8080:8080 --env JAVA_OPTS=-Dlogging.level.org.springframework=DEBUG <image_tag>

Environment Variables

You may use environment variables instead of system properties. Most operating systems do not allow for period-separated key names, but you can use underscores instead (for example,  SPRING_CONFIG_NAME  instead of  spring.config.name ). Check the documentation page for more information.

docker build -t <image_tag> . && docker run -p 8080:8080 --env LOGGING_LEVEL_ORG_SPRINGFRAMEWORK=DEBUG <image_tag>

Mount Your Own Configuration File

You may have noticed that there is a VOLUME command for mounting a configuration folder:

docker build -t <image_tag> . && docker run -p 8080:8080 -v /opt/spring-boot/test/config:/app/config:ro <image_tag>

So your local folder /opt/spring-boot/test/config should contain the file application.properties. This is the default configuration file name and can be easily changed by setting the property spring.config.name.

That’s all for this post, but your requirements may vary in many ways. I tried to solve some of the most important conditions Java developers using Docker.

To see a working example, see  my GitHub project.
Originally published by Pavel Sklenar at https://dzone.com

Learn More

☞ Docker Mastery: The Complete Toolset From a Docker Captain

☞ Learn DevOps: The Complete Kubernetes Course

☞ Docker for the Absolute Beginner - Hands On

☞ Docker Technologies for DevOps and Developers

☞ Docker Swarm Mastery: DevOps Style Cluster Orchestration

Spring Boot Development With Docker for Beginners

Spring Boot Development With Docker for Beginners

Let's examine how to bring containers into your Spring Boot projects. Here, we use Docker to contain a Java REST backend, leaving OS worries behind.

In this post, I will cover how to set up your development environment to debug the Java REST backend that runs in a container.

Building the REST Application

I used the Spring Boot framework to rapidly develop the REST backend that manages products, customers, and orders tables used in the AtSea Shop. The application takes advantage of Spring Boot’s built-in application server, support for REST interfaces and ability to define multiple data sources. Because it was written in Java, it is agnostic to the base operating system and runs in either Windows or Linux containers. This allows developers to build against a heterogeneous architecture.

Project Setup

The AtSea project uses multi-stage builds, a new Docker feature, which allows me to use multiple images to build a single Docker image that includes all the components needed for the application. The multi-stage build uses a Maven container to build the application JAR file. The JAR file is then copied to a Java Development Kit image. This makes for a more compact and efficient image because the Maven is not included with the application. Similarly, the React storefront client is built in a Node image, and the compile application is also added to the final application image.

I used Eclipse to write the AtSea app. If you want info on configuring IntelliJ or Netbeans for remote debugging, you can check out the Docker Labs Repository. You can also check out the code in the AtSea app GitHub repository.

I built the application by cloning the repository and imported the project into Eclipse by setting the Root Directory to the project and clicking Finish

File > Import > Maven > Existing Maven Projects

Since I used Spring Boot, I took advantage of spring-devtools to do remote debugging in the application. I had to add the Spring Boot-devtools dependency to the pom.xml file.

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
</dependency>

Note that developer tools are automatically disabled when the application is fully packaged as a JAR. To ensure that devtools are available during development, I set the configuration to false in the spring-boot-maven build plugin:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludeDevtools>false</excludeDevtools>
            </configuration>
        </plugin>
    </plugins>
</build>	
	

This example uses a Docker Compose file that creates a simplified build of the containers specifically needed for development and debugging.

	
version: "3.1"
services:
  database:
    build: 
       context: ./database
    image: atsea_db
    environment:
      POSTGRES_USER: gordonuser
      POSTGRES_DB: atsea
    ports:
      - "5432:5432" 
    networks:
      - back-tier
    secrets:
      - postgres_password
  appserver:
    build:
       context: .
       dockerfile: app/Dockerfile-dev
    image: atsea_app
    ports:
      - "8080:8080"
      - "5005:5005"
    networks:
      - front-tier
      - back-tier
    secrets:
      - postgres_password
secrets:
  postgres_password:
    file: ./devsecrets/postgres_password
networks:
  front-tier:
  back-tier:
  payment:
    driver: overlay
	

The Compose file uses secrets to provision passwords and other sensitive information such as certificates — without relying on environmental variables. Although the example uses PostgreSQL, the application can use secrets to connect to any database defined by as a Spring Boot datasource. From JpaConfiguration.java:

public DataSourceProperties dataSourceProperties() {
        DataSourceProperties dataSourceProperties = new DataSourceProperties();
    // Set password to connect to database using Docker secrets.
    try(BufferedReader br = new BufferedReader(new FileReader("/run/secrets/postgres_password"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
         dataSourceProperties.setDataPassword(sb.toString());
     } catch (IOException e) {
        System.err.println("Could not successfully load DB password file");
     }
    return dataSourceProperties;
}	
	

Also note that the appserver opens port 5005 for remote debugging and that build calls the Dockerfile-dev file to build a container that has remote debugging turned on. This is set in the Entrypoint, which specifies transport and address for the debugger.

ENTRYPOINT ["java", 
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005","-jar", 
"/app/AtSea-0.0.1-SNAPSHOT.jar"]	
	
Remote Debugging

To start remote debugging on the application, run compose using the docker-compose-dev.yml file.

docker-compose -f docker-compose-dev.yml up --build
	
	

Docker will build the images and start the AtSea Shop database and appserver containers. However, the application will not fully load until Eclipse’s remote debugger attaches to the application. To start remote debugging, click on Run > Debug Configurations …

Select Remote Java Application, then press the new button to create a configuration. In the Debug Configurations panel, you give the configuration a name, select the AtSea project and set the connection properties for host and the port to 5005. Click Apply > Debug.

The appserver will start up:

appserver_1|2017-05-09 03:22:23.095 INFO 1 --- [main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
appserver_1|2017-05-09 03:22:23.118 INFO 1 --- [main] com.docker.atsea.AtSeaApp                : Started AtSeaApp in 38.923 seconds (JVM running for 109.984)	
	

To test remote debugging, set a breakpoint on ProductController.java where it returns a list of products.

You can test it using curl or your preferred tool for making HTTP requests:

curl -H "Content-Type: application/json" -X GET  http://localhost:8080/api/product/
	
	

Eclipse will switch to the debug perspective, where you can step through the code.

The AtSea Shop example shows how easy it is to use containers as part of your normal development environment using tools that you and your team are familiar with. Download the application to try out developing with containers or use it as a basis for your own Spring Boot REST application.

Thanks for reading !