Spring Boot released its latest version 2.3.0 two days back (15 May 2020).
One major feature provided by this release is creating docker images of a spring boot app in a much more efficient way.
Prior to this , if you were to dockerize your spring boot app you need to take the jar generated by spring boot and build your docker image on top of it.
This is inefficient for two reasons as mentioned by the Spring team .
- The jar file is not unpacked .Docker images work best when they are unpacked. Running a packaged jar requires some overhead
- A jar file contains both the application code and their dependencies packed into a single layer . Docker image is built in layers and it works best when the application code and dependencies are built in separate layers . This way docker can cache the dependencies layer which won’t change often.
The above mentioned problems can be resolved using buildpacks to create images . Spring boot internally uses build packs to generate docker images starting version 2.3.0. All you have to do is run the below command once your application is built :
Here is a demo:
Prerequisite : Docker is installed
Step 1 : Create a spring boot project
I created a simple spring boot project using spring initializr and added a rest service in the project which returns the text “Hello World” .
Step 2: Run the maven command to generate the image
Run the below command :
That’s it ! A docker image has been created with the name dockerdemo:0.0.1-SNAPSHOT
Not even a Dockerfile required !
Step 3 : Run the docker image
Run the docker image using docker run command . I have run it at port no 8080.
Step 4 : Test the application
I used docker tools for windows to install docker in my machine . It installed a virtual box where docker runs . It has its own IP ( the default is 22.214.171.124). You can also get the IP using the command:
Hit the REST service using the above IP . I had created a GET service with the name /greet. Hit it with curl command
It returned the response text “Hello World”
It is working !
A containerised image has been created and run .
To run the above application on local host do port mapping in Oracle VM virtual box manager (installed along with docker toolbox) as below :
Open Oracle VM Virtual Box Manager .Go to default —> settings —> Network —> Adapter 1
Add a new port mapping with host IP 127.0.0.1 , port 8080 , guest IP 192.168.99.100 , guest port 8070 . ( the one with the name Docker rule below)
You can now hit your REST service on local host . This time I used the rest client tool POSTMAN ( works with curl command as well )
Hello World !