如何查看 docker 镜像的日志?

新手上路,请多包涵

在 docker 世界中,可以很容易地看到 docker 容器的日志(即运行映像)。但是在图像创建过程中,通常会发出多个命令。例如节点项目中的 npm install 命令。查看这些命令的日志也是有益的。我快速从文档中搜索,但没有找到如何获取 docker 映像的日志。可能吗?

原文由 Ville Miekk-oja 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

更新:由于已经提出了这个问题,似乎每个人都在看到 buildkit 的输出更改后找到了它。 Buildkit 包括以下选项( docker build --help 全部查看):

       --build-arg list          Set build-time variables
      --cache-from strings      Images to consider as cache sources
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
      --no-cache                Do not use cache when building the image
  -o, --output stringArray      Output destination (format: type=local,dest=path)
      --platform string         Set platform if server is multi-platform capable
      --progress string         Set type of progress output (auto, plain, tty). Use plain to show container output (default "auto")
      --pull                    Always attempt to pull a newer version of the image
  -q, --quiet                   Suppress the build output and print image ID on success
  -t, --tag list                Name and optionally a tag in the 'name:tag' format
      --target string           Set the target build stage to build.

许多人想要的 buildkit 选项是 --progress=plain

 docker build -t my-image --progress=plain .

如果您真的想查看之前的构建输出,您可以使用环境变量禁用 buildkit,但我倾向于建议您不要这样做,因为您会丢失 buildkit 的许多功能(跳过未使用的构建步骤、并发构建步骤、多平台图像,以及 Dockerfile 的新语法,用于 RUN --mount... 等功能:

 DOCKER_BUILDKIT=0 docker build -t my-image .


OP 要求将其构建的日志包含在映像本身中。一般来说,我建议不要这样做,您希望这些日志在图像之外。

也就是说,最简单的方法是使用 tee 将所有命令输出的副本发送到日志文件。如果您希望它附加到图像,请将您的运行命令输出到图像内的日志文件,例如:

 RUN my-install-cmd | tee /logs/my-install-cmd.log

然后你可以运行一个快速的一次性容器来查看这些日志的内容:

 docker run --rm my-image cat /logs/my-install-cmd.log

如果您不需要附加到图像的日志,则可以完全按照 JHarris 所说的那样记录每个构建的输出,只需对构建命令进行一次更改(而不是对运行命令进行大量更改):

 docker build -t my-image . | tee my-image.build.log

使用经典的 docker build 命令,如果您在不使用 --rm=true 的情况下进行构建,那么您将拥有所有中间容器,并且每个容器都有一个您可以查看的日志

docker logs $container_id

最后,不要忘记图像中图层的历史。它们不显示每个命令的输出,但它对于所有那些不记录任何输出并且知道每一层来自哪个构建的命令很有用,特别是在使用大量缓存时。

 docker history my-image

原文由 BMitch 发布,翻译遵循 CC BY-SA 4.0 许可协议

有同样的问题,我用它解决了

docker build --no-cache --progress=plain -t my-image .

原文由 diegocl02 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题