Jar 分层是Spring Boot 2.3 新特性,开启Jar分层后,有助于在构建docker镜像时,将项目自身的资源和外部依赖进行区分,这样就能大幅度提高docker镜像的构建和推送速度。
构建镜像
目录结构
如何开启(可以开始抄了~)
在spring-boot-maven-plugin配置相关参数
1 2 3 4 5 6 7 8 9
| <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <layers> <enabled>true</enabled> </layers> </configuration> </plugin>
|
编写Dockerfile,分层打包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| FROM openjdk:8-jre as builder WORKDIR build ARG JAR_FILE=target/layered-jar-demo.jar COPY ${JAR_FILE} app.jar RUN java -Djarmode=layertools -jar app.jar extract && rm app.jar
FROM amazoncorretto:11 LABEL maintainer="pwoer4j@outlook.com" ENV TZ=Asia/Shanghai ENV JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom" WORKDIR app
COPY --from=builder build/dependencies/ ./ COPY --from=builder build/snapshot-dependencies/ ./ COPY --from=builder build/spring-boot-loader/ ./ COPY --from=builder build/application/ ./
EXPOSE 8081
CMD pwd && ls -la && java $JAVA_OPTS org.springframework.boot.loader.JarLauncher
|
这里用到了一个docker 镜像的构建技术叫做multi-stage builds
,需要17.05
以上的docker 引擎。
示例代码
https://github.com/power4j/layered-jar-demo
参考资料
Spring Boot 2.3 Release Notes
Spring Boot Executable Jar Format
Use multi-stage builds
Spring Boot 2.3 新特性分层JAR