preface

Usually we use Dockerfile to build the Docker image of the project. However, there is also a need to use Gradle to build and upload images together while compiling a project. This article will show you how to use Gradle to write and configure a Dockerfile and generate an image.

This series of articles

  1. Spring Boot 2.0 series 1 – Build Docker images using Gradle
  2. Spring Boot 2.0 Series ii – Global exception handling and testing
  3. Spring Boot 2.0 series (3) – Using @async to make asynchronous calls
  4. Spring Boot 2.0 series 4 – Use WebAsyncTask to handle asynchronous tasks
  5. Spring Boot 2.0 series 5 – Listener, Servlet, Filter, and Interceptor
  6. Spring Boot 2.0 series (vi) – Several implementations of single machine timing tasks

The body of the

1. Create projects

Create a Gradle project spring-boot-Gradle-for-docker using Spring Initializer. Add a web dependency when creating a Gradle project. The resulting initial build.gradle looks like this:

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')}Copy the code

2. Configure the entry class

To facilitate container-deployed testing, configure a controller on the Spring Boot Boot class that responds to the current system time.

@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(a) {
        return threadLocal.get().format(newDate()); }}Copy the code

3. Add plug-ins

Gradle-docker plug-in is used to build docker image. In this way, we can configure Dockerfile directly in Gradle scripts to build the image function.

Gradle-docker plug-ins have been uploaded to jCenter and MavenCentral. So you just need to add rely on se in dependencies. Transmode. Gradle: gradle – docker: 1.2 can use docker plug-in.

buildscript {
    ext {
        springBootVersion = '2.0.2. RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("Se. Transmode. Gradle: gradle - docker: 1.2")}}Copy the code

4. Application plug-ins

Add the following code to build.gradle

apply plugin: 'application'
apply plugin: 'docker'
Copy the code

By default, gradle-Docker adds a distDocker gradle task to build a docker image containing all the application files.

5. Configure the image construction information

5.1. The configuration group

group = 'io.ostenant.springboot.sample'
Copy the code

5.2. Configure the image name and version

jar {
    baseName = "spring-boot-gradle-for-docker"
    version = 1.0
}
Copy the code

The default tag of an image is: Project group/application name: Version number

tag = "${project.group}/${applicationName}:${tagVersion}"
Copy the code
  • Project. group: A standard Gradle property. If not defined, the plugin defaults to omitting ${project.group}.

  • ApplicationName: The name of the application when it is containerized.

  • TagVersion: An optional attribute that acts as a label for the mirror. The default value is project.version. If project.version is not specified, latest is used as the flag.

5.3. Configure basic Docker build information

distDocker {
    baseImage = "openjdk"
    maintainer = "harrison"
}
Copy the code

Where baseImage is equivalent to the FROM declared in Dockerfile. Maintainer specifies the Image maintainer based on which the Image is built. If a Registry address is declared, the plug-in can automatically push to that address after mirroring is generated. Other configurations include the Docker Hub address, username, and password.

The detailed configuration example is as follows:

docker {
    baseImage 'openjdk'
    maintainer 'harrison'
    useApi true
    hostUrl 'http://myserver:4243'
    apiUsername 'user'
    apiPassword 'password'
    apiEmail '[email protected]'
}
Copy the code

6. Add a task

After completing the basic configuration, we also need to add a task to perform the mirror build at Gradle compile time.

The plugin provides conversion methods to refer to the keyword syntax in Dockerfile, as shown in the following table.

Dockerfile keywords Gradle task method
ADD addFile(Closure copySpec)
addFile(String source, String dest)
addFile(File source, String dest)
CMD defaultCommand(List cmd)
ENTRYPOINT entryPoint(List entryPoint)
ENV setEnvironment(String key, String val)
EXPOSE exposePort(Integer port)
exposePort(String port)
RUN runCommand(String cmd)
USER switchUser(String userNameOrUid)
VOLUME volume(String… paths)
WORKDIR workingDir(String dir)

Here is the task configuration for the taskBuilder for this project

task dockerBuilder(type: Docker) {
    applicationName = jar.baseName
    tagVersion = jar.version
    volume('/tmp')
    addFile("${jar.baseName}-${jar.version}.jar"."app.jar")
    entryPoint(["java"."-Djava.security.egd=file:/dev/./urandom"."-jar".'app.jar'])
    exposePort(8080)
    doFirst {
        copy {
            from jar
            into stageDir
        }
    }
}
Copy the code

After y is built, Dockerfile and spring-boot-gradle-for-docker-1.0.jar files will appear under the build/docker folder in the root directory of the project. The task above is equivalent to the Dockerfile below.

FROM aglover/java8-pier
VOLUME ["/tmp"]
ADDSpring - the boot - gradle - for - docker - 1.0. Jar app. The jarENTRYPOINT ["java"."-Djava.security.egd=file:/dev/./urandom"."-jar"."app.jar"]
EXPOSE 8080
Copy the code

If you feel uncomfortable writing a Dockerfile replacement script in your task, you can also specify the path of the Dockfile file in your task and use the existing file to generate the image:

task buildDocker(type: Docker) {
    applicationName = jar.baseName
    tagVersion = jar.version
    dockerfile = file('Dockerfile')
    doFirst {
        copy {
            from jar
            into stageDir
        }
    }
}
Copy the code

File () specifies that the task uses a Dockerfile located at the root of the project to produce the image.

7. Compile and build the Docker image

Go to the project root directory and run gradle to package the build.

$ ./gradlew clean build dockerBuilder --info
Copy the code

Gradle first runs local tests, then packages the project, and builds the image from the Docker-Gradle plugin.

Wait for BUILD SUCCESSFUL to appear indicating that the task ran successfully. You can observe that the name of the mirror is

io.ostenant.springboot.sample/spring-boot-gradle-for-docker:1.0
Copy the code

Run Docker Images to view the local image to further verify that the image is successfully built.

The complete build.gradle configuration file is given below

buildscript {
    ext {
        springBootVersion = '2.0.2. RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("Se. Transmode. Gradle: gradle - docker: 1.2")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'application'
apply plugin: 'docker'


group = 'io.ostenant.springboot.sample'
version = '1.0'
sourceCompatibility = 1.8
targetCompatibility = 1.8
mainClassName = "io.ostenant.springboot.sample.Application"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

jar {
    baseName 'spring-boot-gradle-for-docker'
    version '1.0'
}

distDocker {
    baseImage 'openjdk'
    maintainer 'harrison'
}

task dockerBuilder(type: Docker) {
    applicationName = jar.baseName
    tagVersion = jar.version
    volume('/tmp')
    addFile("${jar.baseName}-${jar.version}.jar"."app.jar")
    entryPoint(["java"."-Djava.security.egd=file:/dev/./urandom"."-jar".'app.jar'])
    exposePort(8080)
    doFirst {
        copy {
            from jar
            into stageDir
        }
    }
}
Copy the code

8. Start the container with an image

Run the following command to start the container based on the image and expose the 8080 access port.

$ docker run -d- the name gradle boot - p - 8080:8080 IO. Ostenant. Springboot. Sample/spring - the boot - gradle - for - docker: 1.0Copy the code

Visit http://127.0.0.1:8080/, the page will output the current system time, as shown in the figure:

summary

Gradle-docker is a gradle-docker plugin that uses the docker Remote Api, docker Hub, and gradle-Docker Remote Api. You can use the GitHub address of this project to configure the image repository: github.com/Transmode/g… .


Welcome to pay attention to the technical public number: Zero one Technology Stack

This account will continue to share learning materials and articles on back-end technologies, including virtual machine basics, multithreaded programming, high-performance frameworks, asynchronous, caching and messaging middleware, distributed and microservices, architecture learning and progression.