Docker与Jib(maven插件版)实战

时间:2022-09-29 18:05:05

欢迎访问我的GitHub

这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos

关于Jib

  • Java应用如果要运行在docker环境,就要制作包含该应用的docker镜像,Jib就是用来制作此镜像的的工具,有三种使用Jib的方法:
  1. Maven插件:jib-maven-plugin;
  2. Gradle插件:jib-gradle-plugin;
  3. Java库:Jib Core;
  • Jib的官网地址是:https://github.com/GoogleContainerTools/jib

  • 今天咱们要聊的是第一种:通过jib的maven插件将java应用构建成docker镜像;

实战环境信息

  1. 操作系统:CentOS Linux release 7.6.1810
  2. docker:1.13.1
  3. jdk:1.8.0_191
  4. maven:3.6.0
  • 接下来一起开发一个java应用,并使用jib的maven插件,来构建该应用对应的docker镜像;

源码下载

  • 如果您不打算写代码,也可以从GitHub上下载本次实战的源码,地址和链接信息如下表所示:
名称 链接 备注
项目主页 https://github.com/zq2599/blog_demos 该项目在GitHub上的主页
git仓库地址(https) https://github.com/zq2599/blog_demos.git 该项目源码的仓库地址,https协议
git仓库地址(ssh) git@github.com:zq2599/blog_demos.git 该项目源码的仓库地址,ssh协议
  • 这个git项目中有多个文件夹,本章的源码在hellojib文件夹下,如下图红框所示: Docker与Jib(maven插件版)实战

准备java应用

  • 准备一个最简单的springboot应用hellojib,用于实战构建docker镜像;
  • 该应用是基于maven构建的,启动类如下:
package com.bolingcavalry.hellojib;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HellojibApplication {

    public static void main(String[] args) {
        SpringApplication.run(HellojibApplication.class, args);
    }

}
  • 有一个controller用于后面验证服务是否正常:
package com.bolingcavalry.hellojib.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 普通的controller
 * @author: willzhao E-mail: zq2599@gmail.com
 * @date: 2019/6/29 20:21
 */
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "Hello, " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
}
  • 最重要的部分来了 ,pom.xml的内容如下,请注意注释:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>hellojib</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hellojib</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!--使用jib插件-->
            <plugin>
                <groupId>com.google.cloud.tools</groupId>
                <artifactId>jib-maven-plugin</artifactId>
                <version>1.3.0</version>
                <configuration>
                    <!--from节点用来设置镜像的基础镜像,相当于Docerkfile中的FROM关键字-->
                    <from>
                        <!--使用openjdk官方镜像,tag是8-jdk-stretch,表示镜像的操作系统是debian9,装好了jdk8-->
                        <image>openjdk:8-jdk-stretch</image>
                    </from>
                    <to>
                        <!--镜像名称和tag,使用了mvn内置变量${project.version},表示当前工程的version-->
                        <image>bolingcavalry/hellojib:${project.version}</image>
                    </to>
                    <!--容器相关的属性-->
                    <container>
                        <!--jvm内存参数-->
                        <jvmFlags>
                            <jvmFlag>-Xms4g</jvmFlag>
                            <jvmFlag>-Xmx4g</jvmFlag>
                        </jvmFlags>
                        <!--要暴露的端口-->
                        <ports>
                            <port>8080</port>
                        </ports>
                    </container>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • 上述xml中有以下几处需要注意: a. 插件的节点中增加了插件jib-maven-plugin的配置; b. from节点用来设置基础镜像,一般使用openjdk官方镜像,如果您想了解更多请参考《openjdk镜像的tag说明》; c. to节点用于指定镜像名称和tag; d. container节点用来设置容器的属性,例如对外暴露的端口、jvm参数等;

  • 完成了上述设置,就可以构建镜像了;

构建成tar文件

  • 还记得常用的docker到处到处命令么:

  • docker save 命令将本地仓库的docker镜像导出成tar格式的文件;

  • docker load 命令可以将tar格式的镜像文件导入到本地镜像仓库;

  • 利用Jib,我们可以将java应用做成docker镜像并生成tar格式的文件,操作步骤如下:

  • 在上述java工程的pom.xml文件所在目录,执行以下命令:

mvn compile jib:buildTar
  • 构建成功后,控制台提示以下信息:
[root@centos7 hellojib]# mvn compile jib:buildTar
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.bolingcavalry:hellojib >---------------------
[INFO] Building hellojib 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ hellojib ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ hellojib ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- jib-maven-plugin:1.3.0:buildTar (default-cli) @ hellojib ---
[INFO]
[INFO] Containerizing application to file at '/root/temp/201906/29/hellojib/target/jib-image.tar'...
[INFO] The base image requires auth. Trying again for openjdk:8-jdk-stretch...
[INFO]
[INFO] Container entrypoint set to [java, -Xms4g, -Xmx4g, -cp, /app/resources:/app/classes:/app/libs/*, com.bolingcavalry.hellojib.HellojibApplication]
[INFO]
[INFO] Built image tarball at /root/temp/201906/29/hellojib/target/jib-image.tar
[INFO] Executing tasks:
[INFO] [==============================] 100.0% complete
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  16.521 s
[INFO] Finished at: 2019-06-30T21:43:32+08:00
[INFO] ------------------------------------------------------------------------
  • 去java工程的target目录下,发现生成了名为jib-image.tar的文件,如下图红框所示: Docker与Jib(maven插件版)实战

  • 在java工程的target目录下执行命令 docker load < jib-image.tar 即可将该tar文件中的镜像加载到本地镜像仓库:

[root@centos7 target]# docker load < jib-image.tar
2c8d31157b81: Loading layer [==================================================>] 50.07 MB/50.07 MB
ea20c4bf3aae: Loading layer [==================================================>] 4.932 MB/4.932 MB
51774d97c868: Loading layer [==================================================>]    221 B/221 B
51566e3f832b: Loading layer [==================================================>]   104 MB/104 MB
64c0b8425948: Loading layer [==================================================>] 14.91 MB/14.91 MB
e4c3b920750d: Loading layer [==================================================>]    240 B/240 B
8917d4e7f7b3: Loading layer [==================================================>] 1.034 kB/1.034 kB
Loaded image: bolingcavalry/hellojib:0.0.1-SNAPSHOT
  • 执行命令 docker images 可见镜像加载成功:
[root@centos7 target]# docker images
REPOSITORY                         TAG                         IMAGE ID            CREATED             SIZE
bolingcavalry/hellojib             0.0.1-SNAPSHOT              cf93bd81fbd5        49 years ago        505 MB
  • 可见通过jib生成的tar是正常的docker镜像文件,可以导入

验证镜像是否可用

  • 执行以下命令,即可启动容器:
docker run --rm -p 8080:8080 bolingcavalry/hellojib:0.0.1-SNAPSHOT
  • 控制台显示springboot的启动信息:
[root@centos7 target]# docker run --rm -p 8080:8080 bolingcavalry/hellojib:0.0.1-SNAPSHOT

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-06-30 13:56:50.969  INFO 1 --- [           main] c.b.hellojib.HellojibApplication         : Starting HellojibApplication on c08711533071 with PID 1 (/app/classes started by root in /)
2019-06-30 13:56:50.975  INFO 1 --- [           main] c.b.hellojib.HellojibApplication         : No active profile set, falling back to default profiles: default
2019-06-30 13:56:52.147  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-06-30 13:56:52.173  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-06-30 13:56:52.173  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-06-30 13:56:52.261  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-06-30 13:56:52.261  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1223 ms
2019-06-30 13:56:52.475  INFO 1 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-06-30 13:56:52.772  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-06-30 13:56:52.811  INFO 1 --- [           main] c.b.hellojib.HellojibApplication         : Started HellojibApplication in 2.202 seconds (JVM running for 2.446)
  • 用浏览器访问:http://192.168.121.132:8080/hello ,其中 192.168.121.132 是宿主机IP地址,如下图,可见springboot服务可以正常访问: Docker与Jib(maven插件版)实战

构建到本地镜像仓库

  • 上面的操作是将java应用生成tar文件然后再导入到本地镜像仓库,您也可以直接将java应用构建到本地镜像仓库中:
  • 先执行命令 docker rmi bolingcavalry/hellojib:0.0.1-SNAPSHOT 将前面构建的镜像删除;
  • 在pom.xml文件所在目录执行以下命令即可:
mvn clean compile jib:dockerBuild -U
  • 终端提示如下:
[root@centos7 hellojib]# mvn clean compile jib:dockerBuild -U
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.bolingcavalry:hellojib >---------------------
[INFO] Building hellojib 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ hellojib ---
[INFO] Deleting /root/temp/201906/29/hellojib/target
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ hellojib ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ hellojib ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to /root/temp/201906/29/hellojib/target/classes
[INFO]
[INFO] --- jib-maven-plugin:1.3.0:dockerBuild (default-cli) @ hellojib ---
[INFO]
[INFO] Containerizing application to Docker daemon as bolingcavalry/hellojib:0.0.1-SNAPSHOT...
[INFO] The base image requires auth. Trying again for openjdk:8-jdk-stretch...
[INFO]
[INFO] Container entrypoint set to [java, -Xms4g, -Xmx4g, -cp, /app/resources:/app/classes:/app/libs/*, com.bolingcavalry.hellojib.HellojibApplication]
[INFO]
[INFO] Built image to Docker daemon as bolingcavalry/hellojib:0.0.1-SNAPSHOT
[INFO] Executing tasks:
[INFO] [==============================] 100.0% complete
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  20.923 s
[INFO] Finished at: 2019-06-30T22:04:36+08:00
[INFO] ------------------------------------------------------------------------
  • 执行命令 docker images 可见镜像已经在镜像仓库中了:
[root@centos7 hellojib]# docker images
REPOSITORY                         TAG                         IMAGE ID            CREATED             SIZE
bolingcavalry/hellojib             0.0.1-SNAPSHOT              cf93bd81fbd5        49 years ago        505 MB

构建到hub.docker.com

  • docker的*仓库是 hub.docker.com ,jib也可以在镜像构建成功后自动推送到hub.docker.com网站,前提是您已经在该网站注册过,例如我已经注册过,账号是 bolingcavalry ,因此名为 bolingcavalry/XXXXXXXX 的镜像都可以推送到 hub.docker.com:

  • 在pom.xml文件所在目录执行以下命令即可自动推送到 hub.docker.com,其中bolingcavalry是我在hub.docker.com上的注册账号,123456是密码:

mvn compile jib:build -Djib.to.auth.username=bolingcavalry -Djib.to.auth.password=123456
  • 终端信息如下:
[root@centos7 hellojib]# mvn compile jib:build -Djib.to.auth.username=bolingcavalry -Djib.to.auth.password=123456
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.bolingcavalry:hellojib >---------------------
[INFO] Building hellojib 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ hellojib ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ hellojib ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- jib-maven-plugin:1.3.0:build (default-cli) @ hellojib ---
[INFO]
[INFO] Containerizing application to bolingcavalry/hellojib:0.0.1-SNAPSHOT...
[INFO] The base image requires auth. Trying again for openjdk:8-jdk-stretch...
[INFO]
[INFO] Container entrypoint set to [java, -Xms4g, -Xmx4g, -cp, /app/resources:/app/classes:/app/libs/*, com.bolingcavalry.hellojib.HellojibApplication]
[INFO]
[INFO] Built and pushed image as bolingcavalry/hellojib:0.0.1-SNAPSHOT
[INFO] Executing tasks:
[INFO] [==============================] 100.0% complete
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  02:47 min
[INFO] Finished at: 2019-06-30T22:16:19+08:00
[INFO] ------------------------------------------------------------------------
  • 在hub.docker.com上已经可以看到此镜像了,如下图(要登录后再看自己的镜像列表,如果没有登录是无法立即查到的): Docker与Jib(maven插件版)实战

  • 至此,Jib的实战已经完成,常用的操作相信您已经熟悉了,希望本文能帮助您做出满意的镜像;

欢迎关注51CTO博客:程序员欣宸

学习路上,你不孤单,欣宸原创一路相伴...