📜  tail docker 容器日志 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:05:28.353000             🧑  作者: Mango

使用tail命令查看Docker容器日志

Docker是一种常用的容器技术,使用Docker构建和部署应用程序的过程中需要查看容器日志进行调试和错误排查。tail是一个常用的命令行工具,用于查看文件的末尾内容。在本文中,我们将探讨如何使用tail命令查看Docker容器日志。

使用tail查看容器日志

要查看Docker容器的日志,可以使用docker logs命令。但是,该命令只提供容器的完整日志输出。如果要查看实时日志,可以使用tail命令。

以下是使用tail命令查看Docker容器日志的步骤:

  1. 使用docker ps命令列出正在运行的容器。
$ docker ps

应该会输出类似于下面的内容:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                            NAMES
4b4d2a12cbe4        nginx               "/docker-entrypoint.…"   6 days ago          Up 4 hours          0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp     my-nginx
  1. 使用docker logs命令获取容器的日志文件路径。
$ docker logs my-nginx

输出为:

2021/07/22 03:44:01 [notice] 1#1: using the "epoll" event method
2021/07/22 03:44:01 [notice] 1#1: nginx/1.21.1
2021/07/22 03:44:01 [notice] 1#1: built by gcc 10.3.1 20210424 (Alpine 10.3.1_git20210424)
2021/07/22 03:44:01 [notice] 1#1: OS: Linux 5.10.47-linuxkit x86_64
2021/07/22 03:44:01 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/07/22 03:44:01 [notice] 1#1: start worker processes
  1. 使用tail命令查看日志文件的末尾内容。
$ docker logs my-nginx | tail

输出为:

2021/07/22 03:47:01 [notice] 1#1: signal 15 (SIGTERM) received, exiting
2021/07/22 03:47:01 [notice] 6#6: exiting
2021/07/22 03:47:01 [notice] 6#6: exit
2021/07/22 03:47:01 [notice] 1#1: signal 17 (SIGCHLD) received from 6
2021/07/22 03:47:01 [notice] 1#1: worker process 6 exited with code 0
2021/07/22 03:47:01 [notice] 1#1: exit
如何使用tail实时查看Docker容器日志

要实时查看Docker容器的日志,可以使用tail -f命令。该命令将持续输出容器日志的最新内容。

以下是使用tail -f命令实时查看Docker容器日志的步骤:

$ docker logs -f my-nginx

输出为:

2021/07/22 03:44:01 [notice] 1#1: using the "epoll" event method
2021/07/22 03:44:01 [notice] 1#1: nginx/1.21.1
2021/07/22 03:44:01 [notice] 1#1: built by gcc 10.3.1 20210424 (Alpine 10.3.1_git20210424)
2021/07/22 03:44:01 [notice] 1#1: OS: Linux 5.10.47-linuxkit x86_64
2021/07/22 03:44:01 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/07/22 03:44:01 [notice] 1#1: start worker processes
...
2021/07/22 03:47:01 [notice] 1#1: worker process 6 exited with code 0
2021/07/22 03:47:01 [notice] 1#1: exit

通过按下Ctrl + C可以停止实时查看。

总结

在Docker容器中查看日志是调试和错误排查的重要步骤。使用tail命令可以查看实时日志,使用tail -f命令可以持续查看最新的日志内容。这些命令可以节省时间,提高生产力,也可以在故障排除时快速识别问题。