前言

jib是google开源的纯java实现的容器构建类库,其中有jib-core核心包和maven以及gradle插件,jib可以帮助java开发者,快速构建镜像,并且无需编写dockerfile以及依赖docker环境(docker daemon和docker client),这里只介绍jib-maven-plugin如何使用,并且会讲到其中的坑点,至于核心包,我这边就不讲了,虽然笔者也有使用。详细可以到GitHub搜索jib

安装

在maven项目中的pom.xml文件中:

<project>
  ...
  <build>
    <plugins>
      ...
      <plugin>
        <groupId>com.google.cloud.tools</groupId>
        <artifactId>jib-maven-plugin</artifactId>
        <version>2.6.0</version>
        <configuration>
          <to>
            <image>myimage</image>
          </to>
        </configuration>
      </plugin>
      ...
    </plugins>
  </build>
  ...
</project>

其中插件configuration支持的参数列表如下:

FieldTypeDefaultDescription
totoRequiredConfigures the target image to build your application to.
fromfromSee fromConfigures the base image to build your application on top of.
containercontainerSee containerConfigures the container that is run from your image.
extraDirectoriesextraDirectoriesSee extraDirectoriesConfigures the directories used to add arbitrary files to the image.
outputPathsoutputPathsSee outputPathsConfigures the locations of additional build artifacts generated by Jib.
dockerClientdockerClientSee dockerClientConfigures Docker for building to/from the Docker daemon.
skaffoldskaffoldSee skaffoldConfigures the internal skaffold goals. This configuration should only be used when integrating with skaffold.
containerizingModestringexplodedIf set to packaged, puts the JAR artifact built at ${project.build.directory}/${project.build.finalName}.jar (the default location where many JAR-buidiling plugins put a JAR registered as a main artifact, such as the Maven JAR Plugin) into the final image. If set to exploded (default), containerizes individual .class files and resources files.
allowInsecureRegistriesbooleanfalseIf set to true, Jib ignores HTTPS certificate errors and may fall back to HTTP as a last resort. Leaving this parameter set to false is strongly recommended, since HTTP communication is unencrypted and visible to others on the network, and insecure HTTPS is no better than plain HTTP. If accessing a registry with a self-signed certificate, adding the certificate to your Java runtime’s trusted keys may be an alternative to enabling this option.
skipbooleanfalseIf set to true, Jib execution is skipped (useful for multi-module projects). This can also be specified via the -Djib.skip command line option.

from 参数

PropertyTypeDefaultDescription
imagestringgcr.io/distroless/javaThe image reference for the base image. The source type can be specified using a special type prefix.
authauthNoneSpecifies credentials directly (alternative to credHelper).
credHelperstringNoneSpecifies a credential helper that can authenticate pulling the base image. This parameter can either be configured as an absolute path to the credential helper executable or as a credential helper suffix (following docker-credential-).
platformslistSee platformIncubating feature: Configures platforms of base images to select from a manifest list.

to标签配置

PropertyTypeDefaultDescription
imagestringRequiredThe image reference for the target image. This can also be specified via the -Dimage command line option.
authauthNoneSpecifies credentials directly (alternative to credHelper).
credHelperstringNoneSpecifies a credential helper that can authenticate pushing the target image. This parameter can either be configured as an absolute path to the credential helper executable or as a credential helper suffix (following docker-credential-).
tagslistNoneAdditional tags to push to.

auth标签配置

PropertyType
usernamestring
passwordstring

platform 标签配置

PropertyTypeDefaultDescription
architecturestringamd64The architecture of a base image to select from a manifest list.
osstringlinuxThe OS of a base image to select from a manifest list.

container标签配置

PropertyTypeDefaultDescription
appRootstring/appThe root directory on the container where the app’s contents are placed. Particularly useful for WAR-packaging projects to work with different Servlet engine base images by designating where to put exploded WAR contents; see WAR usage as an example.
argslistNoneAdditional program arguments appended to the command to start the container (similar to Docker’s CMD instruction in relation with ENTRYPOINT). In the default case where you do not set a custom entrypoint, this parameter is effectively the arguments to the main method of your Java application.
creationTimestringEPOCHSets the container creation time. (Note that this property does not affect the file modification times, which are configured using <filesModificationTime>.) The value can be EPOCH to set the timestamps to Epoch (default behavior), USE_CURRENT_TIMESTAMP to forgo reproducibility and use the real creation time, or an ISO 8601 date-time parsable with DateTimeFormatter.ISO_DATE_TIME such as 2019-07-15T10:15:30+09:00 or 2011-12-03T22:42:05Z.
entrypointlistNoneThe command to start the container with (similar to Docker’s ENTRYPOINT instruction). If set, then jvmFlags and mainClass are ignored. You may also set <entrypoint>INHERIT</entrypoint> (<entrypoint><entry>INHERIT</entry></entrypoint> in old Maven versions) to indicate that the entrypoint and args should be inherited from the base image.*
environmentmapNoneKey-value pairs for setting environment variables on the container (similar to Docker’s ENV instruction).
extraClasspathlistNoneAdditional paths in the container to prepend to the computed Java classpath.
filesModificationTimestringEPOCH_PLUS_SECONDSets the modification time (last modified time) of files in the image put by Jib. (Note that this does not set the image creation time, which can be set using <creationTime>.) The value should either be EPOCH_PLUS_SECOND to set the timestamps to Epoch + 1 second (default behavior), or an ISO 8601 date-time parsable with DateTimeFormatter.ISO_DATE_TIME such as 2019-07-15T10:15:30+09:00 or 2011-12-03T22:42:05Z.
formatstringDockerUse OCI to build an OCI container image.
jvmFlagslistNoneAdditional flags to pass into the JVM when running your application.
labelsmapNoneKey-value pairs for applying image metadata (similar to Docker’s LABEL instruction).
mainClassstringInferred**The main class to launch the application from.
portslistNonePorts that the container exposes at runtime (similar to Docker’s EXPOSE instruction).
userstringNoneThe user and group to run the container as. The value can be a username or UID along with an optional groupname or GID. The following are all valid: user, uid, user:group, uid:gid, uid:group, user:gid.
volumeslistNoneSpecifies a list of mount points on the container.
workingDirectorystringNoneThe working directory in the container

extraDirectories 标签配置

PropertyTypeDefaultDescription
pathslist[(project-dir)/src/main/jib]List of path objects and/or extra directory paths. Can be absolute or relative to the project root.
permissionslistNoneMaps file paths (glob patterns) on container to Unix permissions. (Effective only for files added from extra directories.) If not configured, permissions default to “755” for directories and “644” for files. See Adding Arbitrary Files to the Image for an example.

系统构建参数

(i.e. -Djib.parameterName[.nestedParameter.[...]]=value). Some examples are below:

mvn compile jib:build \
    -Djib.to.image=myregistry/myimage:latest \
    -Djib.to.auth.username=$USERNAME \
    -Djib.to.auth.password=$PASSWORD

mvn compile jib:dockerBuild \
    -Djib.dockerClient.executable=/path/to/docker \
    -Djib.container.environment=key1="value1",key2="value2" \
    -Djib.container.args=arg1,arg2,arg3

maven完整使用案例

目录结构
.
├── hello-world
├── jib-lib
├── name
└── pom.xml

这是一个多模块工程,其中jib-lib为基础依赖模块,hello-world和name都是web模块

pom.xml配置如下:

 <properties>
        <maven.build.timestamp.format>yyyyMMdd-HHmmssSSS</maven.build.timestamp.format>
</properties>
<build>
        <!-- Defines plugins that are used in the modules. -->
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>com.google.cloud.tools</groupId>
                    <artifactId>jib-maven-plugin</artifactId>
                    <version>2.6.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

hello-world

  <plugin>
  <groupId>com.google.cloud.tools</groupId>
  <artifactId>jib-maven-plugin</artifactId>
  <configuration>
      <allowInsecureRegistries>true</allowInsecureRegistries>
      <from>
          <image>localhost:5000/jre:11</image>
          <auth>
            <username>${env.DOCKERUSER}</username>
            <password>${env.DOCKERPW}</password>
          </auth>
      </from>
      <to>
          <!-- make sure you already have created a project at Google Cloud Platform, see https://cloud.google.com/container-registry/ -->
          <image>localhost:5000/${project.artifactId}:${project.version}-${maven.build.timestamp}</image>

      </to>
      <container>
      <!-- 使用当前时间构建,否则50年前的时间,可以查看:https://github.com/GoogleContainerTools/jib/blob/master/docs/faq.md#why-is-my-image-created-48-years-ago -->
          <creationTime>USE_CURRENT_TIMESTAMP</creationTime> 
          
          <jvmFlags>
              <jvmFlag>-Xms256m</jvmFlag>
              <jvmFlag>-Xmx512m</jvmFlag>

          </jvmFlags>
          <mainClass>com.example.helloworld.HelloWorldApplication</mainClass>
          <ports>
              <port>8080</port>
              <!-- <port>4000-4004/udp</port> -->
          </ports>
          <format>OCI</format>
          <!-- OR <format>Docker</format> -->

      </container>
  </configuration>
</plugin>

依赖库pom.xml配置:

<plugin>
    <groupId>com.google.cloud.tools</groupId>
    <artifactId>jib-maven-plugin</artifactId>
    <configuration>
        <!-- we don't want jib to execute on this module -->
        <skip>true</skip>
    </configuration>
</plugin>

构建命令:

#构建全部
mvn clean package jib:build -Dmaven.test.skip=true -DsendCredentialsOverHttp=true
#构建某个模块

mvn clean package jib:build -pl hello-world -am -Dmaven.test.skip=true -DsendCredentialsOverHttp=true

这里重点说一下-DsendCredentialsOverHttp=true 这个参数将允许你使用http发送账号密码,google都喜欢强迫用户使用https.

PS: jvmFlag用来配置jvm参数,mainClass 配置运行类 ,构建镜像最后文件否会放到 /app 目录下,该目录下拥有三个目录分别是: classes libs resources 源码字节码,依赖包和配置文件

参考文献

jib源码

jib FAQ


本博客所有文章除特别声明外,均采用: 署名-非商业性使用-禁止演绎 4.0 国际协议,转载请保留原文链接及作者。

我对理财的思考 上一篇
使用Java操作k8s和registry 下一篇

 目录


买个卤蛋,吃根冰棒