打包原理
使用google的 jib
工具
jib使用java实现了docker镜像的打包功能,所以能够跨平台打包
gradle + jib插件使用
- build.gradle 添加插件
plugins {
id 'org.springframework.boot' version '2.1.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id "com.google.cloud.tools.jib" version "2.6.0"
}
- 添加jib配置
jib {
from {
image = "adoptopenjdk/openjdk11:alpine-jre"
}
to {
image = "dingsync:latest"
}
container {
entrypoint = ["sh", "-c", "chmod +x /entrypoint.sh && sync && /entrypoint.sh"]
ports = ["8082"]
environment = [
SPRING_OUTPUT_ANSI_ENABLED: "ALWAYS",
JHIPSTER_SLEEP: "0",
JAVA_OPTS:"-Dspring.profiles.active=dev"
]
}
allowInsecureRegistries = true
}
- 添加entrypoint.sh
记得要修改
主类的名字
,entrypoint.sh
放在项目src/main/jib
文件夹下
#!/bin/sh
echo "The application will start in ${JHIPSTER_SLEEP}s..." && sleep ${JHIPSTER_SLEEP}
exec java ${JAVA_OPTS} -noverify -XX:+AlwaysPreTouch -Djava.security.egd=file:/dev/./urandom -cp /app/resources/:/app/classes/:/app/libs/* "vip.youngboy.dingsync.DingsyncApplication" "$@"
打包镜像命令
gradlew jib //打包并推送参考
gradlew jibBuildTar //打tar包
gradlew jibDockerBuild //打包并运行
maven + jib使用
详见 https://github.com/GoogleContainerTools/jib
maven配置
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>2.7.0</version>
<configuration>
<from>
<image>adoptopenjdk/openjdk11:alpine-jre</image>
</from>
<to>
<image>${docker.repostory}/${docker.registry.name}/${project.artifactId}</image>
<tags>${profiles.active}</tags>
</to>
<container>
<entrypoint>
<entry>sh</entry>
<entry>-c</entry>
<entry><![CDATA[chmod +x /entrypoint.sh && sync && /entrypoint.sh]]></entry>
</entrypoint>
<ports>11330</ports>
<environment>
<SPRING_OUTPUT_ANSI_ENABLED>ALWAYS</SPRING_OUTPUT_ANSI_ENABLED>
<JHIPSTER_SLEEP>0</JHIPSTER_SLEEP>
</environment>
</container>
<allowInsecureRegistries>true</allowInsecureRegistries>
</configuration>
</plugin>
进阶
Q:为什么不使用打成jar包,而是使用 java -cp的方式启动?
A: 打成jar包会导致不能缓存依赖jar包,每次需要上传的文件就会变大,如果把lib分离出来就可以把lib单独作为一个layer层