This article demonstrates how to deploy a Spring Boot app into Docker Container.
To demonstrate the application for deploying Spring Boot, a simple Todo service built in Spring Boot 构建Rest服务实验手册(一) is used as an experimental example in this article. If you are not familiar with the relevant development, you can also download the complete code directly according to the guidelines of Spring Boot 构建Rest服务实验手册 -- 源码下载.
The steps of Deployment and Tool Selection
When building a Spring Boot application, it is common practice to package it directly into a jar package that already contains the project’s code, dependent libraries, and associated configuration files. The jar package is then copied to the specified location on the server. Run directly at startup
1 | java -jar <your application package name> |
Deploying to a Docker container uses a similar step, but it would be too tedious and not conducive to release automation if you had to manually execute the commands to build the image each time you deployed. So we use a maven plugin to help us with this repetitive task.
This article uses the docker-maven-plugin plugin。Official website。
Use pom .xml to configure and deploy
If you are developing a relatively simple program, you can directly take the method of adding a plugin in the pom .xml and configuring the build parameters entirely in the pom .xml.
Open the project’s pom.xml file and add docker-maven-plugin in the build-plugins section at the bottom of the file, as follows:
1 | <build> |
In the above code, lines 8 to 26 are newly added code related to Docker release. On lines 10 to 12, we name the plugin used (docker-maven-plugin) and its version.
In the next configuration, we specify:
imageName - The final resulting docker image, it is named: restful-starter
baseImage - Build on that image, which is equivalent to the FROM directive in Dockerfile
entryPoint - The startup code that names the container runtime, which is equivalent to the ENTRYPOINT directive in Dockerfile
After saving the changes, execute them at the command line:
1 | mvn -DskipTests clean package docker:build |
After the build is complete, execute the docker images command to see the built image:
1 | REPOSITORY TAG IMAGE ID CREATED SIZE |
Execute the following command to start the container:
1 | docker run --name springboot-starter -d -p 8080:8080 restful-starter |
Then visit
1 | http://localhost:8080/todo/ |
to see the results of the service execution。
If you need more fine-grained control during the build process, you can also continue to use Dockerfile。