为什么在 docker 构建命令中使用 -f

Why to use -f in docker build command

我按照this K8s tutorial,在文件中间,有如下指令:

12. Now let’s build an image, giving it a special name that points to our local cluster registry.

$docker build -t 127.0.0.1:30400/hello-kenzan:latest -f applications/hello-kenzan/Dockerfile applications/hello-kenzan

我不明白为什么您需要使用 -f applications/hello-kenzan/Dockerfile.

指向 docker 文件

在docker build 的人中:

-f, --file=PATH/Dockerfile
          Path to the Dockerfile to use. If the path is a relative path and you are
          building from a local directory, then the path must be relative to that
          directory. If you are building from a remote URL pointing to either a
          tarball or a Git repository, then the path must be relative to the root of
          the remote context. In all cases, the file must be within the build context.
          The default is Dockerfile.

所以-f是指向docker文件,但是我们在build命令的最后已经给出了docker文件的路径-docker build ...applications/hello-kenzan,那为什么还要你需要写两次吗?我错过了什么吗?

你是对的。在这种情况下,您不必使用 -f 选项。 official docs 说:

-f:Dockerfile 的名称(默认为“PATH/Dockerfile”)并且由于给定的 PATH 是 applications/hello-kenzan 将隐式找到 Dockerfile。

原因是因为他可能有多个名为 Dockerfile 的文件,并且使用 -f 告诉 docker 不要使用当前目录中的 Dockerfile(当有一个时),而是使用Dockerfile中的applications/hello-kenzan代替。

虽然在这个特定的示例中没有必要这样做,但我感谢教程创建者向您展示了使用 PATH 的选项并将 -f 指向特定位置以向您(想要学习的人)展示可以使用不在 PATH 中的 Dockerfile(即,当您有多个 docker 文件时,您想要使用或当文件未命名为 Dockerfile 但例如 myapp-dockerfile 时创建构建)