如何在多阶段Docker构建的各个阶段之间复制变量? [英] How do I copy variables between stages of multi stage Docker build?
问题描述
我仅看到了使用COPY在多阶段Dockerfile的各阶段之间复制文件的示例,但是有没有一种方法可以简单地复制ENV变量?我的用例是从git映像开始,只是要获取将作为构建一部分的提交哈希.我稍后要构建的图像没有git.
I've only seen examples of using COPY to copy files between stages of a multi stage Dockerfile, but is there a way to simply copy an ENV variable? My use case is to start out with a git image to just to get the commit hash that will be part of the build. The image I'm later building with hasn't got git.
我意识到我可以将git哈希输出到文件中并使用COPY,但我只是想知道是否有更清洁的方法?
I realise I could just pipe out the git hash to a file and use COPY but I'm just wondering if there's a cleaner way?
推荐答案
您有3个选择: "ARG"解决方案,基础"解决方案和文件"解决方案.
You got 3 options: The "ARG" solution, the "base" solution, and "file" solution.
ARG version_default=v1
FROM alpine:latest as base1
ARG version_default
ENV version=$version_default
RUN echo ${version}
RUN echo ${version_default}
FROM alpine:latest as base2
ARG version_default
RUN echo ${version_default}
另一种方法是将基础容器用于多个阶段:
another way is to use base container for multiple stages:
FROM alpine:latest as base
ARG version_default
ENV version=$version_default
FROM base
RUN echo ${version}
FROM base
RUN echo ${version}
您可以在此处找到更多详细信息: https://github.com/moby/moby/issues/37345
You can find more details here: https://github.com/moby/moby/issues/37345
此外,您可以在第一阶段将哈希保存到文件中,然后在第二阶段复制该文件,然后在其中读取和使用它.
Also you could save the hash into a file in the first stage, and copy the file in the second stage and then read it and use it there.
这篇关于如何在多阶段Docker构建的各个阶段之间复制变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!