You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CloudWatch Agent配置中定义自定义指标,实现EC2 Ubuntu实例的Docker容器统计数据上报

上报Docker容器统计数据到CloudWatch的配置方案

嘿,我来帮你搞定把Docker容器指标上报到CloudWatch的事儿!既然你的CloudWatch Agent已经正常工作了,那咱们只需要修改/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json配置文件,添加自定义的Docker指标收集规则就行。下面分步骤给你讲清楚:

前置准备:给CloudWatch Agent授权访问Docker

首先得让CloudWatch Agent能执行Docker命令,把它加入docker用户组就行:

sudo usermod -aG docker cloudwatch-agent
sudo systemctl restart amazon-cloudwatch-agent

配置方案1:收集容器列表/状态统计(对应docker ps -a)

我们可以通过执行自定义Shell命令,解析docker ps -a的输出,把容器的状态(比如运行中、已停止)数量作为指标上报。在配置文件的metrics_collected节点下添加exec配置:

{
  "agent": {
    "metrics_collection_interval": 60,
    "run_as_user": "root"
  },
  "metrics": {
    "namespace": "MyDocker/ContainerStatus",
    "append_dimensions": {
      "InstanceId": "${aws:InstanceId}"
    },
    "metrics_collected": {
      "exec": [
        {
          "command": "docker ps -a --format '{{.Status}}' | awk '{print $1}' | sort | uniq -c | awk '{print \"container_status,status=\"$2\" count=\"$1}'",
          "name": "container_status_count",
          "metrics_format": "influx"
        }
      ],
      // 保留你原来的内存统计配置
      "mem": {
        "measurement": [
          "mem_used_percent"
        ],
        "metrics_collection_interval": 60
      }
    }
  }
}

配置说明:

  • command:执行的Shell命令,把docker ps -a的状态字段提取出来,统计每种状态的容器数量,输出成InfluxDB格式的字符串(CloudWatch Agent支持这种格式解析)。
  • metrics_format:指定输出格式为influx,Agent会自动解析成CloudWatch指标。
  • namespace:自定义的指标命名空间,方便你在CloudWatch里快速找到这些指标。

配置方案2:收集容器资源使用统计(对应docker stats)

如果要上报每个容器的CPU、内存、网络IO等实时数据,可以用docker stats的JSON输出,结合jq工具解析(需要先安装jq:sudo apt install jq -y)。在metrics_collected的exec里添加新的规则:

"exec": [
  // 上面的容器状态统计...
  {
    "command": "docker stats --no-stream --format '{{json .}}' | jq -r '. | \"container_resource,container_name=\(.Name),container_id=\(.ID) cpu_percent=\(.CPUPerc[:-1] | tonumber),mem_usage=\(.MemUsage | split(\"/\") | .[0] | gsub(\"MiB\";\"\") | tonumber),mem_percent=\(.MemPerc[:-1] | tonumber)\"'",
    "name": "container_resource_metrics",
    "metrics_format": "influx"
  }
]

配置说明:

  • docker stats --no-stream --format '{{json .}}':输出所有容器的统计数据为JSON格式,并且只输出一次(不持续流式输出)。
  • jq:解析JSON,提取容器名称、ID、CPU使用率、内存使用量、内存使用率,转成InfluxDB格式的指标字符串。
  • 这样每个容器的资源指标都会带上container_name和container_id的维度,方便在CloudWatch里按容器筛选查看。

应用配置并验证

修改完配置文件后,执行以下命令让Agent加载新配置:

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json -s

然后查看Agent日志,确认没有报错:

tail -f /var/log/amazon/amazon-cloudwatch-agent/amazon-cloudwatch-agent.log

等几分钟后,你就能在CloudWatch控制台的自定义命名空间下看到Docker相关的指标了!

内容的提问来源于stack exchange,提问作者Izak Joubert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:52:41