• 容器的监控和日志管理


    一、Docker监控工具和使用

    1、Docker自带的监控命令

    监控容器最简单的方法是使用Docker自带的监控命令:docker ps、docker top、docker stats。

    (1)docker ps查看容器状态

    可以使用 docker psdocker container ls 命令显示容器列表。

    # 语法
    [root@hqs ~]# docker ps --help
    Usage:  docker ps [OPTIONS选项]
    List containers
    Options:
      -a, --all             Show all containers (default shows just running)                        # 显示所有的容器(包括未运行的容器)
      -f, --filter filter   Filter output based on conditions provided                              # 根据条件过滤显示的容器
          --format string   Pretty-print containers using a Go template                             # go模式格式化打印容器
      -n, --last int        Show n last created containers (includes all states) (default -1)       # 列出最近创建的几个容器(含所有状态)
      -l, --latest          Show the latest created container (includes all states)                 # 列出最新创建的容器(含所有状态)
          --no-trunc        Dont truncate output                                                # 不截断输出(ID和COMMAND)
      -q, --quiet           Only display numeric IDs                                            # 只显示容器ID
      -s, --size            Display total file sizes                                            # 显示总文件大小
    
    # 案例
    [root@localhost docker]# docker ps 
    CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
    4fd309be3850   ubuntu    "/bin/bash"   3 seconds ago   Up 2 seconds             busy_cray
    

    (2)docker top查看容器进程

    查看容器中正在运行的进程。

    # 语法
    [root@localhost ~]# docker top --help
    Usage:  docker top CONTAINER [ps OPTIONS]
    Display the running processes of a container
    
    # 案例
    # 查看已有的容器的进程
    [root@localhost ~]# docker top busy_cray    《————注意替换为自己的容器
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    root                1467                1448                0                   01:33               pts/0               00:00:00            /bin/bash
    [root@localhost ~]# docker run -tid --name redis-test redis
    3a0d4ca05b5c3ab4b65beb333264b504247c6dd4cedee323a7ecdb41c518f6bc
    [root@localhost ~]# 
    [root@localhost ~]# docker top redis-test
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    polkitd             1655                1636                0                   01:34               pts/0               00:00:00            redis-server *:6379
    
    # 案例:跟参数的情况
    [root@localhost ~]# docker top redis-test -e
    PID                 TTY                 TIME                CMD
    1655                pts/0               00:00:03            redis-server
    [root@localhost ~]# docker top redis-test -f
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    polkitd             1655                1636                0                   01:34               pts/0               00:00:03            redis-server *:6379
    [root@localhost ~]# docker top redis-test -ef
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    polkitd             1655                1636                0                   01:34               pts/0               00:00:00            redis-server *:6379
    [root@localhost ~]# docker top redis-test aux
    USER                PID                 %CPU                %MEM                VSZ                 RSS                 TTY                 STAT                START               TIME                COMMAND
    polkitd             1655                0.1                 0.4                 52812               9880                pts/0               Ssl+                01:34               0:00                redis-server *:6379
    
    # 案例:查看所有正在运行的容器中的进程信息
    [root@localhost ~]# for i in `docker ps | grep Up|awk '{print $1}'`;do echo \ &&docker top $i;done
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    polkitd             1655                1636                0                   01:34               pts/0               00:00:00            redis-server *:6379
     
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    root                1467                1448                0                   01:33               pts/0               00:00:00            /bin/bash
     
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    root                1521                1503                0                   01:33               pts/0               00:00:00            /bin/bash
     
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    root                1575                1556                0                   01:33               pts/0               00:00:00            /bin/bash
    

    (3)docker stats查看容器资源使用

    docker stats 命令实时查看容器的系统资源使用情况。

    # 语法
    [root@localhost ~]# docker stats --help
    Usage:  docker stats [OPTIONS] [CONTAINER...]
    Display a live stream of container(s) resource usage statistics
    Options:
      -a, --all             Show all containers (default shows just running)        # 显示所有的容器(默认只显示运行中的容器)
          --format string   Pretty-print images using a Go template                 # 根据指定格式显示内容
          --no-stream       Disable streaming stats and only pull the first result  # 只显示第一条记录
          --no-trunc        Do not truncate output                                  # 不截断输出,显示出完整的信息(id)
    
    # 案例1:默认查看————连续刷新输出
    [root@localhost ~]# docker run -tid --name test1 -m 300M  ubuntu /bin/bash
    a63b5add08d9039c0347ddd16a64098ce43e1f917463ee2215f6974031772e2b
    [root@localhost ~]# docker stats
    容器ID         容器名称        CPU使用百分比    使用内存/最大可用内存  内存使用百分比  网络I/O     磁盘I/O     进程ID
    CONTAINER ID   NAME                  CPU %     MEM USAGE / LIMIT     MEM %     NET I/O       BLOCK I/O     PIDS
    a63b5add08d9   test1                 0.00%     536KiB / 300MiB       0.17%     648B / 0B     0B / 0B       1
    3a0d4ca05b5c   redis-test            0.10%     7.695MiB / 1.936GiB   0.39%     648B / 0B     39.4MB / 0B   5
    4fd309be3850   busy_cray             0.00%     1.59MiB / 300MiB      0.53%     1.09kB / 0B   8.16MB / 0B   1
    53c7acadfb91   quizzical_clarke      0.00%     544KiB / 300MiB       0.18%     996B / 0B     0B / 0B       1
    687d85c07aaf   xenodochial_swanson   0.00%     552KiB / 1.936GiB     0.03%     996B / 0B     0B / 0B       1  
    
    # 案例2:只输出当前状态(仅一条)
    [root@localhost ~]# docker stats --no-stream
    CONTAINER ID   NAME                CPU %     MEM USAGE / LIMIT     MEM %     NET I/O       BLOCK I/O     PIDS
    6a5891ff7c91   distracted_galois   0.00%     540KiB / 300MiB       0.18%     648B / 0B     0B / 0B       1
    ca8e91bf5a35   test                0.00%     1.586MiB / 1.936GiB   0.08%     1.09kB / 0B   8.13MB / 0B   1
    # 指定某个容器且只输出一次
    [root@localhost ~]# docker stats --no-stream test1
    CONTAINER ID   NAME      CPU %     MEM USAGE / LIMIT   MEM %     NET I/O     BLOCK I/O   PIDS
    a63b5add08d9   test1     0.00%     536KiB / 300MiB     0.17%     648B / 0B   0B / 0B     1
    
    # 案例3:只输出一次,且输出所有容器(包含停止)的状态
    [root@localhost ~]# docker ps -a
    CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS      NAMES
    4393de823c60   ubuntu    "bash"                   36 seconds ago   Exited (0) 36 seconds ago              happy_leakey
    df240f1a0d45   ubuntu    "bash"                   37 seconds ago   Exited (0) 37 seconds ago              interesting_poitras
    2570e260027e   ubuntu    "bash"                   47 seconds ago   Exited (0) 46 seconds ago              adasdsad
    ...略
    [root@localhost ~]# docker stats --no-stream -a
    CONTAINER ID   NAME                  CPU %     MEM USAGE / LIMIT     MEM %     NET I/O       BLOCK I/O     PIDS
    4393de823c60   happy_leakey          0.00%     0B / 0B               0.00%     0B / 0B       0B / 0B       0
    df240f1a0d45   interesting_poitras   0.00%     0B / 0B               0.00%     0B / 0B       0B / 0B       0
    2570e260027e   adasdsad              0.00%     0B / 0B               0.00%     0B / 0B       0B / 0B       0
    a63b5add08d9   test1                 0.00%     536KiB / 300MiB       0.17%     648B / 0B     0B / 0B       1
    3a0d4ca05b5c   redis-test            0.08%     7.695MiB / 1.936GiB   0.39%     648B / 0B     39.4MB / 0B   5
    4fd309be3850   busy_cray             0.00%     1.91MiB / 300MiB      0.64%     1.09kB / 0B   8.16MB / 0B   1
    53c7acadfb91   quizzical_clarke      0.00%     544KiB / 300MiB       0.18%     996B / 0B     0B / 0B       1
    687d85c07aaf   xenodochial_swanson   0.00%     552KiB / 1.936GiB     0.03%     996B / 0B     0B / 0B       1
    
    # 案例4:查看某个容器内存限制
    [root@localhost ~]# docker stats test1
    CONTAINER ID   NAME      CPU %           MEM USAGE / LIMIT      MEM %           NET I/O     BLOCK I/O   PIDS
    a63b5add08d9   test1     0.00%           536KiB / 300MiB        0.17%           648B / 0B   0B / 0B     1
    
    # 案例5:自定义输出的内容和格式
    [root@localhost ~]# docker stats --no-stream --format "{{.ID}}"
    6a5891ff7c91
    ca8e91bf5a35
    [root@localhost ~]# docker stats --no-stream  --format  "{{.Name}}" test1
    test1
    [root@localhost ~]# docker stats --no-stream  --format  "{{json .Name}}" test1
    "test1"
    [root@localhost ~]# docker stats --no-stream  --format  "{{json .Name}}-{{.CPUPerc}}-{{.MemUsage}}" test1
    "test1"-0.00%-536KiB / 300MiB
    [root@localhost ~]# docker stats --no-stream  --format  "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" test1
    NAME      CPU %     MEM USAGE / LIMIT
    test1     0.00%     536KiB / 300MiB
    [root@localhost ~]# docker stats --no-stream  --format  "table {{.ID}}\t{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}" myweb
    CONTAINER ID   NAME      CPU %     MEM USAGE / LIMIT     MEM %     NET I/O          BLOCK I/O     PIDS
    463b15216693   myweb     0.00%     11.57MiB / 1.936GiB   0.58%     2.84kB / 1.5kB   11.9MB / 0B   109
    [root@localhost ~]# docker stats --no-stream  --format  "{{.ID}}-{{.Name}}-{{.CPUPerc}}-{{.MemUsage}}-{{.MemPerc}}-{{.NetIO}}-{{.BlockIO}}-{{.PIDs}}" myweb
    463b15216693-myweb-0.00%-11.57MiB / 1.936GiB-0.58%-2.84kB / 1.5kB-11.9MB / 0B-109
    

    2、第三方工具cAdvisor

    用于分析正在运行的容器的资源占用情况和性能指标,是具有图形界面、最易于入门的Docker容器监控工具。

    cAdvisor以守护进程方式运行,负责收集、聚合、处理、输出运行中容器的数据,可以监控资源隔离参数、历史资源使用情况和网络统计数据。

    # 使用cAdvisor案例
    # 1.启动容器用于测试
    [root@localhost ~]# docker run --rm -d --name redis redis
    b1435f629a764712cf235b63a498e6b5cd58c44e8384146467e79f43233c4652
    [root@localhost ~]# docker run --rm -d --name myweb -p 80:80 httpd
    dfe1728c9576d72ef2d3652bc0b319e977ff63c8064f8f5aa35ff79b141ff32d
    [root@localhost ~]# docker ps 
    CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                               NAMES
    dfe1728c9576   httpd     "httpd-foreground"       5 seconds ago    Up 4 seconds    0.0.0.0:80->80/tcp, :::80->80/tcp   myweb
    b1435f629a76   redis     "docker-entrypoint.s…"   30 seconds ago   Up 29 seconds   6379/tcp                            redis
    
    # 2.创建启动cAdvisor容器
    # 拉取镜像
    [root@localhost ~]# docker pull google/cadvisor
    Using default tag: latest
    latest: Pulling from google/cadvisor
    ff3a5c916c92: Pull complete 
    44a45bb65cdf: Pull complete 
    0bbe1a2fe2a6: Pull complete 
    Digest: sha256:815386ebbe9a3490f38785ab11bda34ec8dacf4634af77b8912832d4f85dca04
    Status: Downloaded newer image for google/cadvisor:latest
    docker.io/google/cadvisor:latest
    # 启动容器:
    # 4个volume定义的绑定挂载都不能缺,否则无法连接docker守护进程
    # centos/redhat主机的容器,必须加上--privileged选项,才能真正拥有root权限,检测主机上的设备
    [root@localhost ~]# docker run --privileged \
    > --volume /:/rootfs:ro --volume /var/run:/var/run:rw \
    > --volume /sys:/sys:ro --volume /var/lib/docker/:/var/lib/docker:ro \
    > --publish 8080:8080 --detach --name cadvisor google/cadvisor:latest
    7ecef0c00cb922d9686db11234325a00609bf38bde3c9b26f3529245f0eb59af
    
    # 3.访问 cAdvisor监控服务
    # 再创建一个限制资源的容器
    [root@localhost ~]# docker run -m 300M --memory-swap 500M --memory-reservation 200M -c 512 -tid  ubuntu 
    d2eb61efefcf30687a4e70a43793866ffccb7d286e1f2f1ba144a43e91928a8f
    访问网址:http://[主机IP]:8080
    案例访问:http://192.168.100.111:8080/containers/
    
    

    页面访问如下:
    cAdvisor监控

    cAdvisor提供配置:
    --storage_duration:历史数据保存的时间,默认为2min,即只保存最近2min的数据。
    --allow_dynamic_housekeeping:控制cAdvisor如何和何时执行周期性的容器状态收集工作。
    --global_housekeeping_interval:设置检测是否有新容器的时间周期。
    --housekeeping_interval:统计每个容器数据的时间周期,默认每1s取一次数据,选取统计到的最近的60个数据。

    cAdvisor将数据直接导出到本地文件:

    [root@localhost ~]# docker run --volume /:/rootfs:ro \
     --volume /var/run:/var/run:rw --volume /sys:/sys:ro \
     --volume /var/lib/docker/:/var/lib/docker:ro \
     --publish 8080:8080 --name cadvisor-stdout \
     google/cadvisor:latest --storage_driver stdout >> data
     
    [root@localhost ~]# du -sh *
    4.0K	anaconda-ks.cfg
    104K	data
    
    [root@localhost ~]# cat data 
    

    cAdvisor优势:可以将监控数据导出给第三方工具;劣势:只能监控一个主机,数据展示功能有限。

    3、Weave Scope

    开源的故障诊断与监控工具,除了用于Docker外,还可以用于Kubernetes集群。

    Weave Scope会自动生成容器之间的关系图,便于管理员直观地以可视化的方式监控容器化和微服务化的应用。

    Weave Scope能够进行跨主机监控,并且消耗的资源非常少。

    Weave Scope主要功能:

    • 实时了解容器状态
    • 提供内部细节与深度链接
    • 支持容器的交互与管理
    • 通过插件进行扩展与定制

    (1)Weave Scope安装

    前提是安装并运行Docker,此软件以容器方式运行。

    # 1.下载二进制安装脚本
    curl -L git.io/scope -o /usr/local/bin/scope
    
    # 2.赋予脚本可执行权限
    chmod a+x /usr/local/bin/scope
    
    # 3.执行命令下载镜像并启动容器
    scope launch
    

    二、Docker日志管理

    对运行中的容器,Docker会将日志发送到容器的 STDOUT 和STDERR 上。
    可以将STDOUT 和STDERR视为容器的控制台终端。

    1、容器日志管理工具

    (1)docker logs

    docker logs命令输出正在运行的容器的日志信息。默认输出自容器启动以来完整的日志。

    docker logs命令可能不会显示有用信息的两种情形:

    • 如果使用将日志发送到文件、外部主机、数据库或另外一个后端日志系统的日志驱动,则docker logs命令不会显示有用信息,这时可以通过其他方式处理日志。
    • 如果镜像运行的是Web服务器或数据库等非交互式进程,那么应用程序可能会将输出发送到日志文件而不是STDOUT和STDERR中。
    • 如果容器以后台方式运行,则也不能看到输出的日志。
    # 语法
    [root@localhost ~]# docker logs --help
    Usage:  docker logs [OPTIONS] CONTAINER
    Fetch the logs of a container
    Options:
          --details        Show extra details provided to logs        # 显示更详细的日志信息
      -f, --follow         Follow log output                          # 跟踪日志输出
          --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m
                           for 42 minutes)                            # 显示某时间戳之后的日志或显示多少时间之内的日志
      -n, --tail string    Number of lines to show from the end of the logs (default "all")   # 从最后一行开始显示N行
      -t, --timestamps     Show timestamps                            # 显示时间戳
          --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g.
                           42m for 42 minutes)                        # 显示某时间戳之前的日志或显示多少分钟之前的日志
    
    # 案例1:访问查看日志
    # 1.创建apache容器
    [root@localhost ~]# docker run --rm -d -p 8080:80 --name web-http httpd
    8e226c5a8c4fdcd3bcb91f716d01b2876dda98cc8bc0179021ae783ddf45196b
    # 2.访问apache和查看日志
    在浏览器访问:http://10.10.10.111:8080
    [root@localhost ~]# docker logs web-http
    ...省略
    10.10.10.1 - - [25/May/2022:08:23:32 +0000] "GET / HTTP/1.1" 200 45
    # 3.显示更详细信息
    [root@localhost ~]# docker logs --details web-http      《————对httpd容器没有区别
    
    # 案例2:持续显示新日志
    [root@localhost ~]# docker logs -f web-http
    ...省略
    10.10.10.1 - - [25/May/2022:08:32:04 +0000] "GET / HTTP/1.1" 304 -    《————每次访问页面都会输出新日志
    10.10.10.1 - - [25/May/2022:08:32:06 +0000] "GET / HTTP/1.1" 304 -
    10.10.10.1 - - [25/May/2022:08:32:08 +0000] "GET / HTTP/1.1" 304 -
    
    # 案例3:显示时间戳(对没有时间的日志非常有用)
    [root@localhost ~]# docker logs -t web-http
    2022-05-25T08:22:59.900685745Z AH00558: httpd: Could not reliably determine the servers f..   《————前面都会加上时间戳
    
    # 案例4:显示最后几行
    [root@localhost ~]# docker logs -n 3  web-http
    10.10.10.1 - - [25/May/2022:08:32:06 +0000] "GET / HTTP/1.1" 304 -
    10.10.10.1 - - [25/May/2022:08:32:08 +0000] "GET / HTTP/1.1" 304 -
    10.10.10.1 - - [25/May/2022:08:32:55 +0000] "-" 408 -
    
    # 案例5:显示最后一分钟内的日志
    [root@localhost ~]# docker logs --since 1m  web-http
    10.10.10.1 - - [25/May/2022:08:41:51 +0000] "GET / HTTP/1.1" 304 -
    
    # 案例6:显示某个时间戳之后的日志
    [root@localhost ~]# docker logs --since 2022-05-25T08:32:10.339156073Z web-http
    10.10.10.1 - - [25/May/2022:08:32:55 +0000] "-" 408 -
    10.10.10.1 - - [25/May/2022:08:41:51 +0000] "GET / HTTP/1.1" 304 -
    10.10.10.1 - - [25/May/2022:08:42:42 +0000] "-" 408 -
    
    # 案例7:显示多少分钟之前的日志
    [root@localhost ~]# docker logs --until 30m  web-http
    ...省略
    10.10.10.1 - - [25/May/2022:08:23:32 +0000] "GET / HTTP/1.1" 200 45
    10.10.10.1 - - [25/May/2022:08:24:23 +0000] "-" 408 -
    
    # 案例8:显示某时间戳之前的日志
    [root@localhost ~]# docker logs --until 2022-05-25T08:32:10.339156073Z web-http
    ...省略
    10.10.10.1 - - [25/May/2022:08:31:56 +0000] "GET / HTTP/1.1" 304 -
    10.10.10.1 - - [25/May/2022:08:32:04 +0000] "GET / HTTP/1.1" 304 -
    

    (2)docker service logs

    docker service logs命令显示swarm某服务/任务的所有容器的日志信息。

    该命令适用于集群环境。

    # 语法
    [root@localhost ~]# docker service logs --help
    Usage:  docker service logs [OPTIONS] SERVICE|TASK
    Fetch the logs of a service or task
    Options:
          --details        Show extra details provided to logs
      -f, --follow         Follow log output
          --no-resolve     Do not map IDs to Names in output
          --no-task-ids    Do not include task IDs in output
          --no-trunc       Do not truncate output
          --raw            Do not neatly format logs
          --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m
                           for 42 minutes)
      -n, --tail string    Number of lines to show from the end of the logs (default "all")
      -t, --timestamps     Show timestamps
    

    2、容器日志驱动

    日志驱动(Logging Driver):Docker提供的帮助用户从运行的容器中提取日志信息的机制。默认的日志驱动是 json-file

    选项值如下:

    选项值 说明
    none 禁用容器日志,docker logs命令不会输出任何日志信息
    json-file Docker默认的日志驱动。该驱动将日志保存在JSON文件中,Docker负责格式化其内容并输出到STDOUT和STDERR
    syslog 将日志信息写入syslog日志系统,syslog守护进程必须在主机上运行
    journald 将日志信息写入journald日志系统,journald守护进程必须在主机上运行
    gelf 将日志信息写入像Graylog或Logstash这样的GELF(Graylog Extended Log Format)终端
    fluentd 将日志信息写入fluentd,fluentd守护进程必须在主机上运行
    splunk 将日志信息写入使用HTTP事件搜集器的splunk

    (1)配置默认的日志驱动

    daemon.json文件中的log-driver值设为日志驱动名称。

    案例1:将默认日志驱动设为syslog

    [root@localhost ~]# vi /etc/docker/daemon.json 
    [root@localhost ~]# cat /etc/docker/daemon.json 
    {
      "registry-mirrors": ["https://nxwgbmaq.mirror.aliyuncs.com"],
      "log-driver":"syslog"
    }
    [root@localhost ~]# systemctl daemon-reload
    [root@localhost ~]# systemctl restart docker
    

    log-opts可以配置可配置选项。
    案例2:日志驱动可配置选项

    [root@localhost ~]# vi /etc/docker/daemon.json         《————注意:改之前将之前驱动的容器都删除
    {
      "registry-mirrors": ["https://nxwgbmaq.mirror.aliyuncs.com"],
      "log-driver":"json-file",
      "log-opts":{
        "labels":"production_status",
        "env":"os,customer"
      }
    }
    
    [root@localhost ~]# docker info | grep 'Logging Driver'
     Logging Driver: syslog
    [root@localhost ~]# systemctl daemon-reload
    [root@localhost ~]# systemctl restart docker
    # 查看守护进程的默认日志驱动是否改变:
    [root@localhost ~]# docker info | grep 'Logging Driver'
     Logging Driver: json-file
    # 查看容器的配置选项
    [root@localhost ~]# docker run -tid --name test-opt  ubuntu
    5d8ad65d59bca65a988ef0b5c17504601fdc82d2d14b41619e981983bc9bc76d
    [root@localhost ~]# docker inspect -f='{{.HostConfig.LogConfig.Type}}--{{.HostConfig.LogConfig.Config}}' test-opt
    json-file--map[env:os,customer labels:production_status]
    

    (2)配置容器的日志驱动

    启动容器时,可以使用--log-driver 选项来配置日志驱动,可以使用--log-opt设置可配置选项(可以以键值对的方式配置多个)。

    注意:说明同一个值配两次,最后一个生效。

    [root@localhost ~]# docker run --help
          --log-driver string              Logging driver for the
                                           container            # 配置容器的日志驱动
          --log-opt list                   Log driver options   # 配置容器的日志驱动可配置选项
    
    # 案例1:配驱动和查看
    [root@localhost ~]# docker run --rm -d --log-driver none --name redis redis
    cf2d244c250a8b9d457e4f601cd359c73dc9d530788890b6ffd74406293c94f0
    [root@localhost ~]# docker inspect -f='{{.HostConfig.LogConfig.Type}}' redis
    none
    # 案例2:配驱动和可配置选项
    [root@localhost ~]# docker run --rm -d --log-driver syslog --log-opt env=os,customer --log-opt labels='test' --name redis02 redis
    8cd319bde772774fa00950efa80608ea05823023799554a5e45248c768a3ce29
    [root@localhost ~]# docker inspect -f='{{.HostConfig.LogConfig.Type}}-{{.HostConfig.LogConfig.Config}}' redis02
    syslog-map[env:os,customer labels:test]
    

    3、容器日志清理

    容器的日志文件会占用大量的空间,经常需要进行清理。如果直接删除 /var/lib/docker/containers/<容器id> 目录下的日志文件,并不会释放磁盘空间,因为日志文件是被打开的。

    (1)清理正在运行的容器日志的shell脚本

    #!/bin/sh 
    logs=$(find /var/lib/docker/containers/ -name *-json.log)  
    for log in $logs  
        do  
             echo "clean logs : $log"  
             cat /dev/null > $log  
        done
    

    (2)限制容器的日志上限

    在daemon.json配置文件中通过log-opts选项来限制日志大小的上限

    "log-driver":"json-file",
    "log-opts": {"max-size":"500m", "max-file":"2"} 
    

    上例中设置容器日志大小上限是500M,容器最多有两个日志文件。

    4、将容器的日志重定向到LINUX日志系统

    运行在Linux操作系统的Docker主机上可以通过配置日志驱动将容器的日志重定向到Linux日志系统。

    (1)将容器日志记录到syslog

    syslog是Linux标配的日志记录工具,主要用来收集系统产生的各种日志,日志文件默认放在/var/log目录下。

    选择syslog作为日志驱动可将日志定向输出到syslog日志系统中,条件是:syslog守护进程必须在主机上运行。

    # 打开或复制一个终端窗口,使用tail工具实时监控系统日志文件/var/log/messages。
    [root@host1 ~]# tail -f /var/log/messages
    # 打开另一个终端窗口,创建容器,将该容器的日志记录到syslog日志文件。
    [root@localhost containers]# docker run --rm -d --log-driver syslog --name redis03 redis
    2d7cba9c0c6466c0ecb18e4bfd156710148c8205b299e05f3eed987f873f8b8e
    # 观察/var/log/messages输出:
    May 26 03:01:06 localhost dockerd: time="2022-05-26T03:01:06.231489908+08:00" level=info msg="Configured log driver does not support reads, enabling local file cache for container logs" container=2d7cba9c0c6466c0ecb18e4bfd156710148c8205b299e05f3eed987f873f8b8e driver=syslog
    

    (2)将容器日志记录到journald

    journald是一个收集并存储日志数据的 systemd 日志系统服务,可以使用 journalctl 命令查看它。

    选择journald作为日志驱动可将日志定向输出到systemd日志系统中。

    # 创建容器
    [root@localhost ~]# docker run --rm -d --log-driver journald --name ubuntu01 ubuntu
    cdd3963ab27eac51e8a7d5fc43f92e0f9fb921705e235af822b41bf555a80e23
    # 查看systemd日志系统
    [root@localhost containers]# journalctl
    # 进入日志系统后,输入大写"GG",翻到日志的最后一页
    May 26 03:36:10 localhost.localdomain dockerd[3090]: time="2022-05-26T03:36:10.292765481+08:00" level=info msg="ignoring event" container=cdd3963ab27eac51e8a7d5fc43f92e0f9fb921705e235af822b
    May 26 03:36:10 localhost.localdomain containerd[876]: time="2022-05-26T03:36:10.293637172+08:00" level=info msg="shim disconnected" id=cdd3963ab27eac51e8a7d5fc43f92e0f9fb921705e235af822b41
    May 26 03:36:10 localhost.localdomain containerd[876]: time="2022-05-26T03:36:10.293708026+08:00" level=warning msg="cleaning up after shim disconnected" id=cdd3963ab27eac51e8a7d5fc43f92e0f
    May 26 03:36:10 localhost.localdomain containerd[876]: time="2022-05-26T03:36:10.293715955+08:00" level=info msg="cleaning up dead shim"
    May 26 03:36:10 localhost.localdomain containerd[876]: time="2022-05-26T03:36:10.302648699+08:00" level=warning msg="cleanup warnings time=\"2022-05-26T03:36:10+08:00\" level=info msg=\"sta
    

    5、使用Logspout收集所有容器的日志

    Logspout 是一个 Docker 容器,大小仅 14MB,使用 BusyBox 作为其核心,它可以将来自容器应用程序的日志发送到某一个中央位置,比如单一 JSON 对象或者通过 HTTP API 可获得的流式端点。

    -t 选项容器会以前台方式运行。
    -e 选项可以设置容器环境变量。可以用来排除对某个容器日志路由:-e "LOGSPOUT=ignore"

    (1)将所有容器的输出路由到远程syslog

    案例:将所有日志转发给远程的syslog服务器,这里将本地服务器作为远程syslog服务器。

    # 1.修改centos7的日志服务器rsyslog配置文件
    [root@localhost ~]# vi /etc/rsyslog.conf
    # 找到一下内容(15\16行)去除行首的‘#’
    $ModLoad imudp
    $UDPServerRun 514
    # 改完后,就允许rsyslog服务在UDP的514端口接收日志信息了。
    
    # 2.重启rsyslog,检查514端口是否开启
    [root@localhost ~]# systemctl restart rsyslog
    # 安装网络工具
    [root@localhost ~]# yum install -y net-tools
    # 检查514端口
    [root@localhost ~]# netstat -antup | grep 514
    tcp        0      0 192.168.100.111:22      192.168.100.1:55959     ESTABLISHED 1514/sshd: root@pts 
    udp        0      0 0.0.0.0:514             0.0.0.0:*                           4172/rsyslogd       
    udp6       0      0 :::514                  :::*                                4172/rsyslogd
    
    # 3.启动logspout容器,将日志转发到docker主机的syslog服务中
    # 下载logspout镜像
    [root@localhost ~]# docker pull gliderlabs/logspout
    Using default tag: latest
    latest: Pulling from gliderlabs/logspout
    8572bc8fb8a3: Pull complete 
    bd801371a862: Pull complete 
    58100c398b34: Pull complete 
    Digest: sha256:2d81c026e11ac67f7887029dbfd7d36ee986d946066b45c1dabd966278eb5681
    Status: Downloaded newer image for gliderlabs/logspout:latest
    docker.io/gliderlabs/logspout:latest
    # 拉起容器
    # 注意:logspout需要访问docker守护进程来获取日志,因此需要把UNIX sockets挂载到容器内。
    [root@localhost ~]# docker run --name="logspout" --volume=/var/run/docker.sock:/var/run/docker.sock gliderlabs/logspout syslog+udp://192.168.100.111:514
    2022/05/25 20:03:20 # logspout v3.2.14 by gliderlabs
    2022/05/25 20:03:20 # adapters: tls udp multiline raw syslog tcp
    2022/05/25 20:03:20 # options : 
    2022/05/25 20:03:20 persist:/mnt/routes
    2022/05/25 20:03:20 # jobs    : http[routes,health,logs]:80 pump routes
    2022/05/25 20:03:20 # routes  :
    #   ADAPTER	ADDRESS			CONTAINERS	SOURCES	OPTIONS
    #   syslog+udp	192.168.100.111:514				map[]
    
    # 4.监控和验证
    # 打开syslog日志监控
    [root@localhost containers]# tail -f /var/log/messages
    # 启动一个新容器
    [root@localhost ~]# docker run --rm -d --name redis10 redis
    8113851c267c18a5cfe51cde0ad923c8abb5b949aec34df528ba3db3b61a90ed
    # 查看到新刷出的日志信息
    May 26 04:06:43 localhost containerd: time="2022-05-26T04:06:43.783205236+08:00" level=info msg="starting signal loop" namespace=moby path=/run/containerd/io.containerd.runtime.v2.task/moby/8113851c267c18a5cfe51cde0ad923c8abb5b949aec34df528ba3db3b61a90ed pid=4728
    

    (2)通过HTTP查看Logspout收集的日志

    使用 Logspout 的HTTP流模块,可以实时查看由它聚合的本地日志,而不用提供日志路由的URI。

    # 1.使用Logspout的HTTP流模块,实时查看由它聚合的本地日志
    [root@localhost ~]# docker run -d --name="logspout02" --volume=/var/run/docker.sock:/var/run/docker.sock \
    >  --publish=127.0.0.1:8000:80 gliderlabs/logspout
    5571173f20bfb08f7935cb0e819d34580753a22b3963d1573f26c8df7ad75900
    
    # 2.使用curl观察容器的日志流。
    [root@localhost ~]# curl http://127.0.0.1:8000/logs
    
    # 3.打开另一个终端窗口,启动redis容器
    [root@localhost ~]# docker run --rm -d --name redis06 redis
    7cd8769551266de5955147e409dd48ed9d6df6c41a6d33a9326beed0924a030f
    
    # 4.切回日志流的终端窗口,会发现关于redis容器启动的日志流。
    redis06|1:C 26 May 2022 20:09:47.862 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
    redis06|1:C 26 May 2022 20:09:47.862 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
    ...略
    
  • 相关阅读:
    使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象?”。
    《大道至简》第三章读后感
    动手动脑
    zencart设置特价商品价格
    如何设置zencart买满多少免运费?
    zencart分类页每页显示产品数量自定义选择的方法
    Access数据库LIKE问题
    zencart清空产品商品实用命令
    dedecms织梦后台发布文章提示“标题不能为空”的解决办法
    zencart重置用户登录密码sql
  • 原文地址:https://www.cnblogs.com/xiugeng/p/16285637.html
Copyright © 2020-2023  润新知