如何用 Docker、Gradle 来构建、运行、发布来一个 Spring Boot 应用。
Docker 简介
Docker 是一个 Linux 容器管理工具包,具备“社交”方面,允许用户发布容器的 image (镜像),并使用别人发布的 image。Docker image 是用于运行容器化进程的方案,在本文中,我们将构建一个简单的 Spring Boot 应用程序。
有关 Docker 的详细介绍,可以移步至 《简述 Docker》。
前置条件
- JDK 1.8+
- Gradle 2.3+
- Docker 最新版。有关 Docker 在的安装,可以参阅 《Docker 在 CentOS 下的安装、使用》。 如果你的电脑不是 Linux 系统,最好装个虚拟机,在虚拟机里面装个 Linux ,因为 Docker 的依赖 Linux。
用 Gradle 构建项目
创建目录结构
项目的目录结构因符合 Gradle 的约定。
在 *nix 系统下执行 mkdir -p src/main/java/docker_spring_boot ,生产如下结构 :
1 2 3 4 5 6 |
|
创建 Gradle 构建文件
build.gradle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
Spring Boot gradle plugin 提供了很多方便的功能:
它收集的类路径上所有 jar 文件,并构建成一个单一的、可运行的“über-jar”(德语,相关解释可以移步至 http://stackoverflow.com/questions/11947037/what-is-an-uber-jar),这使得它更方便地执行和传输服务。
编写 Spring Boot 应用
编写一个简单的 Spring Boot 应用 :
src/main/java/com/waylau/docker_spring_boot/Application.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
解释下上面的代码:
- 类用 @SpringBootApplication @RestController 标识,可用 Spring MVC 来处理 Web 请求。
- @RequestMapping 将 / 映射到 home() ,并将”Hello Docker World” 文本作为响应。
- main() 方法使用 Spring Boot 的 SpringApplication.run() 方法来启动应用。
运行程序
使用 Gradle
编译:
1 |
|
运行:
1 |
|
访问项目
如果程序正确运行,浏览器访问 http://localhost:8080/,可以看到页面 “Hello Docker World.” 字样。
将项目容器化
Docker 使用 Dockerfile 文件格式来指定 image 层,
创建文件 src/main/docker/Dockerfile:
1 2 3 4 |
|
解释下这个配置文件:
- VOLUME 指定了临时文件目录为/tmp。其效果是在主机 /var/lib/docker 目录下创建了一个临时文件,并链接到容器的/tmp。改步骤是可选的,如果涉及到文件系统的应用就很有必要了。/tmp目录用来持久化到 Docker 数据文件夹,因为 Spring Boot 使用的内嵌 Tomcat 容器默认使用/tmp作为工作目录
- 项目的 jar 文件作为 “app.jar” 添加到容器的
- ENTRYPOINT 执行项目 app.jar。为了缩短 Tomcat 启动时间,添加一个系统属性指向 “/dev/urandom” 作为 Entropy Source
构建 Docker Image
执行构建成为 docker image:
1 |
|
运行
运行 Docker Image
1 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
访问项目
如果程序正确运行,浏览器访问 http://localhost:8080/,可以看到页面 “Hello Docker World.” 字样。
推送 image 到 Docker Hub
首先,你在 Docker Hub 要有注册账号,且创建了相应的库;
其次,docker 推送前,先要登录,否则报unauthorized: access to the requested resource is not authorized的错误
执行:
1 |
|
输出为:
1 2 3 4 5 6 |
|
执行推送
1 |
|
1 2 3 4 5 6 7 8 |
|
镜像加速器
Docker Hub 在国外,有时候拉取 Image 极其缓慢,可以使用国内的镜像来实现加速
阿里云
1 2 |
|
其中 https://yourlocation.mirror.aliyuncs.com 是您在阿里云注册后的专属加速器地址:
DaoCloud
1 2 |
|
其中 http://your-id.m.daocloud.io 是您在 DaoCloud 注册后的专属加速器地址:
源码
获取项目源码, https://github.com/waylau/docker-demos 中的 samples/spring-boot-gradle
获取项目镜像, 执行
1 |
|
参考引用
- http://spring.io/guides/gs/spring-boot-docker/
- https://hub.docker.com/r/waylau/docker-spring-boot-gradle/