如何查看 docker 镜像的日志? [英] How to view logs for a docker image?

查看:192
本文介绍了如何查看 docker 镜像的日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the docker world, one can easily see logs for docker container (that is, a running image). But during image creation, one usually issues multiple commands. For example npm install commands in node projects. It would be beneficial to see logs for those commands as well. I quickly searched from the documentation, but didn't find how one can obtain logs for docker image. Is it possible?

推荐答案

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

Easiest method is to use tee to send a copy of all your command output to a logfile. If you want it attached to the image, output your run commands to a logfile inside of the image with something like:

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

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

Then you can run a quick one-off container to view the contents of the logs:

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

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

If you don't need the logs attached to the image, you can log the output of every build with a single change to your build command (instead of lots of changes to the run commands) exactly as JHarris says:

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

如果您在构建时不使用 --rm=true,那么您将拥有所有中间容器,并且每个中间容器都有一个您可以使用的日志来查看

If you build without using --rm=true, then you have all the intermediate containers, and each one of those has a log you can review with

docker logs $container_id

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

And lastly, don't forget there's a history of the layers in the image. They don't show the output of each command, but it is useful for all of those commands that don't log any output and knowing which build each layer comes from particularly when there's lots of caching being used.

docker history my-image

这篇关于如何查看 docker 镜像的日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆