前言
通常我们使用 Dockerfile
来构建项目的 Docker
镜像。但是也有使用 gradle
在编译项目的时候一起把镜像给 构建 并 上传 的需求。本文将会讲解如何使用 gradle
编写并配置 Dockerfile
并生成 镜像。
正文
1. 创建项目
利用 Spring Initializer
创建一个 gradle
项目 spring-boot-gradle-for-docker
,创建时添加一个 web
依赖。得到的初始 build.gradle
如下:
buildscript {
ext {
springBootVersion = '2.0.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'io.ostenant.springboot.sample'
version = '1.0'
sourceCompatibility = 1.8
repositories {
mavenCentral()
jcenter()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
2. 配置入口类
为了方便容器部署的测试,在 Spring Boot
启动类上配置一个控制器,响应当前的系统时间。
@RestController
@SpringBootApplication
public class Application {
private ThreadLocal<SimpleDateFormat> threadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"));
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@GetMapping("/")
public String retrieveTime() {
return threadLocal.get().format(new Date());
}
}
3. 添加插件
这里使用 gradle-docker
插件 来实现 docker
镜像构建。这样,我们就可以直接在 Gradle
的脚本里配置 Dockerfile