Spring Boot Docker Tutorial

In this tutorial, we will learn step by step how to dockerize the Spring boot application. We will create a docker image for the Spring boot application and deploy it in a Docker container.

Video

Development Steps

  1. Create Spring boot application
  2. Build a simple REST API
  3. Create Dockerfile
  4. Build Docker Image
  5. Run Docker Image in a Container
  6. Demo

1. Create Spring boot application

Spring Boot provides a web tool called Spring Initializer to bootstrap an application quickly. Just go to https://start.spring.io/ and generate a new spring boot project.

Use the below details in the Spring boot creation:

Project Name: springboot-docker-demo

Project Type: Maven

Choose dependencies: Spring Web

Package name: net.javaguides.springboot

Packaging: Jar

Here is the pom.xml file for your reference:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>net.javaguides</groupId>
	<artifactId>springboot-docker-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-docker-demo</name>
	<description>Demo project for Spring Boot and Docker</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

</project>

2. Build a simple REST API

Let's create a simple REST API to test our Spring boot application deployment in a docker container.

Let's open SpringbootDockerDemoApplication and add the following content to it:
package net.javaguides.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SpringbootDockerDemoApplication {

	@GetMapping("/welcome")
	public String welcome(){
		return "Spring Boot Docker Demo";
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringbootDockerDemoApplication.class, args);
	}
}
Use the following command to maven build this project:
mvn package
Once maven build success, go target folder and you will be able to see the springboot-docker-demo-0.0.1-SNAPSHOT.jar generated:

3. Create Dockerfile

Next step, go to the project root directory and create a file named Dockerfile and the following content to it:
# define base docker image
FROM openjdk:11
LABEL maintainer="javaguides.net"
ADD target/springboot-docker-demo-0.0.1-SNAPSHOT.jar springboot-docker-demo.jar
ENTRYPOINT ["java", "-jar", "springboot-docker-demo.jar"]
FROM: A docker image can use another image available in the docker registry as its base or parent image. In the above example, we use the openjdk:11 image as our base image.

LABEL: The LABEL instruction is used to add metadata to the image. In the above Dockerfile, we have added some info about the maintainer of the image through LABEL instruction.

ADD: The ADD instruction is used to copy new files and directories to the docker image.

ENTRYPOINT: This is where you configure how the application is executed inside the container.

4. Build Docker Image

Now that we have defined the Dockerfile, let’s build a docker image for our application.

Use the below command to build the docker image:
docker build -t springboot-docker-demo:latest .
The file path . defines the location of the Dockerfile in the current directory, and the -t argument tags the resulting image, where the repository name is the springboot-docker-demo and the tag is the latest.

After the build is successfully finished, we can check to see if it appears in the list of docker images available locally. To do so, we can execute the below command.
docker images
Output:
rameshfadatare@Rameshs-MacBook-Air springboot-docker-demo % docker images
REPOSITORY               TAG       IMAGE ID       CREATED          SIZE
springboot-docker-demo   latest    8d61ab5ecfb1   36 seconds ago   667MB
docker-demo              latest    09c04b790f98   3 hours ago      667MB

5. Run Docker Image in a Container

Once we build the docker image, next we will run our docker image in a docker container.

Let's use the following command to run the docker image:
docker run -p 8081:8080 springboot-docker-demo
The -p argument establishes a port mapping from 8080 to 8081. The springboot-docker-demo is a docker image name.

Once docker image running in a container, you will see below output:
rameshfadatare@Rameshs-MacBook-Air springboot-docker-demo % docker run -p 8081:8080 springboot-docker-demo

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.4)

2021-09-03 10:10:38.293  INFO 1 --- [           main] n.j.s.SpringbootDockerDemoApplication    : Starting SpringbootDockerDemoApplication v0.0.1-SNAPSHOT using Java 11.0.12 on 520f1f1ab260 with PID 1 (/springboot-docker-demo.jar started by root in /)
2021-09-03 10:10:38.311  INFO 1 --- [           main] n.j.s.SpringbootDockerDemoApplication    : No active profile set, falling back to default profiles: default
2021-09-03 10:10:42.814  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-09-03 10:10:42.868  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-09-03 10:10:42.870  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.52]
2021-09-03 10:10:43.116  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-09-03 10:10:43.117  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 4443 ms
2021-09-03 10:10:44.909  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-09-03 10:10:45.002  INFO 1 --- [           main] n.j.s.SpringbootDockerDemoApplication    : Started SpringbootDockerDemoApplication in 8.99 seconds (JVM running for 10.882)
2021-09-03 10:11:18.099  INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-09-03 10:11:18.104  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-09-03 10:11:18.127  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 23 ms

6. Demo

Open the browser and hit this link in a browser http://localhost:8081/welcome
You will see the below REST API response message in a browser:
Spring Boot Docker Demo

Comments

  1. Hi, I am using war file for my spring boot application. I am not understanding how to add entry point option for the DockerFile.
    Could you please help?

    ReplyDelete

Post a Comment

Leave Comment