如何在多阶段 Docker 构建的阶段之间复制变量? [英] How do I copy variables between stages of multi stage Docker build?

查看:20
本文介绍了如何在多阶段 Docker 构建的阶段之间复制变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只看到了使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆