如何解析 docker 文件中的 CMD 和 ENTRYPOINT exec 形式?

Ola*_*laf 2 docker dockerfile

我在 Docker 容器中运行 Jupyter。下面的 shell 形式可以正常运行:

CMD jupyter lab --ip='0.0.0.0' --port=8888 --no-browser --allow-root /home/notebooks
Run Code Online (Sandbox Code Playgroud)

但 docker 文件中的以下一项不会:

ENTRYPOINT ["/bin/sh", "-c"]
CMD ["jupyter", "lab", "--ip='0.0.0.0'", "--port=8888", "--no-browser", "--allow-root", "/home/notebooks"]
Run Code Online (Sandbox Code Playgroud)

错误是:

usage: jupyter [-h] [--version] [--config-dir] [--data-dir] [--runtime-dir] [--paths] [--json] [subcommand]
jupyter: error: one of the arguments --version subcommand --config-dir --data-dir --runtime-dir --paths is required
Run Code Online (Sandbox Code Playgroud)

所以显然/bin/sh -c看到了jupyter论点,但没有看到以下论点。

有趣的是,

CMD ["jupyter", "lab", "--ip='0.0.0.0'", "--port=8888", "--no-browser", "--allow-root", "/home/notebooks"]
Run Code Online (Sandbox Code Playgroud)

会运行良好,所以它不能是参数的数量,或者可以吗?

根据https://docs.docker.com/engine/reference/builder/#cmd,CMD 的 shell 形式以/bin/sh -c. 所以从我的角度来看,我认为这两个版本没有什么区别。但原因一定是当 ENTRYPOINT 和 CMD 同时存在时如何评估 exec 形式。

Dav*_*aze 5

在非常低的级别上,Linux 命令作为一系列“单词”执行。通常,您的 shell 将采用类似 的命令行ls -l "a directory"并将其分解为三个单词ls -l a directory。(注意“目录”中的空格:在 shell 形式中需要引用才能在同一个单词中。)

DockerfileCMDENTRYPOINT(and RUN) 命令有两种形式。在您指定的类似于 JSON 数组的表单中,您明确指定了单词的分解方式。如果它看起来不像 JSON 数组,那么整个内容将被视为单个字符串,并包装在命令中sh -c

# Explicitly spelling out the words
RUN ["ls", "-l", "a directory"]

# Asking Docker to run it via a shell
RUN ls -l 'a directory'
# The same as
RUN ["sh", "-c", "ls -l 'a directory'"]
Run Code Online (Sandbox Code Playgroud)

如果您指定两者ENTRYPOINT,则CMD两个单词列表就会组合在一起。对于您的示例来说,重要的是sh -c获取下一个单词并将其作为 shell 命令运行;任何剩余的单词都可以用作该命令字符串中的$0, $1, ... 位置参数。

所以在你的例子中,最后运行的事情或多或少是

ENTRYPOINT+CMD ["sh", "-c", "jupyter", ...]
# If the string "jupyter" contained "$1" it would expand to the --ip option
Run Code Online (Sandbox Code Playgroud)

另一个重要的推论是,实际上,ENTRYPOINT不能是裸字符串格式:当CMD附加到它时,你会得到

ENTRYPOINT some command
CMD with args

ENTRYPOINT+CMD ["sh", "-c", "some command", "sh", "-c", "with args"]
Run Code Online (Sandbox Code Playgroud)

按照同样的规则,所有单词CMD都会被忽略。

在实践中,您几乎不需要在 Dockerfile 中显式放置sh -c或声明;SHELL请改用字符串形式的命令,或将复杂的逻辑放入 shell 脚本中。