This tutorial will show how to build Docker images of your Spring Boot applications leveraging the Cloud Native Buildpacks feature.
Cloud Native Buildpacks provide an efficient way to deliver, without any coding, Cloud applications. Inn our case, it will automatically generate for us the Dockerfile needed to pack a Spring boot application.
This feature is available in Spring Boot 2.3.0.M1 or later for both Maven and Gradle. Thanks to it, you can just type a single command and quickly get a sensible image into your Docker daemon.
Let’s have a look at an example using Maven. First create a new Spring Boot project with a minimal dependency. if you are using start.spring.io:
$ curl https://start.spring.io/starter.zip -d bootVersion=2.3.0.M1 -d dependencies=web -o demo.zip $ unzip demo.zip
If you are using Spring Initializr (https://start.spring.io/) just make sure you flag the correct release and dependency:
After unzipping the project, let’s plug a simple Controller in it to test it:
package com.example.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @RequestMapping("/") public String hello() { return "hello"; } }
Next ensure you have a local Docker installed and running:
service docker start
Then execute:
$ mvn spring-boot:build-image
With Gradle the equivalent command is:
$ gradle bootBuildImage
It will take a bit for all buildpacks to be
[INFO] Successfully built image 'docker.io/library/demo:0.0.1-SNAPSHOT'
Now you can run your image with:
$ docker run -it -p8080:8080 demo:0.0.1-SNAPSHOT
That’s all! enjoy running Spring Boot images with Docker!
Found the article helpful? if so please follow us on Socials