将数据写入 Dockerfile 中的文件
Writing data to file in Dockerfile
我有一个 shell 脚本 script.sh,它将一些行写入文件:
#!/usr/bin/env bash
printf "blah
blah
blah
blah\n" | sudo tee file.txt
现在在我的 Dockerfile 中,我添加了这个脚本和 运行 它,然后尝试添加生成的 file.txt
:
ADD script.sh .
RUN chmod 755 script.sh && ./script.sh
ADD file.txt .
当我执行上述操作时,我只是收到一个关于 ADD file.txt .
命令的错误:
lstat file.txt: no such file or directory
为什么 docker 找不到我的 shell 脚本生成的文件?
我在哪里可以找到它?
这是因为 Docker 在开始时将目录(您的 Docker 文件所在的位置)的整个上下文加载到 Docker 守护进程。来自 Docker 文档,
The build is run by the Docker daemon, not by the CLI. The first thing a build process does is send the entire context (recursively) to the daemon. In most cases, it’s best to start with an empty directory as context and keep your Dockerfile in that directory. Add only the files needed for building the Dockerfile.
由于您的文本文件在开始时不可用,因此您收到了该错误消息。如果您仍然希望将该文本文件添加到 Docker 图像,您可以从同一个脚本文件调用 `docker build' 命令。修改script.sh,
#!/usr/bin/env bash
printf "blah
blah
blah
blah\n" | sudo tee <docker-file-directory>/file.txt
docker build --tag yourtag <docker-file-directory>
并修改您的 Docker 文件以添加生成的文本文件。
ADD file.txt
.. <rest of the Dockerfile instructions>
当你 RUN chmod 755 script.sh && ./script.sh
它实际上执行这个脚本 在 的 docker 容器中(即:在 docker 层)。
当您 ADD file.txt .
尝试从 local 文件系统添加文件到 docker 容器中(即:在新的 docker层).
您不能这样做,因为 file.txt 在您的计算机上不存在。
事实上,您已经在 docker 中找到了这个文件,请尝试 docker run --rm -ti mydockerimage cat file.txt
,您应该会看到显示的内容
我有一个 shell 脚本 script.sh,它将一些行写入文件:
#!/usr/bin/env bash
printf "blah
blah
blah
blah\n" | sudo tee file.txt
现在在我的 Dockerfile 中,我添加了这个脚本和 运行 它,然后尝试添加生成的 file.txt
:
ADD script.sh .
RUN chmod 755 script.sh && ./script.sh
ADD file.txt .
当我执行上述操作时,我只是收到一个关于 ADD file.txt .
命令的错误:
lstat file.txt: no such file or directory
为什么 docker 找不到我的 shell 脚本生成的文件? 我在哪里可以找到它?
这是因为 Docker 在开始时将目录(您的 Docker 文件所在的位置)的整个上下文加载到 Docker 守护进程。来自 Docker 文档,
The build is run by the Docker daemon, not by the CLI. The first thing a build process does is send the entire context (recursively) to the daemon. In most cases, it’s best to start with an empty directory as context and keep your Dockerfile in that directory. Add only the files needed for building the Dockerfile.
由于您的文本文件在开始时不可用,因此您收到了该错误消息。如果您仍然希望将该文本文件添加到 Docker 图像,您可以从同一个脚本文件调用 `docker build' 命令。修改script.sh,
#!/usr/bin/env bash
printf "blah
blah
blah
blah\n" | sudo tee <docker-file-directory>/file.txt
docker build --tag yourtag <docker-file-directory>
并修改您的 Docker 文件以添加生成的文本文件。
ADD file.txt
.. <rest of the Dockerfile instructions>
当你 RUN chmod 755 script.sh && ./script.sh
它实际上执行这个脚本 在 的 docker 容器中(即:在 docker 层)。
当您 ADD file.txt .
尝试从 local 文件系统添加文件到 docker 容器中(即:在新的 docker层).
您不能这样做,因为 file.txt 在您的计算机上不存在。
事实上,您已经在 docker 中找到了这个文件,请尝试 docker run --rm -ti mydockerimage cat file.txt
,您应该会看到显示的内容