DEV Community

Cover image for The Simple Guide To Dockerizing Spring Boot
Abdulcelil Cercenazi
Abdulcelil Cercenazi

Posted on

The Simple Guide To Dockerizing Spring Boot

Why Should I Use A Docker Container? 🤨

  • They are a great replacement for Virtual Machines.
    • Why?
      • VMs are big in size (Gigabytes) and slow to run (1-5 mins).
        • Containers on the other hand:
          • Use a shared operating system, this means you can leave behind the useless 99.9 percent VM junk.
        • They are Linux processes that are isolated from each other.

enter image description here

  • Containers enable us to easily pack, ship, and run any application as a lightweight, portable, self-sufficient container, which can run virtually anywhere.

  • Containers are easy to deploy in the cloud.


Why Should I Wrap My App In A Docker Container 🤓

Well, to give our app all the benefits we've just described.


How To Do It? 👀

First, create a JAR file from your application.
Given that you are using Maven, run the following command in the pom.xml file directory

mvn clean package
Enter fullscreen mode Exit fullscreen mode

This will create a target directory, in which you can find your JAR file.

Then, create a Docker image using the JAR file we've just created.
Start by creating a file named Dockerfile

FROM openjdk:8  
ADD target/demo-0.0.1-SNAPSHOT.jar demo-0.0.1-SNAPSHOT.jar  
EXPOSE  8085  
ENTRYPOINT java -jar -Dspring.profiles.active=dev demo-0.0.1-SNAPSHOT.jar
Enter fullscreen mode Exit fullscreen mode

This means ☝️

  • Using the OpenJDK’s Java 8 machine (FROM)

  • Add this JAR to Docker’s host and name it demo-0.0.1-SNAPSHOT.jar (ADD)

  • Expose this app at port 8085 (EXPOSE)

  • And start the application using this command (ENTRYPOINT)


Then build the Docker image

 docker build -t demo .
Enter fullscreen mode Exit fullscreen mode

This means ☝️

  • Build an image and give it the tag demo.
  • Look for the Dockerfile in the current directory.

Finally, run the image.

docker run -p 8080:8085 demo
Enter fullscreen mode Exit fullscreen mode

This means ☝️

  • Run the image called demo, and map the requests coming from the host machine on port 8080 to the Docker port 8085.

How To Send Requests To Our App Inside Docker? 🤩

Simply send the requests local host on the port we've specified http://localhost:8080/ and they will mapped to the port 8085 inside Docker which will lead to our app.


Last Words ✍️

The Docker world is a wonderful and big place, I recommend you diver deeper into it.
Check out those great resources.
Full YouTube Tutorial💎
Dockerizing a Spring Boot Application⚓️


Code On GitHub💻

Top comments (2)

Collapse
 
jvmlet profile image
Furer Alexander • Edited

I would strongly suggest you to go through spring gradle/maven plugins reference guide to familiarize yourself with proper way of dockerizing spring boot application.

Collapse
 
jarjanazy profile image
Abdulcelil Cercenazi

Will do thanks for the suggestion