【问题标题】:Redirect STDOUT of a RUN command in a Dockerfile在 Dockerfile 中重定向 RUN 命令的 STDOUT
【发布时间】:2021-10-05 20:43:27
【问题描述】:

我需要在 Docker 构建会话期间将两个文件连接在一起。然后将在后续步骤中在容器内访问连接的文件。

当我尝试在 Dockerfile 中使用它时:

COPY ./a /tmp
COPY ./b /tmp
RUN ["ls", "/tmp"]
RUN ["cat", "/tmp/a", "/tmp/b", ">/tmp/c"]
RUN ["ls", "/tmp"]

然后尝试构建容器我得到这个错误:

Step 3/13 : COPY ./a /tmp
 ---> Using cache
 ---> 253aad0eae1a
Step 4/13 : COPY ./b /tmp
 ---> Using cache
 ---> 0f86ea5731bf
Step 5/13 : RUN ["ls", "/tmp"]
 ---> Using cache
 ---> f9aae6a9e657
Step 6/13 : RUN ["cat", "/tmp/a", "/tmp/b", ">/tmp/c"]
 ---> Running in 3aed3ca981ab
Tue Oct  5 16:29:32 EDT 2021
Tue Oct  5 16:29:33 EDT 2021
cat: >/tmp/c: No such file or directory
The command 'cat /tmp/a /tmp/b >/tmp/c' returned a non-zero code: 1

如何使用 RUN 命令重定向 STDOUT?

我可以使用另一个接受输出文件名作为参数的命令吗?

我知道我可以创建一个小脚本并将其添加到容器中,然后运行该脚本,但我希望能够在 Dockerfile 中执行此操作。

【问题讨论】:

  • "small script" ...这是一个小的 shell 脚本。知道如何处理 > 的东西是一个 shell,你使用 json/exec 语法显式绕过它来运行。

标签: docker dockerfile stdout


【解决方案1】:

您正在使用 RUN 和来自的 exec RUN ["executable", "param1", "param2"] 如果扩展变量、子命令、管道输出、将命令链接在一起等 shell 功能不起作用,请使用 RUNshell 形式输入命令作为一个字符串 RUN <command>

COPY ./a /tmp
COPY ./b /tmp
RUN ls /tmp
RUN cat /tmp/a /tmp/b > /tmp/c
RUN ls /tmp

【讨论】:

  • 这是正确的,但你能解释一下原因吗?与原始 Dockerfile 有什么不同,为什么会有所不同?
  • 您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以在help center找到更多关于如何写好答案的信息。
  • 答案已更新。
  • 感谢您的回答。我尝试了您的解决方案的变体: RUN "cat /tmp/a /tmp/b > /tmp/c" 但结果是: /bin/sh: 1: cat /tmp/a /tmp/b > /tmp /c: not found 我没有意识到双引号导致整行被视为单个命令。
猜你喜欢
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2019-10-11
  • 2023-02-07
  • 2019-10-19
  • 1970-01-01
相关资源
最近更新 更多