SpringBoot項目發布到伺服器,是一件很簡單的事情,但是發布到伺服器上docker啟動的tomcat容器中,有一些坑,需要注意。
下面完整的介紹一下:將SpringBoot web項目發布到docker啟動的tomcat容器中。
Spring項目發布,請參考:docker---(3)docker 發布spring web項目
SpringBoot入門,請參考:SpringBoot--從0開始學SpringBoot
Docker入門,請參考: Docker---從零開始學Docker
1.pom.xml
將打包方式改為war包
[java] view plain copy <packaging>war</packaging> 移除springBoot內建的tomcat,添加servlet-api
[java] view plain copy <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!--移除內建的tomcat--> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!--添加servlet-api--> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-servlet-api</artifactId> <version>8.0.36</version> <scope>provided</scope> </dependency> 在build中添加項目訪問路徑 [java] view plain copy <finalName>tweb</finalName>
(我第一次發布時,看了不下30篇文章,沒有提到這一點,發布了20多次都沒成功)
[java] view plain copy <build> <!--打包後的項目訪問名稱--> <finalName>tweb</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> 2.自訂一個Servletinitializer類,繼承SpringBootServletInitializer,用來啟動上下文
(和啟動類目錄同級)
[java] view plain copy package com.jd; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * Date 2018/1/30 * Description:啟動spring的上下文 */