在RUN语句中使用Dockerfile参数

7

I have the following Dockerfile, which works:

FROM someimage
ARG transform

COPY Web*.config /inetpub/wwwroot/
RUN powershell /Build/Transform.ps1 -xml "/inetpub/wwwroot/web.config" -xdt "/inetpub/wwwroot/web.debug.config"

然而,我希望在构建时将web.debug.config文件作为参数传递进来。因此,我将最后一行改为:

RUN powershell /Build/Transform.ps1 -xml "/inetpub/wwwroot/web.config" -xdt "/inetpub/wwwroot/${transform}"

当我这样做时,${transform}参数没有被插值,而是被转换为空字符串。我已经确认transform参数被正确传递,因为我可以执行以下操作:
COPY ${transform} /inetpub/wwwroot/

当使用RUN命令时,我们可以通过插值实现在字符串中传递参数,例如"classpath=%s" % jarname。这样就能将变量jarname的值插入到字符串中。然后文件会被复制。有没有其他方式可以使用RUN命令对字符串进行插值?

我正在使用Windows 10上的Docker 18.03.1-ce。

3个回答

4

我找到了一个可行的解决方案,但肯定不是最理想的。似乎在RUN语句中变量无法展开(至少在Windows上是这样,没有尝试过Linux)。但是COPY语句会展开它们。所以,我可以将文件复制到一个临时文件中并给它一个硬编码的名称,然后使用它:

COPY ./ /inetpub/wwwroot/
COPY ${transform} /inetpub/wwwroot/Web.Current.config
RUN powershell -executionpolicy bypass /Build/Transform.ps1 -xml "/inetpub/wwwroot/web.config" -xdt "/inetpub/wwwroot/Web.Current.config"

在这种情况下,这对我很有效。
更新:找到另一种可行的方法
这可能是一种更好的方法,使用环境变量:
FROM someimage
ARG transform
ENV TransformFile ${transform}

COPY ./ /inetpub/wwwroot/
RUN powershell -executionpolicy bypass /Build/Transform.ps1 -xml "/inetpub/wwwroot/web.config" -xdt "/inetpub/wwwroot/$ENV:TransformFile"

在这种情况下,Docker将评估参数transform并设置为环境变量TransformFile。当我在PowerShell脚本中使用它时,不再是Docker评估参数,而是Powershell自己评估。因此,必须使用Powershell语法来插值环境变量。

1
可以确认它们在Linux上没有被扩展。 - nciao

0

Dockerfile RUN的shell表单应该允许arg扩展。

检查引号是否妨碍了操作。

RUN powershell ... -xdt "/inetpub/wwwroot/"${transform}

注意:您可以在Microsoft文档中看到使用$var而不是${var}的PowerShell命令。


谢谢!不幸的是,这没起作用。我尝试了"/inetpub/wwwroot/"${transform}"/inetpub/wwwroot/"$transform - Mike Christensen

0

尝试使用这个 Dockerfile

FROM someimage
ENV trans transform

COPY ${trans}/inetpub/wwwroot/
RUN powershell /Build/Transform.ps1 -xml "/inetpub/wwwroot/web.config" -xdt "/inetpub/wwwroot/${trans}"

运行命令

docker build --build-arg transform="web.debug.config" -t sample:latest .

是的,我也走过那条路。环境变量在运行时由shell评估,因此它并不是一个真正的模板机制。 - Mike Christensen
尝试以下 Docker 文件: FROM someimage ARG transform ENV trans transform COPY ${trans}/inetpub/wwwroot/ RUN powershell /Build/Transform.ps1 -xml "/inetpub/wwwroot/web.config" -xdt "/inetpub/wwwroot/${trans}"
运行 "docker build --build-arg transform="web.debug.config" -t sample:latest ."
- mahes wari
同样的事情。我得到:步骤5/5:运行powershell -executionpolicy bypass /Build/Transform.ps1 -xml“/inetpub/wwwroot/web.config”-xdt“/inetpub/wwwroot/${trans}” --->在16042f7076ad中运行 使用/inetpub/wwwroot/转换/inetpub/wwwroot/web.config New-Object: Exception calling ".ctor" with "1" argument(s): "Could not find a part of the path 'C:\inetpub\wwwroot\'." - Mike Christensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接