There is a Getting Start article on Spring's official website, which introduces how to use Docker to publish Spring Boot applications. It is quite detailed, but some details are not mentioned, and the official website's entry manual is in the English version. Let’s reorganize and record it here, as a reference for friends with poor English, and leave yourself a memorandum.
Prepare
Required tools and operating environment:
Create a project
First of all, you need to create a Spring Boot project. Spring Tool Suite and IntelliJ IDEA both come with plug-ins to create. Another way is to create it from http://start.spring.io/. This method is recommended. After filling out Group Id and Artifact Id in the form, click the Generate Project button to generate it and import the downloaded project into your favorite IDE.
Modify the pom.xml file and add docker-maven-plugin:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.matrixstudio.springboot</groupId> <artifactId>docker</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>docker</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <docker.image.prefix>springio</docker.image.prefix> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- Docker maven plugin --> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>0.4.3</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <targetPath>/</targetPath> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resources> </configuration> </plugin> </plugins> </build></project>The docker-maven-plugin plugin is used to build Spring Boot projects into Docker images:
Open the DockerApplication.java file and modify it to the following content:
package org.matrixstudio.springboot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@SpringBootApplication@RestControllerpublic class DockerApplication { @RequestMapping("/") public String home() { return "Hello Docker World"; } public static void main(String[] args) { SpringApplication.run(DockerApplication.class, args); }} Compile and run
Run the Spring Boot project by executing the following command:
mvn package && java -jar target/docker-0.0.1-SNAPSHOT.jar
Open the browser and enter http://localhost:8080 . If "Hello Docker World" appears, it means that the run is successful.
Note: When running the above command, you need to download a lot of dependency packages from the official Maven repository. The domestic network is not stable and the download speed is slow. You can consider using a mirror site provided by a third party, such as Alibaba's Maven mirror repository. Add the following configuration to pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.matrixstudio.springboot</groupId> <artifactId>docker</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <!-- Dependencies --> ...... <!-- Build --> ...... <!-- Aliyun repository --> <repository> <id>central</id> <name>aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> </repository> </repository> </repository> </repository> </project>
Containerization project
First, make sure that Docker is installed on your machine. If your Docker is installed on a Linux server, you need to upload the above Spring Boot project to the server. The following steps assume that you are operating on a Linux environment.
Create a Dockerfile
Docker uses a file named Dockerfile to specify the image layer, so we first need to create a Dockerfile file and execute the following command to create the Dockerfile file:
sudo tee src/main/docker/Dockerfile <<-'EOF'FROM frolvlad/alpine-oraclejdk8:slimVOLUME /tmpADD docker-0.0.1-SNAPSHOT.jar app.jarRUN sh -c 'touch /app.jar'ENV JAVA_OPTS=""ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]EOF
Let's roughly explain the above command:
Build a Docker image
Run the following command to build the Docker image:
mvn package docker:build
After the build is completed, run the following command to view:
sudo docker images
The result is:
REPOSITORY TAG IMAGE ID CREATED SIZE
springio/docker latest 7e2ba2f7e81e 2 minutes ago 195 MB
frolvlad/alpine-oraclejdk8 slim 00d8610f052e 4 days ago 167 MB
You can see that the image we built has appeared, and the next step is to run the image.
Run Docker image
Execute the following command to run the Docker image built in the previous step:
sudo docker run -p 8080:8080 -t springio/docker
If nothing unexpected happens, you will see the following output:
. ____ _ __ _ /// / ___'_ __ _(_)_ __ __ _ / / / / ( ( )/___ | '_ | '_ | / / /` | / / / / / / / / / / / / / / | | | | | | | | | | | | | | | || (_| | ) ) ) ) ' |____| .__|| |_| |_| |_| |_/__, | / / / / / ==========================================____/=/_/_/ :: Spring Boot :: (v1.5.2.RELEASE)2017-03-08 03:34:59.434 INFO 6 --- [ main] omspringboot.DockerApplication : Starting DockerApplication v0.0.1-SNAPSHOT on 00eed53e6928 with PID 6 (/app.jar started by root in /)2017-03-08 03:34:59.445 INFO 6 --- [ main] omspringboot.DockerApplication : No active profile set, falling back to default profiles: default2017-03-08 03:34:59.752 INFO 6 --- [ main] cationConfigEmbeddedWebApplicationContext: Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4b9af9a9: startup date [Wed Mar 08 03:34:59 GMT 2017]; root of context hierarchy2017-03-08 03:35:03.755 INFO 6 --- [ main] sbcetTomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)2017-03-08 03:35:03.807 INFO 6 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat2017-03-08 03:35:03.821 INFO 6 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.112017-03-08 03:35:04.042 INFO 6 --- [ost-startStop-1] oaccC[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2017-03-08 03:35:04.043 INFO 6 --- [ost-startStop-1] ost-web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4303 ms2017-03-08 03:35:04.441 INFO 6 --- [ost-startStop-1] ost-bwservlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]2017-03-08 03:35:04.455 INFO 6 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]2017-03-08 03:35:04.457 INFO 6 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2017-03-08 03:35:04.468 INFO 6 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]2017-03-08 03:35:04.468 INFO 6 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]2017-03-08 03:35:05.110 INFO 6 --- [main] swsmmaRequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4b9af9a9: startup date [Wed Mar 08 03:34:59 GMT 2017]; root of context hierarchy2017-03-08 03:35:05.390 INFO 6 --- [ main] swsmmaRequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String org.matrixstudio.springboot.DockerApplication.home()2017-03-08 03:35:05.402 INFO 6 --- [ main] swsmmaRequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)2017-03-08 03:35:05.404 INFO 6 --- [ main] swsmmaRequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2017-03-08 03:35:05.512 INFO 6 --- [ main] oswshandler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-03-08 03:35:05.512 INFO 6 --- [ main] oswshandler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-03-08 03:35:05.639 INFO 6 --- [ main] oswshandler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-03-08 03:35:06.019 INFO 6 --- [ main] osjeaAnnotationMBeanExporter : Registering beans for JMX exposure on startup2017-03-08 03:35:06.168 INFO 6 --- [ main] sbcetTomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2017-03-08 03:35:06.183 INFO 6 --- [ main] omspringboot.DockerApplication : Started DockerApplication in 7.893 seconds (JVM running for 8.743)2017-03-08 03:35:56.728 INFO 6 --- [nio-8080-exec-1] occC[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'2017-03-08 03:35:56.728 INFO 6 --- [nio-8080-exec-1] osweb.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started2017-03-08 03:35:56.774 INFO 6 --- [nio-8080-exec-1] osweb.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 43 msExecute the following command to view the running Docker container:
sudo docker ps
You can see that there is a Docker container running:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES00eed53e6928 springio/docker "sh -c 'java $JAVA..." About a minute ago Up About a minute 0.0.0.0:8080->8080/tcp fervent_leavitt
Now enter http://localhost:8080 to view the "Hello Docker World" result.
If you want to stop the container, you can execute the following command:
sudo docker stop 00e
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.