本文演示了如何用 Docker、Gradle 来构建、运行、宣布来一个 Spring Boot 应用。
Docker 简介
Docker 是一个 Linux 容器打点东西包,具备“社交”方面,答允用户宣布容器的 image (镜像),并利用别人宣布的 image。Docker image 是用于运行容器化历程的方案,软件开发,在本文中,我们将构建一个简朴的 Spring Boot 应用措施。
有关 Docker 的具体先容,软件开发,可以移步至 《简述 Docker》。
前置条件
用 Gradle 构建项目
建设目次布局
项目标目次布局因切合 Gradle 的约定。
在 *nix 系统下执行 mkdir -p src/main/java/docker_spring_boot ,出产如下布局 :
└── src
└── main
└── java
└── com
└── waylau
└── docker_spring_boot
建设 Gradle 构建文件
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath('org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE')
// tag::build[]
classpath('se.transmode.gradle:gradle-docker:1.2')
// end::build[]
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
// tag::plugin[]
apply plugin: 'docker'
// end::plugin[]
// This is used as the docker image prefix (org)
group = 'gregturn'
jar {
baseName = 'docker-spring-boot-gradle'
version = '1.0.0'
}
// tag::task[]
task buildDocker(type: Docker, dependsOn: build) {
push = true
applicationName = jar.baseName
dockerfile = file('src/main/docker/Dockerfile')
doFirst {
copy {
from jar
into stageDir
}
}
}
// end::task[]
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
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:
package com.waylau.docker_spring_boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 主应用进口
* @author <a href="http://waylau.com">waylau.com</a>
* @date 2016年3月19日
*/
@SpringBootApplication
@RestController
public class Application {
@RequestMapping("/")
public String home() {
return "Hello Docker World."
+ "<br />Welcome to <a href='http://waylau.com'>waylau.com</a></li>";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
表明下上面的代码:
运行措施
利用 Gradle
编译:
gradle build
运行:
java -jar build/libs/docker-spring-boot-gradle-1.0.0.jar
会见项目
假如措施正确运行,欣赏器会见 http://localhost:8080/,可以看到页面 “Hello Docker World.” 字样。
将项目容器化
Docker 利用 Dockerfile 文件名目来指定 image 层,劳务派遣管理系统,
建设文件 src/main/docker/Dockerfile:
FROM frolvlad/alpine-oraclejdk8:slim VOLUME /tmp ADD docker-spring-boot-gradle-1.0.0.jar app.jar ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
表明下这个设置文件:
构建 Docker Image
执行构建成为 docker image:
gradle build buildDocker
运行