当前位置 主页 > 网站技术 > 代码类 >

    使用Docker部署SpringBoot项目的实现方法

    栏目:代码类 时间:2020-01-07 18:07

    Docker 技术发展为微服务落地提供了更加便利的环境,使用 Docker 部署 Spring Boot 其实非常简单,这篇文章我们就来简单学习下。

    首先构建一个简单的 Spring Boot 项目,然后给项目添加 Docker 支持,最后对项目进行部署。

    一个简单 Spring Boot 项目

    在 pom.xml 中 ,使用 Spring Boot 2.0 相关依赖

    <parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.0.0.RELEASE</version>
    </parent>
    

    添加 web 和测试依赖

    <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>
    

    创建一个 DockerController,在其中有一个index()方法,访问时返回:Hello Docker!

    @RestController
    public class DockerController {
     
      @RequestMapping("/")
      public String index() {
        return "Hello Docker!";
      }
    }
    

    启动类

    @SpringBootApplication
    public class DockerApplication {
     
     public static void main(String[] args) {
     SpringApplication.run(DockerApplication.class, args);
     }
    }
    

    添加完毕后启动项目,启动成功后浏览器访问:http://localhost:8080/,页面返回:Hello Docker!,说明 Spring Boot 项目配置正常。

    Spring Boot 项目添加 Docker 支持

    在 pom.xml-properties中添加 Docker 镜像名称

    <properties>
     <docker.image.prefix>springboot</docker.image.prefix>
    </properties>
    

    plugins 中添加 Docker 构建插件:

    <build>
     <plugins>
     <plugin>
      <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>1.0.0</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>
       </resource>
      </resources>
      </configuration>
     </plugin>
     <!-- Docker maven plugin -->
     </plugins>
    </build>
    

    在目录src/main/docker下创建 Dockerfile 文件,Dockerfile 文件用来说明如何来构建镜像。

    FROM openjdk:8-jdk-alpine
    VOLUME /tmp
    ADD spring-boot-docker-1.0.jar app.jar
    ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]