实战Spring Boot 2.0系列(一) - 使用Gradle构建Docker镜像

前言

通常我们使用 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

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值