Dockerfile
FROM openjdk:8-jdk-alpine as basic VOLUME /tmp COPY BOOT-INF/lib /app/lib COPY META-INF /app/META-INF COPY BOOT-INF/classes /app/classes FROM openjdk:8-jdk-alpine COPY --from=basic /app/lib /app/lib COPY --from=basic /app/META-INF /app/META-INF COPY --from=basic /app/classes /app/classes ENTRYPOINT java -XX:MaxRAMFraction=2 -cp app/classes:app/lib/* com.example.demo.DemoApplication
构建脚本
repository="harbor.hknaruto.com/library/training" mvn clean package -Dmaven.test.skip=true -T4 mkdir target/dependency cp Dockerfile target/dependency ( cd target/dependency jar -xf ../*.jar docker build -t "$repository":"$(git branch | awk '{print $2}')"."$(git rev-parse --short HEAD)" . # 清理老的镜像,本地保留3个最近构建的镜像,从第4个开始,删除本地镜像 docker images | grep "$repository" | tail -n +4 | awk '{print $3}' | xargs -i docker rmi {} )
第一次构建效果
$ docker history harbor.hknaruto.com/library/training:master.30b943a IMAGE CREATED CREATED BY SIZE COMMENT f5d2de97b288 12 seconds ago /bin/sh -c #(nop) ENTRYPOINT ["/bin/sh" "-c… 0B a50c1ee7d59c 12 seconds ago /bin/sh -c #(nop) COPY dir:590e06da69bc4b6fc… 10.8kB 5b91b3624e0a 12 seconds ago /bin/sh -c #(nop) COPY dir:34d1e4a296310a6ec… 2.17kB 52dcee3f3e35 4 minutes ago /bin/sh -c #(nop) COPY dir:94d828a4ed8596549… 20MB a3562aa0b991 2 years ago /bin/sh -c set -x && apk add --no-cache o… 99.3MB <missing> 2 years ago /bin/sh -c #(nop) ENV JAVA_ALPINE_VERSION=8… 0B <missing> 2 years ago /bin/sh -c #(nop) ENV JAVA_VERSION=8u212 0B <missing> 2 years ago /bin/sh -c #(nop) ENV PATH=/usr/local/sbin:… 0B <missing> 2 years ago /bin/sh -c #(nop) ENV JAVA_HOME=/usr/lib/jv… 0B <missing> 2 years ago /bin/sh -c { echo '#!/bin/sh'; echo 'set… 87B <missing> 2 years ago /bin/sh -c #(nop) ENV LANG=C.UTF-8 0B <missing> 2 years ago /bin/sh -c #(nop) CMD ["/bin/sh"] 0B <missing> 2 years ago /bin/sh -c #(nop) ADD file:a86aea1f3a7d68f6a… 5.53MB
第二次构建效果
$ docker history harbor.hknaruto.com/library/training:master.30b943a IMAGE CREATED CREATED BY SIZE COMMENT abc62088b1b6 1 second ago /bin/sh -c #(nop) ENTRYPOINT ["/bin/sh" "-c… 0B 61cf540de3ff 1 second ago /bin/sh -c #(nop) COPY dir:d4dc9a24cb84bd616… 10.8kB 5b91b3624e0a 2 minutes ago /bin/sh -c #(nop) COPY dir:34d1e4a296310a6ec… 2.17kB 52dcee3f3e35 5 minutes ago /bin/sh -c #(nop) COPY dir:94d828a4ed8596549… 20MB a3562aa0b991 2 years ago /bin/sh -c set -x && apk add --no-cache o… 99.3MB <missing> 2 years ago /bin/sh -c #(nop) ENV JAVA_ALPINE_VERSION=8… 0B <missing> 2 years ago /bin/sh -c #(nop) ENV JAVA_VERSION=8u212 0B <missing> 2 years ago /bin/sh -c #(nop) ENV PATH=/usr/local/sbin:… 0B <missing> 2 years ago /bin/sh -c #(nop) ENV JAVA_HOME=/usr/lib/jv… 0B <missing> 2 years ago /bin/sh -c { echo '#!/bin/sh'; echo 'set… 87B <missing> 2 years ago /bin/sh -c #(nop) ENV LANG=C.UTF-8 0B <missing> 2 years ago /bin/sh -c #(nop) CMD ["/bin/sh"] 0B <missing> 2 years ago /bin/sh -c #(nop) ADD file:a86aea1f3a7d68f6a… 5.53MB
其中最大的lib目录由于没有发生变动,并没有执行更新。
注意,如果不采用COPY --from 方式,即使lib目录没有更新,也会重新创建新的层!导致镜像变动部分仍然很大。