Dockerfile的 multi-stage builds模板样例

kuberlin 2020-05-16

dockerfile多阶段构建,默认的情况下,构建的阶段是不会命名的,同一个docerfile里的第一个FROM会以0命名,然而你可以命名构建阶段使用AS起别名,在FROM后面指定,这样就可以使用--copy=别名 ,将该阶段的制品拷贝到当前阶段的镜像。

参考链接:https://docs.docker.com/develop/develop-images/multistage-build/

By default, the stages are not named, and you refer to them by their integer number, starting with 0 for the first FROM instruction. However, you can name your stages, by adding an AS <NAME> to the FROM instruction. This example improves the previous one by naming the stages and using the name in the COPY instruction. This means that even if the instructions in your Dockerfile are re-ordered later, the COPY doesn’t break.

Demo 如下:
FROM maven:latest AS builder #起个别名builder,该阶段主要是构建jar包
COPY . . #拷贝当前目录代码到镜像
RUN mvn -Dmaven.test.skip=true package ###maven构建

FROM openjdk:8-jre-alpine
COPY --from=builder target/xxx-0.0.1.jar /app.jar #--from 指定上个阶段起的别名,会在target目录下将构建好的jar包,拷贝到当前镜像
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ #设置时间同步
&& echo "Asia/Shanghai" > /etc/timezone
EXPOSE 8080 #暴露容器端口
ENTRYPOINT java -jar /app.jar #定义容器启动的命令

相关推荐