写点什么

Docker 与 Jib(maven 插件版) 实战

作者:程序员欣宸
  • 2022 年 9 月 29 日
    广东
  • 本文字数:7557 字

    阅读完需:约 25 分钟

Docker与Jib(maven插件版)实战

欢迎访问我的 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;


实战环境信息

  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 上下载本次实战的源码,地址和链接信息如下表所示:


  • 这个 git 项目中有多个文件夹,本章的源码在 hellojib 文件夹下,如下图红框所示:

准备 java 应用

  • 准备一个最简单的 springboot 应用 hellojib,用于实战构建 docker 镜像;

  • 该应用是基于 maven 构建的,启动类如下:


package com.bolingcavalry.hellojib;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic 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 */@RestControllerpublic 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 的文件,如下图红框所示:


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


[root@centos7 target]# docker load < jib-image.tar2c8d31157b81: Loading layer [==================================================>] 50.07 MB/50.07 MBea20c4bf3aae: Loading layer [==================================================>] 4.932 MB/4.932 MB51774d97c868: Loading layer [==================================================>]    221 B/221 B51566e3f832b: Loading layer [==================================================>]   104 MB/104 MB64c0b8425948: Loading layer [==================================================>] 14.91 MB/14.91 MBe4c3b920750d: Loading layer [==================================================>]    240 B/240 B8917d4e7f7b3: Loading layer [==================================================>] 1.034 kB/1.034 kBLoaded image: bolingcavalry/hellojib:0.0.1-SNAPSHOT
复制代码


  • 执行命令 docker images 可见镜像加载成功:


[root@centos7 target]# docker imagesREPOSITORY                         TAG                         IMAGE ID            CREATED             SIZEbolingcavalry/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: default2019-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 WebApplicationContext2019-06-30 13:56:52.261 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1223 ms2019-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)
复制代码


构建到本地镜像仓库

  • 上面的操作是将 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 imagesREPOSITORY                         TAG                         IMAGE ID            CREATED             SIZEbolingcavalry/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 上已经可以看到此镜像了,如下图(要登录后再看自己的镜像列表,如果没有登录是无法立即查到的):


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

欢迎关注 InfoQ:程序员欣宸

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


发布于: 3 小时前阅读数: 12
用户头像

搜索"程序员欣宸",一起畅游Java宇宙 2018.04.19 加入

前腾讯、前阿里员工,从事Java后台工作,对Docker和Kubernetes充满热爱,所有文章均为作者原创,个人Github:https://github.com/zq2599/blog_demos

评论

发布
暂无评论
Docker与Jib(maven插件版)实战_Docker_程序员欣宸_InfoQ写作社区