How Dockerize a Spring Boot Java Application or Run Spring Boot Application on Docker

Hello folks,

In this post, we are going to create a spring boot application and run it inside a Docker container.

1. Create a spring boot application 


First, we need a simple spring boot application. We'll use "spring initializr" --> https://start.spring.io/ 


- Just choose WEB dependency and Generate the Project.
- Unzip the project files
- Open the pom.xml via IntelliJ (or if you are using eclipse import the project)



Now we may create a simple rest API. And run it.

code:

Test it, open the endpoint on your browser.
http://localhost:8080/hi


That's it. Now, you have your spring boot application.

Before building the application (or exporting the jar file). Just add this to you pom.xml to rename it.

spring-boot

Full pom.xml

Now you may create your jar file (mvn clean install)



TL;DR 

  • Create a Dockerfile (this will copy your jar application to the image)
  • Build your image : docker build . -t spring-boot-example
  • Run it. : docker run -i -p 8080:8080 -t spring-boot-example
You may find the project in here : 

2. Create a Dockerfile 

I'm using OpenJDK Java 8 for base. Use alpine versions whenever you may :)

3. Run Docker! 

- First open your terminal in the project directory.
- Then build the Docker image by this command :
docker build . -t spring-boot-example


And Just Run it!

docker run -i -p 8080:8080 -t spring-boot-example




If you face any issue while running it... it may be related with name of image so you may want to check the name of the image by running the command

docker images


You may check the browser again :)


Comments