

# Container Insights 收集的指标
<a name="Container-Insights-metrics"></a>

Container Insights 为 Amazon ECS 和 Amazon ECS 上的 AWS Fargate 收集一组指标，并为 Amazon EKS、Amazon EKS 上的 AWS Fargate、RedHat OpenShift on AWS (ROSA) 和 Kubernetes 收集另一组指标。

容器任务运行一段时间后，指标才可见。

**Topics**
+ [具有增强型可观测性的 Amazon ECS Container Insights](Container-Insights-enhanced-observability-metrics-ECS.md)
+ [Amazon ECS Container Insights 指标](Container-Insights-metrics-ECS.md)
+ [具有增强型可观测性的 Amazon EKS 和 Kubernetes Container Insights](Container-Insights-metrics-enhanced-EKS.md)
+ [Amazon EKS 和 Kubernetes Container Insights 指标](Container-Insights-metrics-EKS.md)
+ [Container Insights 性能日志参考](Container-Insights-reference.md)
+ [Container Insights Prometheus 指标监控](ContainerInsights-Prometheus.md)
+ [与 Application Insights 集成](container-insights-appinsights.md)
+ [在 Container Insights 内查看 Amazon ECS 生命周期事件](container-insights-ECS-lifecycle-events.md)
+ [Container Insights 问题排查](ContainerInsights-troubleshooting.md)
+ [构建您自己的 CloudWatch 代理 Docker 镜像](ContainerInsights-build-docker-image.md)
+ [在容器中部署其他 CloudWatch 代理功能](ContainerInsights-other-agent-features.md)

# 具有增强型可观测性的 Amazon ECS Container Insights
<a name="Container-Insights-enhanced-observability-metrics-ECS"></a>

具有增强型可观测性的 Container Insights 具备以下特点，可以帮助用户更深入地了解容器化工作负载：
+ 任务和容器级别的更高指标粒度
+ 改进的监控和问题排查功能
+ 与 CloudWatch Logs 集成，可用于：
  + 将指标异常与日志条目相关联
  + 更快地进行根本原因分析
  + 缩短复杂容器问题的解决时间

**使用案例**

具有增强型可观测性的 Container Insights 扩展了标准 Container Insights 的功能，并且支持以下使用案例：
+ **任务级别问题排查**：确定任务级别的性能瓶颈。分析任务级别指标并将指标与预留资源进行比较，确定任务是否有足够的处理能力 
+ **容器级别资源优化**：跟踪预留级别的利用率，确定资源受限或过度预置的容器 
+ **容器运行状况评测**：监控重启计数和状态转换，检测需要干预的不稳定容器 
+ **应用程序性能监控**：跟踪应用程序如何相互通信，监控资源使用模式并优化数据存储性能
+ **运行监控**：监控部署，跟踪蓝色或绿色部署的任务集，并通过服务指标维护平台运行状况

有关 Amazon ECS 指标的更多信息，请参阅 [Amazon ECS 服务利用率指标使用案例](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_utilization-metrics-explanation.html)；有关具有增强型可观测性的 Container Insights 的信息，请参阅[具有增强型可观测性的 Amazon ECS Container Insights 指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-enhanced-observability-metrics-ECS.html)。

Container Insights 还会计算所有任务的数据平均值，以显示集群、服务和进程守护程序范围的统计数据。这有助于更深入地了解服务和进程守护程序的运行状况，为环境监控和容量规划提供支持。

**注意**  
Amazon ECS 托管进程守护程序指标使用与服务指标相同的 `ECS/ContainerInsights` 命名空间和 `ServiceName` 维度。对于进程守护程序指标，`ServiceName` 维度值使用 `daemon:daemon-name` 格式。例如，名为 `my-daemon` 的进程守护程序的 `ServiceName` 维度值为 `daemon:my-daemon`。下表中包含 `ServiceName` 维度的所有指标也适用于托管进程守护程序。

下表列出了具有增强型可观测性的 Container Insights 针对 Amazon ECS 收集的指标和维度。这些指标位于 `ECS/ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果在控制台中未看到任何 Container Insights 指标，请确保已完成具有增强型可观测性的 Container Insights 的设置。在完全设置具有增强型可观测性的 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置具有增强型可观测性的 Container Insights](deploy-container-insights-ECS-cluster.md#set-container-insights-ECS-cluster-enhanced)。

以下指标适用于所有启动类型。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `ContainerInstanceCount`  |  `ClusterName`  |  注册到集群的运行 Amazon ECS 代理的 EC2 实例的数目。 仅针对在集群中运行 Amazon ECS 任务的容器实例收集此指标。对于没有任何 Amazon ECS 任务的空容器实例，不会收集此指标。 单位：个  | 
|  `ContainerCpuUtilized`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器使用的 CPU 单元。 也适用于托管进程守护程序。 单位：无  | 
|  `ContainerCpuReserved`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器预留的 CPU 单元。根据任务定义（例如任务级别或所有容器级别）中指定的 CPU 预留收集此指标。如果未在任务定义中指定 CPU 预留，则会使用实例 CPU 预留。 也适用于托管进程守护程序。 单位：无  | 
|  `ContainerCpuUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   | 您正在使用的维度集指定资源中容器正在使用的 CPU 单元总百分比。 单位：百分比 | 
|  `ContainerMemoryUtilized`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器正在使用的内存。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `ContainerMemoryReserved`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  |  您正在使用的维度集指定资源中容器预留的内存。 根据任务定义（例如任务级别或所有容器级别）中指定的内存预留收集此指标。如果未在任务定义中指定内存预留，则会使用实例内存预留。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `ContainerMemoryUtilization`  |  `ClusterName` `ContainerName`, `TaskId`, `ServiceName`, `ClusterName` `ContainerName`, `TaskDefinitionFamily`, `ClusterName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `ServiceName`, `ClusterName`, `ContainerName`  | 您正在使用的维度集指定资源中容器正在使用的内存总百分比。 也适用于托管进程守护程序。 单位：百分比 | 
|  `ContainerNetworkRxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您正在使用的维度指定容器接收的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `ContainerNetworkTxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您正在使用的维度指定容器传输的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `ContainerStorageReadBytes`  |  `ClusterName` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `TaskId`, `ContainerName`  |  从您正在使用的维度指定资源中容器上存储读取的字节数。这不包括存储设备的读取字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `ContainerStorageWriteBytes`  |  `ClusterName` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `TaskId`, `ContainerName`  |  写入到您正在使用的维度指定容器中存储的字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `CpuUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务在您使用的维度集所指定的资源中使用的 CPU 单元。 也适用于托管进程守护程序。 单位：无  | 
|  `CpuReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  任务在您使用的维度集所指定的资源中预留的 CPU 单元。根据任务定义（例如任务级别或所有容器级别）中指定的 CPU 预留收集此指标。如果未在任务定义中指定 CPU 预留，则会使用实例 CPU 预留。 也适用于托管进程守护程序。 单位：无  | 
|  `DeploymentCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务中的部署数。 单位：个  | 
|  `DesiredTaskCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务所需的任务数。 单位：个  | 
|  `EBSFilesystemSize`  |  `ClusterName` ,`TaskDefinitionFamily`, `VolumeName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  分配给您使用的维度所指定资源的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `EBSFilesystemUtilized`  |  `ClusterName` ,`TaskDefinitionFamily`, `VolumeName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  您使用的维度所指定资源使用的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 对于在 Fargate 上运行的任务，Fargate 会在磁盘上预留仅供 Fargate 使用的空间。Fargate 使用的空间不会产生任何成本，但可以使用类似 `df` 的工具看到额外的存储空间。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `TaskEBSFilesystemUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ClusterName`, `ServiceName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `TaskDefinitionFamily`, `ClusterName`, `TaskId`  |  您正在使用的维度指定的任务所使用的 Amazon EBS 文件系统存储的百分比。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 也适用于托管进程守护程序。 单位：百分比  | 
|  EphemeralStorageReserved [1](#ci-enhanced-metrics-ecs-storage-fargate-note)  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  从您使用的维度所指定的资源中临时存储保留的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  EphemeralStorageUtilized [1](Container-Insights-metrics-ECS.md#ci-metrics-ecs-storage-fargate-note)  |  `ClusterName` `ClusterName`, `TaskDefinitionFamily` `ClusterName`, `ServiceName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  从您使用的维度所指定的资源中临时存储使用的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `MemoryUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  任务在您使用的维度集所指定的资源中使用的内存。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `MemoryReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  任务在您使用的维度集所指定的资源中预留的内存。 根据任务定义（例如任务级别或所有容器级别）中指定的内存预留收集此指标。如果未在任务定义中指定内存预留，则会使用实例内存预留。 也适用于托管进程守护程序。 单位：兆字节  | 
|  `NetworkRxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您使用的维度所指定的资源接收的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `NetworkTxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  您使用的维度所指定的资源传输的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `PendingTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `PENDING` 状态的任务的数量。 单位：个  | 
|  `RunningTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `RUNNING` 状态的任务的数量。 单位：个  | 
|  `RestartCount`  |  `ClusterName` `ClusterName`, `ServiceName` `ClusterName`, `TaskDefinitionFamily` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `TaskDefinitionFamily`, `ClusterName`, `ContainerName` `TaskDefinitionFamily`, `ClusterName`, `TaskId`, `ContainerName`  |  Amazon ECS 任务中容器重新启动的次数。 仅会对启用了重启策略的容器收集此指标。 也适用于托管进程守护程序。 单位：个  | 
|  `UnHealthyContainerHealthStatus`  |  `ClusterName` `ClusterName`, `ServiceName`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `ContainerName` `ClusterName`, `ServiceName`, `TaskId`, `ContainerName` `ClusterName`, `TaskDefinitionFamily`, `TaskId`, `ContainerName`  |  基于容器运行状况检查状态的非正常运行容器的数量。当容器的运行状况检查结果为不正常状态时，该容器就被视为不正常。 此指标仅针对在任务定义中已配置运行状况检查的容器进行收集。 当容器运行状况为 `UNHEALTHY` 时，指标值为 1；当运行状况为 `HEALTHY` 时，指标值为 0。 单位：个  | 
|  `ServiceCount`  |  `ClusterName`  |  集群中的服务数。 单位：个  | 
|  `StorageReadBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  从您使用之维度所指定资源中实例上的存储读取的字节数。这不包括存储设备的读取字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `StorageWriteBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`  |  写入到您使用的维度所指定的资源中的存储的字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `TaskCount`  |  `ClusterName`  |  正在集群中运行的任务数。 单位：个  | 
|  `TaskCpuUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务使用的 CPU 单元的总百分比。 也适用于托管进程守护程序。 单位：百分比  | 
|  `TaskEphemeralStorageUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务使用的临时存储总百分比。 也适用于托管进程守护程序。 单位：百分比  | 
|  `TaskMemoryUtilization`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName` `ClusterName`, `ServiceName`, `TaskId` `ClusterName`, `TaskDefinitionFamily`, `TaskId`   |  任务使用的内存总百分比。 也适用于托管进程守护程序。 单位：百分比  | 
|  `TaskSetCount`  |  `ServiceName`, `ClusterName`  |  服务中设置的任务数。 单位：个  | 

**注意**  
`EphemeralStorageReserved` 和 `EphemeralStorageUtilized` 指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。  
Fargate 可保留磁盘空间。该磁盘空间仅由 Fargate 使用。您无需为此付费。它没有显示在这些指标中。但是，您可以在 `df` 等其他工具中看到这种额外的存储空间。

完成[部署 CloudWatch 代理以收集 Amazon ECS 上的 EC2 实例级别指标](deploy-container-insights-ECS-instancelevel.md)中的步骤并使用 EC2 启动类型后，以下指标将可用。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `instance_cpu_limit`  |  `ClusterName`  |  可分配给集群中单个 EC2 实例的 CPU 单元最大数目。 单位：无  | 
|  `instance_cpu_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的 CPU 的百分比。 单位：百分比  | 
|  `instance_cpu_usage_total`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的数目。 单位：无  | 
|  `instance_cpu_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的总百分比。 单位：百分比  | 
|  `instance_filesystem_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的文件系统容量的总百分比。 单位：百分比  | 
|  `instance_memory_limit`  |  `ClusterName`  |  可分配给此集群中单个 EC2 实例的最大内存量（以字节为单位）。 单位：字节  | 
|  `instance_memory_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的内存百分比。 单位：百分比  | 
|  `instance_memory_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存总百分比。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：百分比  | 
|  `instance_memory_working_set`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存量（以字节为单位）。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：字节  | 
|  `instance_network_total_bytes`  |  `ClusterName`  |  集群中单个 EC2 实例上通过网络传输和接收的每秒总字节数。 单位：字节/秒  | 
|  `instance_number_of_running_tasks`  |  `ClusterName`  |  集群中单个 EC2 实例上正在运行的任务数。 单位：个  | 

# Amazon ECS Container Insights 指标
<a name="Container-Insights-metrics-ECS"></a>

Container Insights 指标提供了额外的网络指标、存储指标和临时存储指标。这些指标提供的信息比标准 Amazon ECS 指标要多。Container Insights 与 CloudWatch Logs 集成。您可以将指标更改与日志条目相关联，以便于进行问题排查。Container Insights 还会计算所有任务的数据平均值，以显示集群、服务和进程守护程序范围的统计数据。这有助于更深入地了解服务和进程守护程序的运行状况，为环境监控和容量规划提供支持。

**使用案例**
+ **问题识别和故障排除**：通过分析任务状态转换模式来跟踪失败的部署，从而快速识别故障点。通过全面检查任务启动顺序和初始化行为来诊断配置问题
+ **集群和服务级别运行状况评测**：显示整个集群的平均任务性能。这种方法可以调节异常值，提供更稳定的集群和服务运行状况视图。使用这些洞察进行一般服务监控，极值在一般服务监控中可能会产生误导 
+ **服务可用性问题**：通过监控正在运行的任务计数指标来检测失败的部署。将服务事件日志与性能指标相关联，了解基础设施的影响。跟踪任务重启模式以发现不稳定的服务或基础设施问题
+ **平均负载的容量规划**：有助于根据典型的任务行为模式确定资源需求，提供适用于有效长期规划的一致指标，并减少短期峰值对容量决策的影响
+ **提供其他指标**：收集公开发布的指标中不可用的其他网络指标、存储指标和临时存储指标

有关 Amazon ECS 指标的更多信息，请参阅 [Amazon ECS 服务利用率指标使用案例](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_utilization-metrics-explanation.html)；有关具有增强型可观测性的 Container Insights 的信息，请参阅[具有增强型可观测性的 Amazon ECS Container Insights 指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-enhanced-observability-metrics-ECS.html)。

**注意**  
Amazon ECS 托管进程守护程序指标使用与服务指标相同的 `ECS/ContainerInsights` 命名空间和 `ServiceName` 维度。对于进程守护程序指标，`ServiceName` 维度值使用 `daemon:daemon-name` 格式。例如，名为 `my-daemon` 的进程守护程序的 `ServiceName` 维度值为 `daemon:my-daemon`。下表中包含 `ServiceName` 维度的所有指标也适用于托管进程守护程序。

下表列出了 Container Insights 收集的针对 Amazon ECS 的指标和维度。这些指标位于 `ECS/ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果您在控制台中未看到任何 Container Insights 指标，请确保已完成 Container Insights 的设置。在完全设置 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。

完成[在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS-cluster.md)中的步骤后，以下指标将可用。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `ContainerInstanceCount`  |  `ClusterName`  |  注册到集群的运行 Amazon ECS 代理的 EC2 实例的数目。 仅针对在集群中运行 Amazon ECS 任务的容器实例收集此指标。对于没有任何 Amazon ECS 任务的空容器实例，不会收集此指标。 单位：个  | 
|  `CpuUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中使用的 CPU 单元。 也适用于托管进程守护程序。 单位：无  | 
|  `CpuReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中预留的 CPU 单元。 根据任务定义（例如任务级别或所有容器级别）中指定的 CPU 预留收集此指标。如果未在任务定义中指定 CPU 预留，则会使用实例 CPU 预留。 也适用于托管进程守护程序。 单位：无  | 
|  `DeploymentCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务中的部署数。 单位：个  | 
|  `DesiredTaskCount`  |  `ServiceName`, `ClusterName`  |  Amazon ECS 服务所需的任务数。 单位：个  | 
|  `EBSFilesystemSize`  |  `VolumeName`, `TaskDefinitionFamily`, `ClusterName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  分配给您使用的维度所指定资源的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `EBSFilesystemUtilized`  |  `VolumeName`, `TaskDefinitionFamily`, `ClusterName` `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName`  |  您使用的维度所指定资源使用的 Amazon EBS 文件系统存储总量，以千兆字节（GB）为单位。 该指标仅适用于使用平台版本 `1.4.0` 在 Fargate 上运行的 Amazon ECS 基础设施上运行的任务，或在使用容器代理版本 `1.79.0` 或更高版本的 Amazon EC2 实例上运行的任务。 对于在 Fargate 上运行的任务，Fargate 会在磁盘上预留仅供 Fargate 使用的空间。Fargate 使用的空间不会产生任何成本，但可以使用类似 `df` 的工具看到额外的存储空间。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  EphemeralStorageReserved [1](#ci-metrics-ecs-storage-fargate-note)  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  从您使用的维度所指定的资源中临时存储保留的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  EphemeralStorageUtilized [1](#ci-metrics-ecs-storage-fargate-note)  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  从您使用的维度所指定的资源中临时存储使用的字节数。临时存储用于容器根文件系统以及容器映像和任务定义中所定义的任何绑定装载主机卷。无法在正在运行的任务中更改临时存储量。 该指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。 也适用于托管进程守护程序。 单位：千兆字节（GB）  | 
|  `InstanceOSFilesystemUtilization`  |  `CapacityProviderName`, `ClusterName`, `ContainerInstanceId`, `EC2InstanceId` `ClusterName`  |  操作系统卷已使用磁盘空间占总磁盘空间的百分比。  | 
|  `InstanceDataFilesystemUtilization`  |  `CapacityProviderName`, `ClusterName`, `ContainerInstanceId`, `EC2InstanceId` `ClusterName`  |  数据卷已使用磁盘空间占总磁盘空间的百分比。  | 
|  `MemoryUtilized`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中使用的内存。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。 尽管 `MemoryUtilized` 和 `MemoryReserved` 都标记为“兆字节”，但实际单位是 MiB（二进制兆字节）。  也适用于托管进程守护程序。 单位：兆字节  | 
|  `MemoryReserved`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  任务在您使用的维度集所指定的资源中预留的内存。根据任务定义（例如任务级别或所有容器级别）中指定的内存预留收集此指标。如果未在任务定义中指定内存预留，则会使用实例内存预留。 也适用于托管进程守护程序。 单位：兆字节  尽管 `MemoryUtilized` 和 `MemoryReserved` 都标记为“兆字节”，但实际单位是 MiB（二进制兆字节）。   | 
|  `NetworkRxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  您使用的维度所指定的资源接收的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `NetworkTxBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  您使用的维度所指定的资源传输的字节数。该指标是从 Docker 运行时系统获取的。 此指标仅适用于使用 `awsvpc` 或 `bridge` 网络模式的任务中的容器。 也适用于托管进程守护程序。 单位：字节/秒  | 
|  `PendingTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `PENDING` 状态的任务的数量。 单位：个  | 
|  `RunningTaskCount`  |  `ServiceName`, `ClusterName`  |  当前处于 `RUNNING` 状态的任务的数量。 单位：个  | 
|  `RestartCount`  |  `ClusterName` `ClusterName`, `ServiceName` `ClusterName`, `TaskDefinitionFamily`  |  Amazon ECS 任务中容器重新启动的次数。 仅会对启用了重启策略的容器收集此指标。 也适用于托管进程守护程序。 单位：个  | 
|  `ServiceCount`  |  `ClusterName`  |  集群中的服务数。 单位：个  | 
|  `StorageReadBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  从您使用之维度所指定资源中实例上的存储读取的字节数。这不包括存储设备的读取字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `StorageWriteBytes`  |  `TaskDefinitionFamily`, `ClusterName` `ServiceName`, `ClusterName` `ClusterName`  |  写入到您使用的维度所指定的资源中的存储的字节数。该指标是从 Docker 运行时系统获取的。 也适用于托管进程守护程序。 单位：字节  | 
|  `TaskCount`  |  `ClusterName`  |  正在集群中运行的任务数。 单位：个  | 
|  `TaskSetCount`  |  `ServiceName`, `ClusterName`  |  服务中设置的任务数。 单位：个  | 

**注意**  
`EphemeralStorageReserved` 和 `EphemeralStorageUtilized` 指标仅适用于在 Fargate Linux 平台 1.4.0 或更高版本上运行的任务。  
Fargate 可保留磁盘空间。该磁盘空间仅由 Fargate 使用。您无需为此付费。它没有显示在这些指标中。但是，您可以在 `df` 等其他工具中看到这种额外的存储空间。

完成[部署 CloudWatch 代理以收集 Amazon ECS 上的 EC2 实例级别指标](deploy-container-insights-ECS-instancelevel.md)中的步骤后，以下指标将可用


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `instance_cpu_limit`  |  `ClusterName`  |  可分配给集群中的单个 EC2 实例的 CPU 单元的最大数目。 单位：无  | 
|  `instance_cpu_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的 CPU 的百分比。 单位：百分比  | 
|  `instance_cpu_usage_total`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的数目。 单位：无  | 
|  `instance_cpu_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的 CPU 单元的总百分比。 单位：百分比  | 
|  `instance_filesystem_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的文件系统容量的总百分比。 单位：百分比  | 
|  `instance_memory_limit`  |  `ClusterName`  |  可分配给此集群中单个 EC2 实例的最大内存量（以字节为单位）。 单位：字节  | 
|  `instance_memory_reserved_capacity`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上当前预留的内存的百分比。 单位：百分比  | 
|  `instance_memory_utilization`  |  `ClusterName` `InstanceId`, `ContainerInstanceId`, `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存的总百分比。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：百分比  | 
|  `instance_memory_working_set`  |  `ClusterName`  |  集群中单个 EC2 实例上正在使用的内存量（以字节为单位）。  如果您的应用程序中使用 Java ZGC 垃圾收集器，则该指标可能不准确。  单位：字节  | 
|  `instance_network_total_bytes`  |  `ClusterName`  |  集群中单个 EC2 实例通过网络传输和接收的每秒总字节数。 单位：字节/秒  | 
|  `instance_number_of_running_tasks`  |  `ClusterName`  |  集群中单个 EC2 实例上正在运行的任务的数目。 单位：个  | 

# 具有增强型可观测性的 Amazon EKS 和 Kubernetes Container Insights
<a name="Container-Insights-metrics-enhanced-EKS"></a>

下表列出了具有增强型可观测性的 Container Insights 为 Amazon EKS 和 Kubernetes 收集的指标和维度。这些指标位于 `ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果在控制台中未看到任何具有增强型可观测性的 Container Insights 指标，请确保已完成具有增强型可观测性的 Container Insights 的设置。在完全设置具有增强型可观测性的 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。

如果您使用 Amazon EKS 附加组件 1.5.0 版或更高版本或者 CloudWatch 代理 1.300035.0 版，则将为 Linux 和 Windows 节点收集下表中列出的大多数指标。请参阅该表的**指标名称**列，了解哪些指标并非为 Windows 收集。

Container Insights 的早期版本在集群和服务级别提供聚合指标，这些指标作为自定义指标收费。借助针对 Amazon EKS 增强了可观测性的 Container Insights，Container Insights 指标按每次观测收费，而不是按存储的指标或摄取的日志收费。有关 CloudWatch 定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**注意**  
在 Windows 上，不会为主机进程容器收集 `pod_network_rx_bytes` 和 `pod_network_tx_bytes` 等网络指标。  
在 RedHat OpenShift on AWS (ROSA) 集群中，不会收集 `node_diskio_io_serviced_total`、`node_diskio_io_service_bytes_total` 等磁盘指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `cluster_failed_node_count`  |  `ClusterName`  |  集群中失败的工作线程节点的数目。如果节点遭受任何*节点条件*的影响，则该节点被视为失败。有关更多信息，请参阅 Kubernetes 文档中的[条件](https://kubernetes.io/docs/concepts/architecture/nodes/#condition)。  | 
|  `cluster_node_count`  |  `ClusterName`  |  集群中工作线程节点的总数。  | 
|  `namespace_number_of_running_pods`  |  `Namespace` `ClusterName` `ClusterName`  |  您使用的维度所指定的资源中每个命名空间运行的 pod 的数目。  | 
|  `node_cpu_limit`  |  `ClusterName`  `ClusterName`, `InstanceId`, `NodeName`   |  可以分配给此集群中单个节点的 CPU 单元的最大数目。  | 
|  `node_cpu_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  为节点组件保留的 CPU 单元的百分比，例如 kubelet、kube-proxy 和 Docker。 公式：`node_cpu_request / node_cpu_limit`  `node_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_cpu_usage_total`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  集群中节点上正在使用的 CPU 单元的数目。  | 
|  `node_cpu_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的 CPU 单元的总百分比。 公式：`node_cpu_usage_total / node_cpu_limit`  | 
|  `node_filesystem_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的文件系统容量的总百分比。 公式：`node_filesystem_usage / node_filesystem_capacity`  `node_filesystem_usage` 和 `node_filesystem_capacity` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_limit`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  可以分配给此集群中单个节点的最大内存量（以字节为单位）。  | 
|  `node_filesystem_inodes`  其在 Windows 上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上 inode（已使用和未使用）的总数。  | 
|  `node_filesystem_inodes_free` 其在 Windows 上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上未使用 inode 的总数。  | 
|  `node_gpu_limit` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上可用 GPU 的总数。  | 
|  `node_gpu_usage_total` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上正在运行的容器组 (pod) 正在使用的 GPU 数量。  | 
|  `node_gpu_reserved_capacity` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  | 
|  `node_memory_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上当前正在使用的内存百分比。 公式：`node_memory_request / node_memory_limit`  `node_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  一个或多个节点当前正在使用的内存百分比。它是节点内存使用量除以节点内存限制的百分比。 公式：`node_memory_working_set / node_memory_limit`。  | 
|  `node_memory_working_set`  |  `ClusterName`  `ClusterName`, `InstanceId`, `NodeName`   |  集群中节点的工作集中正在使用的内存量（以字节为单位）。  | 
|  `node_network_total_bytes`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点通过网络传输和接收的每秒总字节数。 公式：`node_network_rx_bytes + node_network_tx_bytes`  `node_network_rx_bytes` 和 `node_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_number_of_running_containers`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点的正在运行的容器数。  | 
|  `node_number_of_running_pods`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点上运行的 pod 的数量。  | 
|  `node_status_allocatable_pods`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  根据节点的可分配资源可以分配给节点的容器组（pod）数量，这定义为考虑系统进程守护程序预留和硬驱逐阈值后的节点容量余数。  | 
|  `node_status_capacity_pods`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  根据节点容量可以分配给节点的容器组（pod）数量。  | 
|  `node_status_condition_ready`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示 Amazon EC2 节点的节点状态条件 `Ready` 是否为 true。  | 
|  `node_status_condition_memory_pressure`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示节点状态条件是 `MemoryPressure` 是否为 true。  | 
|  `node_status_condition_pid_pressure`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示节点状态条件是 `PIDPressure` 是否为 true。  | 
|  `node_status_condition_disk_pressure`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示节点状态条件是 `OutOfDisk` 是否为 true。  | 
|  `node_status_condition_unknown`   |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  表示是否有任何节点状态条件为“未知”。  | 
|  `node_interface_network_rx_dropped`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上的网络接口接收并随后丢弃的数据包数量。  | 
|  `node_interface_network_tx_dropped`  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  本应传输但被节点上的网络接口丢弃的数据包数量。  | 
|  `node_diskio_io_service_bytes_total`  其在 Windows 或 ROSA 集群上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上所有 I/O 操作传输的总字节数。  | 
|  `node_diskio_io_serviced_total` 其在 Windows 或 ROSA 集群上不可用。  |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`   |  节点上 I/O 操作的总数。  | 
|  `pod_cpu_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  `ClusterName`, `Namespace`, `Service`   |  集群中每个 pod 预留的 CPU 容量。 公式：`pod_cpu_request / node_cpu_limit`  `pod_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  pod 所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / node_cpu_limit`  | 
|  `pod_cpu_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  相对于容器组（pod）限制的容器组（pod）所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / pod_cpu_limit`  | 
|  `pod_memory_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  `ClusterName`, `Namespace`, `Service`   |  为 pod 预留的内存的百分比。 公式：`pod_memory_request / node_memory_limit`  `pod_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  一个或多个 pod 当前正在使用的内存百分比。 公式：`pod_memory_working_set / node_memory_limit`  | 
|  `pod_memory_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  相对于容器组（pod）限制的容器组（pod）所使用的内存百分比。如果容器组（pod）中的任何容器没有定义内存限制，则不会显示该指标。 公式：`pod_memory_working_set / pod_memory_limit`  | 
|  `pod_network_rx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  pod 通过网络每秒接收的字节数。 公式：`sum(pod_interface_network_rx_bytes)`  `pod_interface_network_rx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_network_tx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace,` `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`   |  pod 通过网络每秒传输的字节数。 公式：`sum(pod_interface_network_tx_bytes)`  `pod_interface_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_request`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  容器组（pod）的 CPU 请求。 公式：`sum(container_cpu_request)`  `pod_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_request`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  容器组（pod）的内存请求。 公式：`sum(container_memory_request)`  `pod_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_limit`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  为容器组（pod）中的容器定义的 CPU 限制。如果容器组（pod）中的任何容器没有定义 CPU 限制，则不会显示此指标。 公式：`sum(container_cpu_limit)`  `pod_cpu_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_limit`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  为容器组（pod）中的容器定义的内存限制。如果容器组（pod）中的任何容器没有定义内存限制，则不会显示该指标。 公式：`sum(container_memory_limit)`  `pod_cpu_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_status_failed`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都已终止，并且至少有一个容器以非零状态终止或已被系统终止。  | 
|  `pod_status_ready`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都已准备就绪，且已达到 `ContainerReady` 的条件。  | 
|  `pod_status_running`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都在运行。  | 
|  `pod_status_scheduled`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）已被调度到某个节点。  | 
|  `pod_status_unknown`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示无法获取容器组（pod）的状态。  | 
|  `pod_status_pending`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示集群已接受容器组（pod），但其中一个或多个容器尚未准备就绪。  | 
|  `pod_status_succeeded`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  表示容器组（pod）中的所有容器都已成功终止并且不会重启。  | 
|  `pod_number_of_containers`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）规范中定义的容器数量。  | 
|  `pod_number_of_running_containers`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中当前处于 `Running` 状态的容器数量。  | 
|  `pod_container_status_terminated`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中处于 `Terminated` 状态的容器数量。  | 
|  `pod_container_status_running`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中处于 `Running` 状态的容器数量。  | 
|  `pod_container_status_waiting`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中处于 `Waiting` 状态的容器数量。  | 
|  `pod_container_status_waiting_reason_crash_loop_back_off`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中因 `CrashLoopBackOff` 错误而处于待处理状态的容器数量，该错误会导致容器反复启动失败。  | 
|  `pod_container_status_waiting_reason_create_container_config_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中因 `CreateContainerConfigError` 而处于待处理状态的容器数量。这是因为创建容器配置时出错。  | 
|  `pod_container_status_waiting_reason_create_container_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中由于创建容器时出错而因 `CreateContainerError` 处于待处理状态的容器数量。  | 
|  `pod_container_status_waiting_reason_image_pull_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中因 `ErrImagePull`、`ImagePullBackOff` 或 `InvalidImageName` 而处于待处理状态的容器数量。这些情况是由于拉取容器映像时出错造成的。  | 
|  `pod_container_status_waiting_reason_start_error`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  报告容器组（pod）中由于启动容器时出错而因 `StartError` 处于待处理状态的容器数量。  | 
|  `pod_container_status_terminated_reason_oom_killed`   |  `ContainerName`, `FullPodName`, `PodName`, `Namespace`, `ClusterName` `ContainerName`, `PodName`, `Namespace`, `ClusterName` `ClusterName`  |  表示容器组 (pod) 因超过内存限制而被终止。仅当发生此问题时才会显示此指标。  | 
|  `pod_interface_network_rx_dropped`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  容器组（pod）的网络接口接收并随后丢弃的数据包数量。  | 
|  `pod_interface_network_tx_dropped`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  |  本应传输但为容器组（pod）丢弃的数据包数量。  | 
| `pod_memory_working_set` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  | 容器组 (pod) 当前正在使用的内存（以字节为单位）。 | 
| `pod_cpu_usage_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName`  | 容器组 (pod) 使用的 CPU 单元的数量。 | 
|  `container_cpu_utilization`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  容器所使用的 CPU 单元的百分比。 公式：`container_cpu_usage_total / node_cpu_limit`  `container_cpu_utilization` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_cpu_utilization_over_container_limit`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  相对于容器限制，容器所使用的 CPU 单元的百分比。如果容器没有定义 CPU 限制，则不会显示此指标。 公式：`container_cpu_usage_total / container_cpu_limit`  `container_cpu_utilization_over_container_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_memory_utilization`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  容器所使用的内存单元的百分比。 公式：`container_memory_working_set / node_memory_limit`  `container_memory_utilization` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_memory_utilization_over_container_limit`    |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  相对于容器限制，容器所使用的内存单元的百分比。如果容器没有定义内存限制，则不会显示此指标。 公式：`container_memory_working_set / container_memory_limit`  `container_memory_utilization_over_container_limit` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `container_memory_failures_total`  其在 Windows 上不可用。  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`, `ContainerName` `PodName`, `Namespace`, `ClusterName`, `ContainerName`, `FullPodName`  |  容器遇到的内存分配失败的次数。  | 
|  `pod_number_of_container_restarts`  |  PodName、`Namespace`、`ClusterName`  |  一个 pod 中容器重新启动的总次数。  | 
|  `service_number_of_running_pods`  |  Service、`Namespace`、`ClusterName` `ClusterName`  |  运行集群中的服务的 pod 的数量。  | 
|  `replicas_desired`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  工作负载规范中定义的工作负载所需的容器组（pod）数量。  | 
|  `replicas_ready`   |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  已达到就绪状态的工作负载的容器组（pod）数量。  | 
|  `status_replicas_available`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  工作负载可用的容器组（pod）数量。当容器组（pod）已就绪工作负载规范中定义的 `minReadySeconds` 时，容器组（pod）才可用。  | 
|  `status_replicas_unavailable`  |  `ClusterName` `PodName`, `Namespace`, `ClusterName`  |  工作负载不可用的容器组（pod）数量。当容器组（pod）已就绪工作负载规范中定义的 `minReadySeconds` 时，容器组（pod）才可用。如果容器组（pod）不符合此标准，则它们不可用。  | 
|  `apiserver_storage_objects`  |  `ClusterName` `ClusterName`, `resource`  |  上次检查时存储在 etcd 中的对象数量。  | 
|  `apiserver_storage_db_total_size_in_bytes`  |  `ClusterName` `ClusterName`, `endpoint`  |  物理分配的存储数据库文件的总大小（以字节为单位）。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。 单位：字节 有意义的统计数据：总和、平均值、最小值、最大值  | 
|  `apiserver_request_total`  |  `ClusterName` `ClusterName`, `code`, `verb`  |  向 Kubernetes API 服务器发出的 API 请求总数。  | 
|  `apiserver_request_duration_seconds`  |  `ClusterName` `ClusterName`, `verb`  |  向 Kubernetes API 服务器发出的 API 请求的响应延迟。  | 
|  `apiserver_admission_controller_admission_duration_seconds`  |  `ClusterName` `ClusterName`, `operation`  |  准入控制器延迟（以秒为单位）。准入控制器是拦截向 Kubernetes API 服务器发出的请求的代码。  | 
|  `rest_client_request_duration_seconds`   |  `ClusterName` `ClusterName`, `operation`  |  客户端在调用 Kubernetes API 服务器时遇到的响应延迟。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `rest_client_requests_total`   |  `ClusterName` `ClusterName`, `code`, `method`  |  客户端向 Kubernetes API 服务器发出的 API 请求总数。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `etcd_request_duration_seconds`   |  `ClusterName` `ClusterName`, `operation`  |  对 Etcd 的 API 调用的响应延迟。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_storage_size_bytes`   |  `ClusterName` `ClusterName`, `endpoint`  |  物理分配的存储数据库文件的大小（以字节为单位）。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_longrunning_requests`  |  `ClusterName` `ClusterName`, `resource`  |  向 Kubernetes API 服务器发出的长时间运行的活跃请求数。  | 
|  `apiserver_current_inflight_requests`  |  `ClusterName` `ClusterName`, `request_kind`  |  Kubernetes API 服务器正在处理的请求数。  | 
|  `apiserver_admission_webhook_admission_duration_seconds`  |  `ClusterName` `ClusterName`, `name`  |  准入 Webhook 延迟（以秒为单位）。准入 Webhook 是 HTTP 回调，用于接收准入请求并对其进行一些处理。  | 
|  `apiserver_admission_step_admission_duration_seconds`   |  `ClusterName` `ClusterName`, `operation`  |  准入子步骤延迟（以秒为单位）。  | 
|  `apiserver_requested_deprecated_apis`   |  `ClusterName` `ClusterName`, `group`  |  向 Kubernetes API 服务器上已弃用的 API 发出的请求数。  | 
|  `apiserver_request_total_5xx`  |  `ClusterName` `ClusterName`, `code`, `verb`  |  向 Kubernetes API 服务器发出的请求数，这些请求以 5XX HTTP 响应代码为响应。  | 
|  `apiserver_storage_list_duration_seconds`   |  `ClusterName` `ClusterName`, `resource`  |  列出 Etc 中的对象的响应延迟。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_flowcontrol_request_concurrency_limit`   |  `ClusterName` `ClusterName`, `priority_level`  |  API 优先级和公平性子系统中当前正在执行的请求使用的线程数。  | 
|  `apiserver_flowcontrol_rejected_requests_total`   |  `ClusterName` `ClusterName`, `reason`  |  API 优先级和公平性子系统拒绝的请求数。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 
|  `apiserver_current_inqueue_requests`   |  `ClusterName` `ClusterName`, `request_kind`  |  Kubernetes API 服务器排队的请求数。此指标是实验性的，在将来的 Kubernetes 版本中可能会发生变化。  | 

## NVIDIA GPU 指标
<a name="Container-Insights-metrics-EKS-GPU"></a>

从 CloudWatch 代理版本 `1.300034.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 默认从 EKS 工作负载收集 NVIDIA GPU 指标。必须使用 CloudWatch Observability EKS 附加组件版本 `v1.3.0-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。本节的表中列出了这些会被收集的 NVIDIA GPU 指标。

要让 Container Insights 收集 NVIDIA GPU 指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 Amazon CloudWatch Observability EKS 附加组件版本 `v1.3.0-eksbuild.1` 或更高版本结合使用。
+ 集群中必须安装[适用于 Kubernetes 的 NVIDIA 设备插件](https://github.com/NVIDIA/k8s-device-plugin)。
+ 集群的节点上必须安装 [NVIDIA 容器工具包](https://github.com/NVIDIA/nvidia-container-toolkit)。例如，使用必要的组件构建 Amazon EKS 优化版加速型 AMI。

您可以将起始 CloudWatch 代理配置文件中的 `accelerated_compute_metrics` 选项设置为 `false`，从而选择不收集 NVIDIA GPU 指标。有关更多信息和选择不收集配置的示例，请参阅 [（可选）其他配置](install-CloudWatch-Observability-EKS-addon.md#install-CloudWatch-Observability-EKS-addon-configuration)。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `container_gpu_memory_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 上的帧缓冲区总大小（以字节为单位）。  | 
|  `container_gpu_memory_used` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 上使用的帧缓冲区字节数。  | 
|  `container_gpu_memory_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 已使用的帧缓冲区百分比。  | 
|  `container_gpu_power_draw` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 的功耗（以瓦特为单位）。  | 
|  `container_gpu_temperature` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 的温度（以摄氏度为单位）。  | 
|  `container_gpu_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 的利用率百分比。  | 
|  `container_gpu_tensor_core_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器的 GPU 张量核心利用率百分比。  | 
|  `node_gpu_memory_total` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 上的帧缓冲区总大小（以字节为单位）。  | 
|  `node_gpu_memory_used` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 上使用的帧缓冲区字节数。  | 
|  `node_gpu_memory_utilization` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 上使用的帧缓冲区百分比。  | 
|  `node_gpu_power_draw` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 的功耗（以瓦特为单位）。  | 
|  `node_gpu_temperature` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 的温度（以摄氏度为单位）。  | 
|  `node_gpu_utilization` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 的利用率百分比。  | 
|  `node_gpu_tensor_core_utilization` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `GpuDevice`  |  分配给节点的 GPU 张量核心利用率百分比。  | 
|  `pod_gpu_memory_total` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 上的帧缓冲区总大小（以字节为单位）。  | 
|  `pod_gpu_memory_used` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 上使用的帧缓冲区字节数。  | 
|  `pod_gpu_memory_utilization` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 上使用的帧缓冲区百分比。  | 
|  `pod_gpu_power_draw` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给 Pod 的 GPU 的功耗（以瓦特为单位）。  | 
|  `pod_gpu_temperature` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`. `GpuDevice`  |  分配给容器组 (pod) 的 GPU 的温度（以摄氏度为单位）。  | 
|  `pod_gpu_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给 Pod 的 GPU 的利用率百分比。  | 
|  `pod_gpu_tensor_core_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `GpuDevice`  |  分配给容器组（pod）的 GPU 张量核心利用率百分比。  | 

### GPU 精细化监控
<a name="Container-Insights-detailed-GPU-monitoring"></a>

从 CloudWatch 代理 `1.300062.0` 版本开始，适用于 Amazon EKS 的可观测性增强型 Container Insights 支持亚分钟级收集间隔的 GPU 精细化监控。该功能填补了短时机器学习推理工作负载的监控空白；此类工作负载在标准收集间隔下可能被完全遗漏。必须使用 CloudWatch Observability EKS 附加组件版本 `v4.7.0-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。

默认情况下，GPU 指标的收集与上报间隔为 60 秒。启用精细化监控后，CloudWatch 代理将以亚分钟级间隔（最小 1 秒）收集 GPU 指标，但指标仍以 1 分钟为间隔上报至 CloudWatch。不过，您可对每个 1 分钟周期内的亚分钟级数据点进行统计聚合查询（如最小值、最大值及 P90 等百分位数），以此获取精准的 GPU 利用率数据，实现更优的资源优化。

#### 配置
<a name="Container-Insights-detailed-GPU-monitoring-configuration"></a>

如需启用 GPU 精细化监控，需更新 CloudWatch 代理配置，在 `kubernetes` 配置段中添加 `accelerated_compute_gpu_metrics_collection_interval` 参数，配置示例如下。

```
{  
    "logs": {  
        "metrics_collected": {  
            "kubernetes": {  
                "cluster_name": "MyCluster",  
                "enhanced_container_insights": true,  
                "accelerated_compute_metrics": true,  
                "accelerated_compute_gpu_metrics_collection_interval": 1  
            }  
        }  
    }  
}
```

`accelerated_compute_gpu_metrics_collection_interval` 参数的取值单位为秒，最小值为 1 秒。将此参数设位 `1` 时，即可启用 1 秒的收集间隔。若未指定此参数，则将采用默认的 60 秒采集间隔。

有关完整配置说明，请参阅[设置 CloudWatch 代理以收集集群指标](Container-Insights-setup-metrics.md)。

## AWS Trainium 和 AWS Inferentia 的 AWS Neuron 指标
<a name="Container-Insights-metrics-EKS-Neuron"></a>

从 CloudWatch 代理版本 `1.300036.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 默认从 AWS Trainium 和 AWS Inferentia 加速器收集加速计算指标。必须使用 CloudWatch Observability EKS 附加组件版本 `v1.5.0-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。有关 AWS Trainium 的更多信息，请参阅 [AWS Trainium](https://aws.amazon.com/machine-learning/trainium/)。有关 AWS Inferentia 的更多信息，请参阅 [AWS Inferentia](https://aws.amazon.com/machine-learning/inferentia/)。

要让 Container Insights 收集 AWS Neuron 指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 Amazon CloudWatch Observability EKS 附加组件版本 `v1.5.0-eksbuild.1` 或更高版本结合使用。
+ [Neuron 驱动程序](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/setup/neuron-setup/pytorch/neuronx/ubuntu/torch-neuronx-ubuntu22.html#setup-torch-neuronx-ubuntu22)必须安装在集群的节点上。
+ [Neuron 设备插件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/containers/kubernetes-getting-started.html)必须安装在集群上。例如，使用必要的组件构建 Amazon EKS 优化版加速型 AMI。

本节的表中列出了将收集的指标。这些指标是为 AWS Trainium、AWS Inferentia 和 AWS Inferentia2 收集的。

CloudWatch 代理从 [Neuron Monitor](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/tools/neuron-sys-tools/neuron-monitor-user-guide.html) 收集这些指标，并进行必要的 Kubernetes 资源关联，以在容器组（pod）和容器级别提供指标


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `container_neuroncore_utilization` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 在捕获期内的 NeuronCore 利用率。 单位：百分比  | 
|  `container_neuroncore_memory_usage_constants` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 在训练期间用于常量的设备内存量（或推理期间的权重）。 单位：字节  | 
|  `container_neuroncore_memory_usage_model_code` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于模型可执行代码的设备内存量。 单位：字节  | 
|  `container_neuroncore_memory_usage_model_shared_scratchpad` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于模型共享暂存器的设备内存量。此内存区域保留用于模型。 单位：字节  | 
|  `container_neuroncore_memory_usage_runtime_memory` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于 Neuron 运行时的设备内存量。 单位：字节  | 
|  `container_neuroncore_memory_usage_tensors` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 用于张量的设备内存量。 单位：字节  | 
|  `container_neuroncore_memory_usage_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`, `NeuronCore`  |  分配给容器的 NeuronCore 使用的内存总量。 单位：字节  | 
|  `container_neurondevice_hw_ecc_events_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NeuronDevice`  |  节点上 Neuron 设备的片上 SRAM 和设备内存的已校正和未校正 ECC 事件数。 单位：个  | 
|  `pod_neuroncore_utilization` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 在捕获期内的 NeuronCore 利用率。 单位：百分比  | 
|  `pod_neuroncore_memory_usage_constants` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 在训练期间用于常量的设备内存量（或推理期间的权重）。 单位：字节  | 
|  `pod_neuroncore_memory_usage_model_code` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于模型可执行代码的设备内存量。 单位：字节  | 
|  `pod_neuroncore_memory_usage_model_shared_scratchpad` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于模型共享暂存器的设备内存量。此内存区域保留用于模型。 单位：字节  | 
|  `pod_neuroncore_memory_usage_runtime_memory` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于 Neuron 运行时的设备内存量。 单位：字节  | 
|  `pod_neuroncore_memory_usage_tensors` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 用于张量的设备内存量。 单位：字节  | 
|  `pod_neuroncore_memory_usage_total` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`, `NeuronCore`  |  分配给容器组（pod）的 NeuronCore 使用的内存总量。 单位：字节  | 
|  `pod_neurondevice_hw_ecc_events_total` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NeuronDevice`  |  分配给容器组（pod）的 Neuron 设备的片上 SRAM 和设备内存的已校正和未校正 ECC 事件数。 单位：字节  | 
|  `node_neuroncore_utilization` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 在捕获期内的 NeuronCore 利用率。 单位：百分比  | 
|  `node_neuroncore_memory_usage_constants` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 在训练期间用于常量的设备内存量（或推理期间的权重）。 单位：字节  | 
|  `node_neuroncore_memory_usage_model_code` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于模型可执行代码的设备内存量。 单位：字节  | 
|  `node_neuroncore_memory_usage_model_shared_scratchpad` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于模型共享暂存器的设备内存量。这保留用于模型的内存区域。 单位：字节  | 
|  `node_neuroncore_memory_usage_runtime_memory` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于 Neuron 运行时的设备内存量。 单位：字节  | 
|  `node_neuroncore_memory_usage_tensors` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 用于张量的设备内存量。 单位：字节  | 
|  `node_neuroncore_memory_usage_total` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceType`, `InstanceId`, `NodeName`, `NeuronDevice`, `NeuronCore`  |  分配给节点的 NeuronCore 使用的内存总量。 单位：字节  | 
|  `node_neuron_execution_errors_total` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName`  |  节点上执行错误的总数。这是由 CloudWatch 代理通过汇总以下类型的错误来计算的：`generic`、`numerical`、`transient`、`model`、`runtime` 和 `hardware` 单位：个  | 
|  `node_neurondevice_runtime_memory_used_bytes` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName`  |  节点上 Neuron 设备内存使用总量（以字节为单位）。 单位：字节  | 
| `node_neuron_execution_latency` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName`  |  Neuron 运行时测量的节点上执行的延迟（以秒为单位）。 单位：秒  | 
| `node_neurondevice_hw_ecc_events_total` |  `ClusterName` `ClusterName`, `UltraServer` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `NodeName`, `NeuronDevice`  |  节点上 Neuron 设备的片上 SRAM 和设备内存的已校正和未校正 ECC 事件数。 单位：个  | 

## AWS Elastic Fabric Adapter（EFA）指标
<a name="Container-Insights-metrics-EFA"></a>

从 CloudWatch 代理版本 `1.300037.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 从 Linux 实例上的 Amazon EKS 集群收集 AWS Elastic Fabric Adapter（EFA）指标。必须使用 CloudWatch Observability EKS 附加组件版本 `v1.5.2-eksbuild.1` 或更高版本安装 CloudWatch 代理。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。有关 AWS Elastic Fabric Adapter（EFA）的更多信息，请参阅 [Elastic Fabric Adapter](https://aws.amazon.com/hpc/efa/)。

要让 Container Insights 收集 AWS Elastic Fabric Adapter 指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 Amazon CloudWatch Observability EKS 附加组件版本 `v1.5.2-eksbuild.1` 或更高版本结合使用。
+ EFA 设备插件必须安装在集群上。有关更多信息，请参阅 GitHub 上的 [aws-efa-k8s-device-plugin](https://github.com/aws/eks-charts/tree/master/stable/aws-efa-k8s-device-plugin)。

下表中列出了收集的指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `container_efa_rx_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备每秒接收的字节数。 单位：字节/秒  | 
|  `container_efa_tx_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备每秒传输的字节数。 单位：字节/秒  | 
|  `container_efa_rx_dropped` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备接收然后丢弃的数据包数量。 单位：计数/秒  | 
|  `container_efa_rdma_read_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备使用远程直接内存访问读取操作每秒接收的字节数。 单位：字节/秒  | 
|  `container_efa_rdma_write_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备使用远程直接内存访问读取操作每秒传输的字节数。 单位：字节/秒  | 
|  `container_efa_rdma_write_recv_bytes` |  `ClusterName` `ClusterName`, `Namespace`, `PodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `ContainerName`, `NetworkInterfaceId`   |  分配给容器的 EFA 设备在远程直接内存访问写入操作期间每秒接收的字节数。 单位：字节/秒  | 
|  `pod_efa_rx_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备每秒接收的字节数。 单位：字节/秒  | 
|  `pod_efa_tx_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备每秒传输的字节数。 单位：字节/秒  | 
|  `pod_efa_rx_dropped` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备接收然后丢弃的数据包数量。 单位：计数/秒  | 
|  `pod_efa_rdma_read_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备使用远程直接内存访问读取操作每秒接收的字节数。 单位：字节/秒  | 
|  `pod_efa_rdma_write_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备使用远程直接内存访问读取操作每秒传输的字节数。 单位：字节/秒  | 
|  `pod_efa_rdma_write_recv_bytes` |  `ClusterName` `ClusterName`, `Namespace` `ClusterName`, `Namespace`, `Service` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName` `ClusterName`, `Namespace`, `PodName`, `FullPodName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备在远程直接内存访问写入操作期间每秒接收的字节数。 单位：字节/秒  | 
|  `node_efa_rx_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备每秒接收的字节数。 单位：字节/秒  | 
|  `node_efa_tx_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备每秒传输的字节数。 单位：字节/秒  | 
|  `node_efa_rx_dropped` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备接收然后丢弃的数据包数量。 单位：计数/秒  | 
|  `node_efa_rdma_read_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备使用远程直接内存访问读取操作每秒接收的字节数。 单位：字节/秒  | 
|  `node_efa_rdma_write_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给容器组（pod）的 EFA 设备使用远程直接内存访问读取操作每秒传输的字节数。 单位：字节/秒  | 
|  `node_efa_rdma_write_recv_bytes` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName` `ClusterName`, `InstanceId`, `InstanceType`, `NodeName`, `NetworkInterfaceId`  |  分配给节点的 EFA 设备在远程直接内存访问写入操作期间每秒接收的字节数。 单位：字节/秒  | 

## Amazon SageMaker AI HyperPod 指标
<a name="Container-Insights-metrics-Sagemaker-HyperPod"></a>

从 CloudWatch Observability EKS 附加组件的 `v2.0.1-eksbuild.1` 版本开始，具有 Amazon EKS 增强可观测性的 Container Insights 会自动从 Amazon EKS 集群收集 Amazon SageMaker AI HyperPod 指标。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。有关 Amazon SageMaker AI HyperPod 的更多信息，请参阅 [Amazon SageMaker AI HyperPod](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-hyperpod-eks.html)。

下表中列出了收集的指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `hyperpod_node_health_status_unschedulable` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 `Unschedulable` HyperPod 标记为 Amazon SageMaker AI。这意味着该节点正在运行深度运行状况检查，无法用于运行的工作负载。 单位：个  | 
|  `hyperpod_node_health_status_schedulable` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 `Schedulable` HyperPod 标记为 Amazon SageMaker AI。这意味着该节点已通过基本运行状况检查或深度运行状况检查，可用于运行的工作负载。 单位：个  | 
|  `hyperpod_node_health_status_unschedulable_pending_replacement` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 HyperPod 标记为 `UnschedulablePendingReplacement`。这意味着该节点未通过深度运行状况检查或运行状况监测代理检查，需要替换。 如果启用了自动节点恢复，该节点将自动被 Amazon SageMaker AI HyperPod 替换。 单位：个  | 
|  `hyperpod_node_health_status_unschedulable_pending_reboot` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  表示节点是否被 `UnschedulablePendingReboot` HyperPod 标记为 Amazon SageMaker AI。这意味着该节点正在运行深度运行状况检查，需要重启。 如果启用了自动节点恢复，Amazon SageMaker AI HyperPod 将自动重启该节点。 单位：个  | 

## Amazon EBS NVMe 驱动指标
<a name="Container-Insights-metrics-EBS"></a>

从 CloudWatch 代理版本 ` 1.300056.0` 开始，针对 Amazon EKS 增强了可观测性的 Container Insights 从 Linux 实例上的 Amazon EKS 集群自动收集 Amazon EBS NVMe 驱动指标。必须使用 CloudWatch Observability Amazon EKS 附加组件版本 `4.1.0` 或更高版本安装 CloudWatch 代理。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。如需进一步了解 Amazon EBS，请参阅 [Amazon EBS 详细性能统计数据](https://docs.aws.amazon.com/ebs/latest/userguide/nvme-detailed-performance-stats.html)。

要让 Container Insights 收集 Amazon EBS NVMe 驱动指标，必须满足以下先决条件：
+ 必须将针对 Amazon EKS 增强了可观测性的 Container Insights 与 CloudWatch Observability Amazon EKS 附加组件版本 `4.1.0` 或更高版本结合使用。
+ 必须在已启用指标的集群上安装 EBS CSI 驱动程序 `1.42.0` 插件或 Helm 图表。
  + 若要在使用 Amazon EBS CSI 驱动程序插件时启用指标功能，请在创建或更新该插件时配置以下选项。`--configuration-values '{ "node": { "enableMetrics": true } }'`
  + 若要在使用 Helm 图表时启用指标功能，请在创建或更新该插件时配置以下选项。`--set node.enableMetrics=true`

下表中列出了收集的指标。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `node_diskio_ebs_total_read_ops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 已完成的读取操作总数。 | 
|  `node_diskio_ebs_total_write_ops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 已完成的写入操作总数。 | 
|  `node_diskio_ebs_total_read_bytes` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 传输的读取字节总数。 | 
|  `node_diskio_ebs_total_write_bytes` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 传输的写入字节总数。 | 
|  `node_diskio_ebs_total_read_time` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 所有已完成读取操作的总耗时（单位：微秒）。 | 
|  `node_diskio_ebs_total_write_time` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 所有已完成写入操作的总耗时（单位：微秒）。 | 
|  `node_diskio_ebs_volume_performance_exceeded_iops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | IOPS 需求超出存储卷预调配 IOPS 性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_volume_performance_exceeded_tp` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 吞吐量需求超出存储卷预配置吞吐量性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_ec2_instance_performance_exceeded_iops` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | EBS 卷超出所附加的 Amazon EC2 实例最大 IOPS 性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_ec2_instance_performance_exceeded_tp` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | EBS 卷超出所附加的 Amazon EC2 实例最大吞吐量性能的总时长（单位：微秒）。 | 
|  `node_diskio_ebs_volume_queue_length` |  `ClusterName` `ClusterName`, `NodeName`, `InstanceId` `ClusterName`, `NodeName`, `InstanceId` `VolumeId`  | 待完成的读取与写入操作的数量。 | 

# Amazon EKS 和 Kubernetes Container Insights 指标
<a name="Container-Insights-metrics-EKS"></a>

下表列出了 Container Insights 为 Amazon EKS 和 Kubernetes 收集的指标和维度。这些指标位于 `ContainerInsights` 命名空间中。有关更多信息，请参阅 [指标](cloudwatch_concepts.md#Metric)。

如果您在控制台中未看到任何 Container Insights 指标，请确保已完成 Container Insights 的设置。在完全设置 Container Insights 之前，指标不会显示。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `cluster_failed_node_count`  |  `ClusterName`  |  集群中失败的工作线程节点的数目。如果节点遭受任何*节点条件*的影响，则该节点被视为失败。有关更多信息，请参阅 Kubernetes 文档中的[条件](https://kubernetes.io/docs/concepts/architecture/nodes/#condition)。  | 
|  `cluster_node_count`  |  `ClusterName`  |  集群中工作线程节点的总数。  | 
|  `namespace_number_of_running_pods`  |  `Namespace` `ClusterName` `ClusterName`  |  您使用的维度所指定的资源中每个命名空间运行的 pod 的数目。  | 
|  `node_cpu_limit`  |  `ClusterName`   |  可以分配给此集群中单个节点的 CPU 单元的最大数目。  | 
|  `node_cpu_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  为节点组件保留的 CPU 单元的百分比，例如 kubelet、kube-proxy 和 Docker。 公式：`node_cpu_request / node_cpu_limit`  `node_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_cpu_usage_total`  |  `ClusterName`  |  集群中节点上正在使用的 CPU 单元的数目。  | 
|  `node_cpu_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的 CPU 单元的总百分比。 公式：`node_cpu_usage_total / node_cpu_limit`  | 
|  `node_gpu_limit` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上可用 GPU 的总数。  | 
|  `node_gpu_usage_total` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上正在运行的容器组 (pod) 正在使用的 GPU 数量。  | 
|  `node_gpu_reserved_capacity` |  `ClusterName` `ClusterName`, `InstanceId`, `NodeName`  |  节点上当前预留的 GPU 百分比。公式是 `node_gpu_request / node_gpu_limit`。  `node_gpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_filesystem_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上正在使用的文件系统容量的总百分比。 公式：`node_filesystem_usage / node_filesystem_capacity`  `node_filesystem_usage` 和 `node_filesystem_capacity` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_limit`  |  `ClusterName`  |  可以分配给此集群中单个节点的最大内存量（以字节为单位）。  | 
|  `node_memory_reserved_capacity`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中节点上当前正在使用的内存百分比。 公式：`node_memory_request / node_memory_limit`  `node_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_memory_utilization`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  一个或多个节点当前正在使用的内存百分比。它是节点内存使用量除以节点内存限制的百分比。 公式：`node_memory_working_set / node_memory_limit`。  | 
|  `node_memory_working_set`  |  `ClusterName`   |  集群中节点的工作集中正在使用的内存量（以字节为单位）。  | 
|  `node_network_total_bytes`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点通过网络传输和接收的每秒总字节数。 公式：`node_network_rx_bytes + node_network_tx_bytes`  `node_network_rx_bytes` 和 `node_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `node_number_of_running_containers`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点的正在运行的容器数。  | 
|  `node_number_of_running_pods`  |  `NodeName`, `ClusterName`, `InstanceId` `ClusterName`  |  集群中每个节点上运行的 pod 的数量。  | 
|  `pod_cpu_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName`  |  集群中每个 pod 预留的 CPU 容量。 公式：`pod_cpu_request / node_cpu_limit`  `pod_cpu_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_cpu_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  pod 所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / node_cpu_limit`  | 
|  `pod_cpu_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  相对于容器组（pod）限制的容器组（pod）所使用的 CPU 单元的百分比。 公式：`pod_cpu_usage_total / pod_cpu_limit`  | 
|  `pod_gpu_request` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  容器组 (pod) 的 CPU 请求。此值必须始终等于 `pod_gpu_limit`。  | 
|  `pod_gpu_limit` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  可以分配给节点中容器组 (pod) 的 GPU 的最大数量。  | 
|  `pod_gpu_usage_total` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  在 Pod 上分配的 GPU 数量。  | 
|  `pod_gpu_reserved_capacity` |  `ClusterName` `ClusterName`, `Namespace`, `PodName` `ClusterName`, `FullPodName`, `Namespace`, `PodName`  |  当前为容器组 (pod) 预留的 GPU 百分比。公式是 pod\$1gpu\$1request / node\$1gpu\$1reserved\$1capacity。  | 
|  `pod_memory_reserved_capacity`  |  `PodName`, `Namespace`, `ClusterName` `ClusterName`  |  为 pod 预留的内存的百分比。 公式：`pod_memory_request / node_memory_limit`  `pod_memory_request` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_memory_utilization`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  一个或多个 pod 当前正在使用的内存百分比。 公式：`pod_memory_working_set / node_memory_limit`  | 
|  `pod_memory_utilization_over_pod_limit`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  相对于容器组（pod）限制的容器组（pod）所使用的内存百分比。如果容器组（pod）中的任何容器没有定义内存限制，则不会显示该指标。 公式：`pod_memory_working_set / pod_memory_limit`  | 
|  `pod_network_rx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  pod 通过网络每秒接收的字节数。 公式：`sum(pod_interface_network_rx_bytes)`  `pod_interface_network_rx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_network_tx_bytes`  |  `PodName`, `Namespace`, `ClusterName` `Namespace`, `ClusterName` `Service`, `Namespace`, `ClusterName` `ClusterName`  |  pod 通过网络每秒传输的字节数。 公式：`sum(pod_interface_network_tx_bytes)`  `pod_interface_network_tx_bytes` 不是直接作为指标报告，而是性能日志事件中的一个字段。有关更多信息，请参阅 [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)。   | 
|  `pod_number_of_container_restarts`  |  `PodName`, `Namespace`, `ClusterName`  |  一个 pod 中容器重新启动的总次数。  | 
|  `service_number_of_running_pods`  |  `Service`, `Namespace`, `ClusterName` `ClusterName`  |  运行集群中的服务的 pod 的数量。  | 

## Kueue 指标
<a name="Container-Insights-metrics-Kueue"></a>

从 CloudWatch 可观测性 EKS 附加组件的 `v2.4.0-eksbuild.1` 版本开始，适用于 Amazon EKS 的 Container Insights 支持从 Amazon EKS 集群收集 Kueue 指标。有关附加组件的更多信息，请参阅 [使用 Amazon CloudWatch Observability EKS 附加组件或 Helm 图表安装 CloudWatch 代理](install-CloudWatch-Observability-EKS-addon.md)。

有关启用这些指标的信息，请参阅[启用 Kueue 指标](install-CloudWatch-Observability-EKS-addon.md#enable-Kueue-metrics)来启用这些指标。

下表中列出了收集的 Kueue 指标。这些指标将发布到 CloudWatch 中的 `ContainerInsights/Prometheus` 命名空间中。其中一些指标使用以下维度：
+ `ClusterQueue` 是 ClusterQueue 的名称
+ `Status` 的可能值为 `active` 和 `inadmissible`
+ `Reason` 的可能值为 `Preempted`、`PodsReadyTimeout`、`AdmissionCheck`、`ClusterQueueStopped` 和 `InactiveWorkload`
+ `Flavor` 是引用的风格。
+ `Resource` 指集群计算机资源，例如 `cpu`、`memory`、`gpu` 等。


| 指标名称 | Dimensions | 说明 | 
| --- | --- | --- | 
|  `kueue_pending_workloads` |  `ClusterName`, `ClusterQueue`, `Status` `ClusterName`, `ClusterQueue` `ClusterName`, `Status` `ClusterName`  |  待处理的工作负载数量。  | 
|  `kueue_evicted_workloads_total` |  `ClusterName`, `ClusterQueue`, `Reason` `ClusterName`, `ClusterQueue` `ClusterName`, `Reason` `ClusterName`  |  已驱逐工作负载总数。  | 
|  `kueue_admitted_active_workloads` |  `ClusterName`, `ClusterQueue` `ClusterName`  |  允许的处于活动状态（未暂停和未完成）的工作负载数量。  | 
|  `kueue_cluster_queue_resource_usage` |  `ClusterName`, `ClusterQueue`, `Resource`, `Flavor` `ClusterName`, `ClusterQueue`, `Resource` `ClusterName`, `ClusterQueue`, `Flavor` `ClusterName`, `ClusterQueue` `ClusterName`  |  报告 ClusterQueue 的总资源使用情况。  | 
|  `kueue_cluster_queue_nominal_quota` |  `ClusterName`, `ClusterQueue`, `Resource`, `Flavor` `ClusterName`, `ClusterQueue`, `Resource` `ClusterName`, `ClusterQueue`, `Flavor` `ClusterName`, `ClusterQueue` `ClusterName`  |  报告 ClusterQueue 的资源配额。  | 

# Container Insights 性能日志参考
<a name="Container-Insights-reference"></a>

本节包含有关 Container Insights 如何使用性能日志事件来收集指标的参考信息。当您部署 Container Insights 时，它会自动为性能日志事件创建日志组。您无需自行创建该日志组。

**Topics**
+ [Amazon ECS 的 Container Insights 性能日志事件](Container-Insights-reference-performance-logs-ECS.md)
+ [Amazon EKS 和 Kubernetes 的 Container Insights 性能日志事件](Container-Insights-reference-performance-logs-EKS.md)
+ [Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段](Container-Insights-reference-performance-entries-EKS.md)

# Amazon ECS 的 Container Insights 性能日志事件
<a name="Container-Insights-reference-performance-logs-ECS"></a>

以下是 Container Insights 从 Amazon ECS 收集的性能日志事件的实例。

这些日志在 CloudWatch Logs 中位于名为 `/aws/ecs/containerinsights/CLUSTER_NAME/performance` 的日志组中。在该日志组中，每个容器实例都将有一个名为 `AgentTelemetry-CONTAINER_INSTANCE_ID` 的日志流。

您可以使用查询来查询这些日志，例如使用 `{ $.Type = "Container" }` 来查看所有容器日志事件。

**类型：容器**

```
{
	"Version":"0",
	"Type":"Container",
	"ContainerName":"sleep",
	"TaskId":"7ac4dfba69214411b4783a3b8189c9ba",
	"TaskDefinitionFamily":"sleep360",
	"TaskDefinitionRevision":"1",
	"ContainerInstanceId":"0d7650e6dec34c1a9200f72098071e8f",
	"EC2InstanceId":"i-0c470579dbcdbd2f3",
	"ClusterName":"MyCluster",
	"Image":"busybox",
	"ContainerKnownStatus":"RUNNING",
	"Timestamp":1623963900000,
	"CpuUtilized":0.0,
	"CpuReserved":10.0,
	"MemoryUtilized":0,
	"MemoryReserved":10,
	"StorageReadBytes":0,
	"StorageWriteBytes":0,
	"NetworkRxBytes":0,
	"NetworkRxDropped":0,
	"NetworkRxErrors":0,
	"NetworkRxPackets":14,
	"NetworkTxBytes":0,
	"NetworkTxDropped":0,
	"NetworkTxErrors":0,
	"NetworkTxPackets":0
}
```

**类型：任务**

尽管 `StorageReadBytes` 和 `StorageWriteBytes` 以字节/秒为单位，但这些值分别表示从存储中读取和写入存储的累积字节数。

```
{
    "Version": "0",
    "Type": "Task",
    "TaskId": "7ac4dfba69214411b4783a3b8189c9ba",
    "TaskDefinitionFamily": "sleep360",
    "TaskDefinitionRevision": "1",
    "ContainerInstanceId": "0d7650e6dec34c1a9200f72098071e8f",
    "EC2InstanceId": "i-0c470579dbcdbd2f3",
    "ClusterName": "MyCluster",
    "AccountID": "637146863587",
    "Region": "us-west-2",
    "AvailabilityZone": "us-west-2b",
    "KnownStatus": "RUNNING",
    "LaunchType": "EC2",
    "PullStartedAt": 1623963608201,
    "PullStoppedAt": 1623963610065,
    "CreatedAt": 1623963607094,
    "StartedAt": 1623963610382,
    "Timestamp": 1623963900000,
    "CpuUtilized": 0.0,
    "CpuReserved": 10.0,
    "MemoryUtilized": 0,
    "MemoryReserved": 10,
    "StorageReadBytes": 0,
    "StorageWriteBytes": 0,
    "NetworkRxBytes": 0,
    "NetworkRxDropped": 0,
    "NetworkRxErrors": 0,
    "NetworkRxPackets": 14,
    "NetworkTxBytes": 0,
    "NetworkTxDropped": 0,
    "NetworkTxErrors": 0,
    "NetworkTxPackets": 0,
    "EBSFilesystemUtilized": 10,
    "EBSFilesystemSize": 20,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "CpuUtilized",
                    "Unit": "None"
                },
                {
                    "Name": "CpuReserved",
                    "Unit": "None"
                },
                {
                    "Name": "MemoryUtilized",
                    "Unit": "Megabytes"
                },
                {
                    "Name": "MemoryReserved",
                    "Unit": "Megabytes"
                },
                {
                    "Name": "StorageReadBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "StorageWriteBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "NetworkRxBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "NetworkTxBytes",
                    "Unit": "Bytes/Second"
                },
                {
                    "Name": "EBSFilesystemSize",
                    "Unit": "Gigabytes"
                },
                {
                    "Name": "EBSFilesystemUtilzed",
                    "Unit": "Gigabytes"
                }
            ],
            "Dimensions": [
                ["ClusterName"],
                [
                    "ClusterName",
                    "TaskDefinitionFamily"
                ]
            ]
        }
    ]
}
```

**类型：服务**

```
{   
    "Version": "0",
    "Type": "Service",
    "ServiceName": "myCIService",
    "ClusterName": "myCICluster",
    "Timestamp": 1561586460000,
    "DesiredTaskCount": 2,
    "RunningTaskCount": 2,
    "PendingTaskCount": 0,
    "DeploymentCount": 1,
    "TaskSetCount": 0,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "DesiredTaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "RunningTaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "PendingTaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "DeploymentCount",
                    "Unit": "Count"
                },
                {
                    "Name": "TaskSetCount",
                    "Unit": "Count"
                }
            ],
            "Dimensions": [
                [
                    "ServiceName",
                    "ClusterName"
                ]
            ]
        }
    ]
}
```

**类型：卷**

```
{
    "Version": "0",
    "Type": "Volume",
    "TaskDefinitionFamily": "myCITaskDef",
    "TaskId": "7ac4dfba69214411b4783a3b8189c9ba",
    "ClusterName": "myCICluster",
    "ServiceName": "myCIService",
    "VolumeId": "vol-1233436545ff708cb",
    "InstanceId": "i-0c470579dbcdbd2f3",
    "LaunchType": "EC2",
    "VolumeName": "MyVolumeName",
    "EBSFilesystemUtilized": 10,
    "EBSFilesystemSize": 20,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "EBSFilesystemSize",
                    "Unit": "Gigabytes"
                },
                {
                    "Name": "EBSFilesystemUtilzed",
                    "Unit": "Gigabytes"
                }
            ],
            "Dimensions": [
                ["ClusterName"],
                [
                    "VolumeName",
                    "TaskDefinitionFamily",
                    "ClusterName"
                ],
                [
                    "ServiceName",
                    "ClusterName"
                ]
            ]
        }
    ]
}
```

**类型：集群**

```
{
    "Version": "0",
    "Type": "Cluster",
    "ClusterName": "myCICluster",
    "Timestamp": 1561587300000,
    "TaskCount": 5,
    "ContainerInstanceCount": 5,
    "ServiceCount": 2,
    "CloudWatchMetrics": [
        {
            "Namespace": "ECS/ContainerInsights",
            "Metrics": [
                {
                    "Name": "TaskCount",
                    "Unit": "Count"
                },
                {
                    "Name": "ContainerInstanceCount",
                    "Unit": "Count"
                },
                {
                    "Name": "ServiceCount",
                    "Unit": "Count"
                }
            ],
            "Dimensions": [
                [
                    "ClusterName"
                ]
            ]
        }
    ]
}
```

# Amazon EKS 和 Kubernetes 的 Container Insights 性能日志事件
<a name="Container-Insights-reference-performance-logs-EKS"></a>

以下是 Container Insights 从 Amazon EKS 和 Kubernetes 集群中收集的性能日志事件的示例。

**类型：Node**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "node_cpu_utilization"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_utilization"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "node_network_total_bytes"
        },
        {
          "Unit": "Percent",
          "Name": "node_cpu_reserved_capacity"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_reserved_capacity"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_pods"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_containers"
        }
      ],
      "Dimensions": [
        [
          "NodeName",
          "InstanceId",
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    },
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "node_cpu_utilization"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_utilization"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "node_network_total_bytes"
        },
        {
          "Unit": "Percent",
          "Name": "node_cpu_reserved_capacity"
        },
        {
          "Unit": "Percent",
          "Name": "node_memory_reserved_capacity"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_pods"
        },
        {
          "Unit": "Count",
          "Name": "node_number_of_running_containers"
        },
        {
          "Name": "node_cpu_usage_total"
        },
        {
          "Name": "node_cpu_limit"
        },
        {
          "Unit": "Bytes",
          "Name": "node_memory_working_set"
        },
        {
          "Unit": "Bytes",
          "Name": "node_memory_limit"
        }
      ],
      "Dimensions": [
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor",
    "/proc",
    "pod",
    "calculated"
  ],
  "Timestamp": "1567096682364",
  "Type": "Node",
  "Version": "0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_cpu_limit": 4000,
  "node_cpu_request": 1130,
  "node_cpu_reserved_capacity": 28.249999999999996,
  "node_cpu_usage_system": 33.794636630852764,
  "node_cpu_usage_total": 136.47852169244098,
  "node_cpu_usage_user": 71.67075111567326,
  "node_cpu_utilization": 3.4119630423110245,
  "node_memory_cache": 3103297536,
  "node_memory_failcnt": 0,
  "node_memory_hierarchical_pgfault": 0,
  "node_memory_hierarchical_pgmajfault": 0,
  "node_memory_limit": 16624865280,
  "node_memory_mapped_file": 406646784,
  "node_memory_max_usage": 4230746112,
  "node_memory_pgfault": 0,
  "node_memory_pgmajfault": 0,
  "node_memory_request": 1115684864,
  "node_memory_reserved_capacity": 6.7109407818311055,
  "node_memory_rss": 798146560,
  "node_memory_swap": 0,
  "node_memory_usage": 3901444096,
  "node_memory_utilization": 6.601302600149552,
  "node_memory_working_set": 1097457664,
  "node_network_rx_bytes": 35918.392817386324,
  "node_network_rx_dropped": 0,
  "node_network_rx_errors": 0,
  "node_network_rx_packets": 157.67565245448117,
  "node_network_total_bytes": 68264.20276554905,
  "node_network_tx_bytes": 32345.80994816272,
  "node_network_tx_dropped": 0,
  "node_network_tx_errors": 0,
  "node_network_tx_packets": 154.21455923431654,
  "node_number_of_running_containers": 16,
  "node_number_of_running_pods": 13
}
```

**类型：NodeFS**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "node_filesystem_utilization"
        }
      ],
      "Dimensions": [
        [
          "NodeName",
          "InstanceId",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "EBSVolumeId": "aws://us-west-2b/vol-0a53108976d4a2fda",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567097939726",
  "Type": "NodeFS",
  "Version": "0",
  "device": "/dev/nvme0n1p1",
  "fstype": "vfs",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_filesystem_available": 17298395136,
  "node_filesystem_capacity": 21462233088,
  "node_filesystem_inodes": 10484720,
  "node_filesystem_inodes_free": 10367158,
  "node_filesystem_usage": 4163837952,
  "node_filesystem_utilization": 19.400767547940255
}
```

**类型：NodeDiskIO**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "EBSVolumeId": "aws://us-west-2b/vol-0a53108976d4a2fda",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor"
  ],
  "Timestamp": "1567096928131",
  "Type": "NodeDiskIO",
  "Version": "0",
  "device": "/dev/nvme0n1",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_diskio_io_service_bytes_async": 9750.505814277016,
  "node_diskio_io_service_bytes_read": 0,
  "node_diskio_io_service_bytes_sync": 230.6174506688036,
  "node_diskio_io_service_bytes_total": 9981.123264945818,
  "node_diskio_io_service_bytes_write": 9981.123264945818,
  "node_diskio_io_serviced_async": 1.153087253344018,
  "node_diskio_io_serviced_read": 0,
  "node_diskio_io_serviced_sync": 0.03603397666700056,
  "node_diskio_io_serviced_total": 1.1891212300110185,
  "node_diskio_io_serviced_write": 1.1891212300110185
}
```

**类型：NodeNet**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567096928131",
  "Type": "NodeNet",
  "Version": "0",
  "interface": "eni972f6bfa9a0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal"
  },
  "node_interface_network_rx_bytes": 3163.008420864309,
  "node_interface_network_rx_dropped": 0,
  "node_interface_network_rx_errors": 0,
  "node_interface_network_rx_packets": 16.575629266820258,
  "node_interface_network_total_bytes": 3518.3935157426017,
  "node_interface_network_tx_bytes": 355.385094878293,
  "node_interface_network_tx_dropped": 0,
  "node_interface_network_tx_errors": 0,
  "node_interface_network_tx_packets": 3.9997714100370625
}
```

**类型：Pod**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "pod_cpu_utilization"
        },
        {
          "Unit": "Percent",
          "Name": "pod_memory_utilization"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "pod_network_rx_bytes"
        },
        {
          "Unit": "Bytes/Second",
          "Name": "pod_network_tx_bytes"
        },
        {
          "Unit": "Percent",
          "Name": "pod_cpu_utilization_over_pod_limit"
        },
        {
          "Unit": "Percent",
          "Name": "pod_memory_utilization_over_pod_limit"
        }
      ],
      "Dimensions": [
        [
          "PodName",
          "Namespace",
          "ClusterName"
        ],
        [
          "Service",
          "Namespace",
          "ClusterName"
        ],
        [
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    },
    {
      "Metrics": [
        {
          "Unit": "Percent",
          "Name": "pod_cpu_reserved_capacity"
        },
        {
          "Unit": "Percent",
          "Name": "pod_memory_reserved_capacity"
        }
      ],
      "Dimensions": [
        [
          "PodName",
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    },
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "pod_number_of_container_restarts"
        }
      ],
      "Dimensions": [
        [
          "PodName",
          "Namespace",
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "pod",
    "calculated"
  ],
  "Timestamp": "1567097351092",
  "Type": "Pod",
  "Version": "0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  },
  "pod_cpu_limit": 200,
  "pod_cpu_request": 200,
  "pod_cpu_reserved_capacity": 5,
  "pod_cpu_usage_system": 1.4504841104992765,
  "pod_cpu_usage_total": 5.817016867430125,
  "pod_cpu_usage_user": 1.1281543081661038,
  "pod_cpu_utilization": 0.14542542168575312,
  "pod_cpu_utilization_over_pod_limit": 2.9085084337150624,
  "pod_memory_cache": 8192,
  "pod_memory_failcnt": 0,
  "pod_memory_hierarchical_pgfault": 0,
  "pod_memory_hierarchical_pgmajfault": 0,
  "pod_memory_limit": 104857600,
  "pod_memory_mapped_file": 0,
  "pod_memory_max_usage": 25268224,
  "pod_memory_pgfault": 0,
  "pod_memory_pgmajfault": 0,
  "pod_memory_request": 104857600,
  "pod_memory_reserved_capacity": 0.6307275170893897,
  "pod_memory_rss": 22777856,
  "pod_memory_swap": 0,
  "pod_memory_usage": 25141248,
  "pod_memory_utilization": 0.10988455961791709,
  "pod_memory_utilization_over_pod_limit": 17.421875,
  "pod_memory_working_set": 18268160,
  "pod_network_rx_bytes": 9880.697124714186,
  "pod_network_rx_dropped": 0,
  "pod_network_rx_errors": 0,
  "pod_network_rx_packets": 107.80005532263283,
  "pod_network_total_bytes": 10158.829201483635,
  "pod_network_tx_bytes": 278.13207676944796,
  "pod_network_tx_dropped": 0,
  "pod_network_tx_errors": 0,
  "pod_network_tx_packets": 1.146027574644318,
  "pod_number_of_container_restarts": 0,
  "pod_number_of_containers": 1,
  "pod_number_of_running_containers": 1,
  "pod_status": "Running"
}
```

**类型：PodNet**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567097351092",
  "Type": "PodNet",
  "Version": "0",
  "interface": "eth0",
  "kubernetes": {
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  },
  "pod_interface_network_rx_bytes": 9880.697124714186,
  "pod_interface_network_rx_dropped": 0,
  "pod_interface_network_rx_errors": 0,
  "pod_interface_network_rx_packets": 107.80005532263283,
  "pod_interface_network_total_bytes": 10158.829201483635,
  "pod_interface_network_tx_bytes": 278.13207676944796,
  "pod_interface_network_tx_dropped": 0,
  "pod_interface_network_tx_errors": 0,
  "pod_interface_network_tx_packets": 1.146027574644318
}
```

**类型：容器**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-sample",
  "ClusterName": "myCICluster",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "pod",
    "calculated"
  ],
  "Timestamp": "1567097399912",
  "Type": "Container",
  "Version": "0",
  "container_cpu_limit": 200,
  "container_cpu_request": 200,
  "container_cpu_usage_system": 1.87958283771964,
  "container_cpu_usage_total": 6.159993652997942,
  "container_cpu_usage_user": 1.6707403001952357,
  "container_cpu_utilization": 0.15399984132494854,
  "container_memory_cache": 8192,
  "container_memory_failcnt": 0,
  "container_memory_hierarchical_pgfault": 0,
  "container_memory_hierarchical_pgmajfault": 0,
  "container_memory_limit": 104857600,
  "container_memory_mapped_file": 0,
  "container_memory_max_usage": 24580096,
  "container_memory_pgfault": 0,
  "container_memory_pgmajfault": 0,
  "container_memory_request": 104857600,
  "container_memory_rss": 22736896,
  "container_memory_swap": 0,
  "container_memory_usage": 24453120,
  "container_memory_utilization": 0.10574541028701798,
  "container_memory_working_set": 17580032,
  "container_status": "Running",
  "kubernetes": {
    "container_name": "cloudwatch-agent",
    "docker": {
      "container_id": "8967b6b37da239dfad197c9fdea3e5dfd35a8a759ec86e2e4c3f7b401e232706"
    },
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  },
  "number_of_container_restarts": 0
}
```

**类型：ContainerFS**

```
{
  "AutoScalingGroupName": "eksctl-myCICluster-nodegroup-standard-workers-NodeGroup-1174PV2WHZAYU",
  "ClusterName": "myCICluster",
  "EBSVolumeId": "aws://us-west-2b/vol-0a53108976d4a2fda",
  "InstanceId": "i-1234567890123456",
  "InstanceType": "t3.xlarge",
  "Namespace": "amazon-cloudwatch",
  "NodeName": "ip-192-0-2-0.us-west-2.compute.internal",
  "PodName": "cloudwatch-agent-statsd",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "cadvisor",
    "calculated"
  ],
  "Timestamp": "1567097399912",
  "Type": "ContainerFS",
  "Version": "0",

  "device": "/dev/nvme0n1p1",
  "fstype": "vfs",
  "kubernetes": {
    "container_name": "cloudwatch-agent",
    "docker": {
      "container_id": "8967b6b37da239dfad197c9fdea3e5dfd35a8a759ec86e2e4c3f7b401e232706"
    },
    "host": "ip-192-168-75-26.us-west-2.compute.internal",
    "labels": {
      "app": "cloudwatch-agent-statsd",
      "pod-template-hash": "df44f855f"
    },
    "namespace_name": "amazon-cloudwatch",
    "pod_id": "2f4ff5ac-c813-11e9-a31d-06e9dde32928",
    "pod_name": "cloudwatch-agent-statsd-df44f855f-ts4q2",
    "pod_owners": [
      {
        "owner_kind": "Deployment",
        "owner_name": "cloudwatch-agent-statsd"
      }
    ],
    "service_name": "cloudwatch-agent-statsd"
  }
}
```

**类型：集群**

```
{
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "cluster_node_count"
        },
        {
          "Unit": "Count",
          "Name": "cluster_failed_node_count"
        }
      ],
      "Dimensions": [
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "Sources": [
    "apiserver"
  ],
  "Timestamp": "1567097534160",
  "Type": "Cluster",
  "Version": "0",
  "cluster_failed_node_count": 0,
  "cluster_node_count": 3
}
```

**类型：“ClusterService”**

```
{
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "service_number_of_running_pods"
        }
      ],
      "Dimensions": [
        [
          "Service",
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "Namespace": "amazon-cloudwatch",
  "Service": "cloudwatch-agent-statsd",
  "Sources": [
    "apiserver"
  ],
  "Timestamp": "1567097534160",
  "Type": "ClusterService",
  "Version": "0",
  "kubernetes": {
    "namespace_name": "amazon-cloudwatch",
    "service_name": "cloudwatch-agent-statsd"
  },
  "service_number_of_running_pods": 1
}
```

**类型：ClusterNamespace**

```
{
  "CloudWatchMetrics": [
    {
      "Metrics": [
        {
          "Unit": "Count",
          "Name": "namespace_number_of_running_pods"
        }
      ],
      "Dimensions": [
        [
          "Namespace",
          "ClusterName"
        ],
        [
          "ClusterName"
        ]
      ],
      "Namespace": "ContainerInsights"
    }
  ],
  "ClusterName": "myCICluster",
  "Namespace": "amazon-cloudwatch",
  "Sources": [
    "apiserver"
  ],
  "Timestamp": "1567097594160",
  "Type": "ClusterNamespace",
  "Version": "0",
  "kubernetes": {
    "namespace_name": "amazon-cloudwatch"
  },
  "namespace_number_of_running_pods": 7
}
```

# Amazon EKS 和 Kubernetes 的性能日志事件中的相关字段
<a name="Container-Insights-reference-performance-entries-EKS"></a>

对于 Amazon EKS 和 Kubernetes，容器化的 CloudWatch 代理将数据作为性能日志事件发出。这使 CloudWatch 能够摄取和存储高基数数据。CloudWatch 使用性能日志事件中的数据在集群、节点和 pod 级别创建聚合的 CloudWatch 指标，而不会丢失详细信息。

下表列出了这些性能日志事件中与 Container Insights 指标数据收集相关的字段。您可以使用 CloudWatch Logs Insights 查询其中的任何字段以收集数据或调查问题。有关更多信息，请参阅[使用 CloudWatch Logs Insights 分析日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)。


| Type | 日志字段 | 来源 | 公式或备注 | 
| --- | --- | --- | --- | 
|  Pod |  `pod_cpu_utilization`  |  计算  |  公式：`pod_cpu_usage_total / node_cpu_limit`  | 
|  Pod |  `pod_cpu_usage_total` `pod_cpu_usage_total` 以千分之一核心为单位报道。  |  cadvisor  |   | 
|  Pod |  `pod_cpu_limit`  |  计算  |  公式：`sum(container_cpu_limit)` `sum(container_cpu_limit)` 包括已经完成的容器组（pod）。 如果 pod 中的任何容器未定义 CPU 限制，则该字段不会显示在日志事件中。这包括 [init 容器](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#resources)。  | 
|  Pod |  `pod_cpu_request`  |  计算  |  公式：`sum(container_cpu_request)` 不保证设置 `container_cpu_request`。仅在总和中包括设置的字段。  | 
|  Pod |  `pod_cpu_utilization_over_pod_limit`  |  计算  |  公式：`pod_cpu_usage_total / pod_cpu_limit`  | 
|  Pod |  `pod_cpu_reserved_capacity`  |  计算  |  公式：`pod_cpu_request / node_cpu_limit`  | 
|  Pod |  `pod_memory_utilization`  |  计算  |  公式：`pod_memory_working_set / node_memory_limit` 它是 pod 内存使用量相比节点内存限制的百分比。  | 
|  Pod |  `pod_memory_working_set`  |  cadvisor  |   | 
|  Pod |  `pod_memory_limit`  |  计算  |  公式：`sum(container_memory_limit)` 如果 pod 中的任何容器没有定义内存限制，则该字段不会显示在日志事件中。这包括 [init 容器](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#resources)。  | 
|  Pod |  `pod_memory_request`  |  计算  |  公式：`sum(container_memory_request)` 不保证设置 `container_memory_request`。仅在总和中包括设置的字段。  | 
|  Pod |  `pod_memory_utilization_over_pod_limit`  |  计算  |  公式：`pod_memory_working_set / pod_memory_limit` 如果 pod 中的任何容器没有定义内存限制，则该字段不会显示在日志事件中。这包括 [init 容器](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#resources)。  | 
|  Pod |  `pod_memory_reserved_capacity`  |  计算  |  公式：`pod_memory_request / node_memory_limit`  | 
|  Pod |  `pod_network_tx_bytes`  |  计算  |  公式：`sum(pod_interface_network_tx_bytes)` 该数据适用于每个 pod 的所有网络接口。CloudWatch 代理计算总数并添加指标提取规则。  | 
|  Pod |  `pod_network_rx_bytes`  |  计算  |  公式：`sum(pod_interface_network_rx_bytes)`  | 
|  Pod |  `pod_network_total_bytes`  |  计算  |  公式：`pod_network_rx_bytes + pod_network_tx_bytes`  | 
|  PodNet |  `pod_interface_network_rx_bytes`  |  cadvisor  | 该数据是 pod 网络接口每秒接收的网络字节数。  | 
|  PodNet |  `pod_interface_network_tx_bytes`  |  cadvisor  | 该数据是 pod 网络接口每秒发送的网络字节数。 | 
|  容器 |  `container_cpu_usage_total`  |  cadvisor  |   | 
|  容器 |  `container_cpu_limit`  |  cadvisor  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  容器 |  `container_cpu_request`  |  cadvisor  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  容器 |  `container_memory_working_set`  |  cadvisor  |   | 
|  容器 |  `container_memory_limit`  |  容器组（pod）  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  容器 |  `container_memory_request`  |  容器组（pod）  |  不保证设置该字段。如果未设置，则不会发出该指标。 | 
|  节点 |  `node_cpu_utilization`  |  计算  |  公式：`node_cpu_usage_total / node_cpu_limit`  | 
|  节点 |  `node_cpu_usage_total`  |  cadvisor  |   | 
|  节点 |  `node_cpu_limit`  |  /proc  |   | 
|  节点 |  `node_cpu_request`  |  计算  | 公式：`sum(pod_cpu_request)` 对于 cronjobs，`node_cpu_request` 还包括来自已完成的容器组（pod）的请求。这可能会导致 `node_cpu_reserved_capacity` 的值很高。  | 
|  节点 |  `node_cpu_reserved_capacity`  |  计算  | 公式：`node_cpu_request / node_cpu_limit`  | 
|  节点 |  `node_memory_utilization`  |  计算  | 公式：`node_memory_working_set / node_memory_limit`  | 
|  节点 |  `node_memory_working_set`  |  cadvisor  |   | 
|  节点 |  `node_memory_limit`  |  /proc  |   | 
|  节点 |  `node_memory_request`  |  计算  |  公式：`sum(pod_memory_request)`  | 
|  节点 |  `node_memory_reserved_capacity`  |  计算  | 公式：`node_memory_request / node_memory_limit`  | 
|  节点 |  `node_network_rx_bytes`  |  计算  | 公式：`sum(node_interface_network_rx_bytes)`  | 
|  节点 |  `node_network_tx_bytes`  |  计算  | 公式：`sum(node_interface_network_tx_bytes)`  | 
|  节点 |  `node_network_total_bytes`  |  计算  | 公式：`node_network_rx_bytes + node_network_tx_bytes`  | 
|  节点 |  `node_number_of_running_pods`  |  Pod 列表  |   | 
|  节点 |  `node_number_of_running_containers`  |  Pod 列表  |   | 
|  NodeNet |  `node_interface_network_rx_bytes`  |  cadvisor  |  该数据是工作线程节点网络接口每秒接收的网络字节数。  | 
|  NodeNet |  `node_interface_network_tx_bytes`  |  cadvisor  |  该数据是工作线程节点网络接口每秒发送的网络字节数。  | 
|  NodeFS |  `node_filesystem_capacity`  |  cadvisor  |   | 
|  NodeFS |  `node_filesystem_usage`  |  cadvisor  |   | 
|  NodeFS |  `node_filesystem_utilization`  |  计算  |  公式：`node_filesystem_usage / node_filesystem_capacity` 该数据适用于每个设备名称。  | 
|  集群 |  `cluster_failed_node_count`  |  API 服务器  |   | 
|  集群 |  `cluster_node_count`  |  API 服务器  |   | 
|  服务 |  `service_number_of_running_pods`  |  API 服务器  |   | 
|  `Namespace` |  `namespace_number_of_running_pods`  |  API 服务器  |   | 

## 指标计算示例
<a name="Container-Insights-calculation-examples"></a>

本节包含的示例说明了如何计算上表中的某些值。

假设您具有一个处于以下状态的集群。

```
Node1
   node_cpu_limit = 4
   node_cpu_usage_total = 3
   
   Pod1
     pod_cpu_usage_total = 2
     
     Container1
        container_cpu_limit = 1
        container_cpu_request = 1
        container_cpu_usage_total = 0.8
        
     Container2
        container_cpu_limit = null
        container_cpu_request = null
        container_cpu_usage_total = 1.2
        
   Pod2
     pod_cpu_usage_total = 0.4
     
     Container3
        container_cpu_limit = 1
        container_cpu_request = 0.5
        container_cpu_usage_total = 0.4
        
Node2
   node_cpu_limit = 8
   node_cpu_usage_total = 1.5
   
   Pod3
     pod_cpu_usage_total = 1
     
     Container4
        container_cpu_limit = 2
        container_cpu_request = 2
        container_cpu_usage_total = 1
```

下表说明了如何使用该数据计算 pod CPU 指标。


| 指标 | Formula | Pod1 | Pod2 | Pod3 | 
| --- | --- | --- | --- | --- | 
|  `pod_cpu_utilization` |  `pod_cpu_usage_total / node_cpu_limit`  |  2 / 4 = 50%  |  0.4 / 4 = 10%  |  1 / 8 = 12.5%  | 
|  `pod_cpu_utilization_over_pod_limit` |  `pod_cpu_usage_total / sum(container_cpu_limit)`  |  不适用，因为没有定义 `Container2` 的 CPU 限制  |  0.4 / 1 = 40%  |  1 / 2 = 50%  | 
|  `pod_cpu_reserved_capacity` |  `sum(container_cpu_request) / node_cpu_limit`  |  (1 \$1 0) / 4 = 25%  |  0.5 / 4 = 12.5%  |  2 / 8 = 25%  | 

下表说明了如何使用该数据计算节点 CPU 指标。


| 指标 | Formula | Node1 | Node2 | 
| --- | --- | --- | --- | 
|  `node_cpu_utilization` |  `node_cpu_usage_total / node_cpu_limit`  |  3 / 4 = 75%  |  1.5 / 8 = 18.75%  | 
|  `node_cpu_reserved_capacity` |  `sum(pod_cpu_request) / node_cpu_limit`  |  1.5 / 4 = 37.5%  |  2 / 8 = 25%  | 

# Container Insights Prometheus 指标监控
<a name="ContainerInsights-Prometheus"></a>

适用于 Prometheus 的 CloudWatch Container Insights 监控可以自动发现来自容器化系统和工作负载的 Prometheus 指标。Prometheus 是一个开源系统监控和警报工具包。有关更多信息，请参阅 Prometheus 文档中的[什么是 Prometheus？](https://prometheus.io/docs/introduction/overview/)

[Amazon Elastic Container Service](https://aws.amazon.com/ecs/)、[Amazon Elastic Kubernetes Service](https://aws.amazon.com/eks/) 和在 Amazon EC2 实例上运行的 [Kubernetes](https://aws.amazon.com/kubernetes/) 集群支持发现 Prometheus 指标。收集了 Prometheus 计数器、计量表和汇总指标类型。

对于 Amazon ECS 和 Amazon EKS 集群，EC2 和 Fargate 启动类型均受支持。Container Insights 会自动从多个工作负载收集指标，您可以将其配置为从任何工作负载收集指标。

您可以采用 Prometheus 作为开源和开放标准方法，在 CloudWatch 中摄取自定义指标。具有 Prometheus 支持的 CloudWatch 代理可以发现并收集 Prometheus 指标，以便监控应用程序性能下降和故障，并更快地进行故障排除和发出告警。这也减少了改进可观测性所需的监控工具数量。

Container Insights Prometheus 支持涉及按用量付费的指标和日志，包括收集、存储和分析。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**某些工作负载的预构建控制面板**

Container Insights Prometheus 解决方案包括针对本节中列出的常见工作负载的预构建控制面板。有关这些工作负载的示例配置，请参阅 [（可选）为 Prometheus 指标测试设置示例容器化 Amazon ECS 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS.md) 和 [（可选）为 Prometheus 指标测试设置示例容器化 Amazon EKS 工作负载](ContainerInsights-Prometheus-Sample-Workloads.md)。

您还可以配置 Container Insights 以通过编辑代理配置文件从其他容器化服务和应用程序收集 Prometheus 指标。

带有适用于在 Amazon EC2 实例上运行的 Amazon EKS 集群和 Kubernetes 集群的预构建控制面板的工作负载：
+ AWS App Mesh
+ NGINX
+ Memcached
+ Java/JMX
+ HAProxy

带有适用于 Amazon ECS 集群的预构建控制面板的工作负载：
+ AWS App Mesh
+ Java/JMX
+ NGINX
+ NGINX Plus

# 在亚马逊云服务器集群上设置和配置 Prometheus 指标收集 在 Amazon ECS 集群上设置和配置 Prometheus 指标收集
<a name="ContainerInsights-Prometheus-Setup-ECS"></a>

要从 Amazon ECS 集群收集 Prometheus 指标，您可以使用 CloudWatch 代理作为收集器或使用 AWS Distro for OpenTelemetry 收集器。有关使用 AWS Distro for OpenTelemetry 收集器的信息，请参阅 [https://aws-otel.github.io/docs/getting-started/container-insights/ecs-prometheus](https://aws-otel.github.io/docs/getting-started/container-insights/ecs-prometheus)。

下面几节介绍如何使用 CloudWatch 代理作为收集器来检索 Prometheus 指标。您可以在运行 Amazon ECS 的集群上安装带有 Prometheus 监控功能的 CloudWatch 代理，还可以选择配置该代理以抓取其他目标。这些部分还提供用于设置示例工作负载的可选教程，以使用 Prometheus 监控进行测试。

Amazon ECS 上的 Container Insights 支持 Prometheus 指标的以下启动类型和网络模式组合：


| Amazon ECS 启动类型 | 支持的网络模式 | 
| --- | --- | 
|  EC2 (Linux)  |  网桥、主机和 awsvpc  | 
|  Fargate  |  awsvpc  | 

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

**Topics**
+ [在 Amazon ECS 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理](ContainerInsights-Prometheus-install-ECS.md)
+ [抓取其他 Prometheus 源并导入这些指标](ContainerInsights-Prometheus-Setup-configure-ECS.md)
+ [（可选）为 Prometheus 指标测试设置示例容器化 Amazon ECS 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS.md)

# 在 Amazon ECS 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-install-ECS"></a>

本节介绍如何在运行 Amazon ECS 的集群中设置带有 Prometheus 监控功能的 CloudWatch 代理。执行此操作后，代理会自动抓取并导入该集群中运行的以下工作负载的指标。
+ AWS App Mesh
+ Java/JMX

您还可以将代理配置为从其他 Prometheus 工作负载和源抓取及导入指标。

## 设置 IAM 角色
<a name="ContainerInsights-Prometheus-Setup-ECS-IAM"></a>

您需要两个 IAM 角色来执行 CloudWatch 代理任务定义。如果您指定 CloudFormation 堆栈中的 **CreateIAMRoles=True** 让 Container Insights 为您创建这些角色，则将使用正确的权限创建这些角色。如果要自己创建或使用现有角色，则需要以下角色和权限。
+ **CloudWatch 代理 ECS 任务角色** – CloudWatch 代理容器使用此角色。它必须包括 **CloudWatchAgentServerPolicy** 策略以及包含以下只读权限的客户管理策略：
  + `ec2:DescribeInstances`
  + `ecs:ListTasks`
  + `ecs:ListServices`
  + `ecs:DescribeContainerInstances`
  + `ecs:DescribeServices`
  + `ecs:DescribeTasks`
  + `ecs:DescribeTaskDefinition`
+ **CloudWatch 代理 ECS 任务执行角色** – 这是 Amazon ECS 启动和执行容器所需的角色。确保您的任务执行角色附加了 **AmazonSSMReadOnlyAccess**、**AmazonECSTaskExecutionRolePolicy** 和 **CloudWatchAgentServerPolicy** 策略。如果您需要存储更敏感的数据以供 Amazon ECS 使用，请参阅[指定敏感数据](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html)以了解更多信息。

## 使用 CloudFormation 安装带有 Prometheus 监控功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-ECS-CFN"></a>

您使用 AWS CloudFormation 为 Amazon ECS 集群安装带有 Prometheus 监控功能的 CloudWatch 代理。以下列表显示了您将在 CloudFormation 模板中使用的参数。
+ **ECSClusterName** – 指定目标 Amazon ECS 集群。
+ **CreateIAMRoles** – 指定 **True** 为 Amazon ECS 任务角色和 Amazon ECS 任务执行角色创建新角色。指定 **False** 重新使用现有角色。
+ **TaskRoleName** – 如果您为 **CreateIAMRoles** 指定 **True**，这会指定用于新 Amazon ECS 任务角色的名称。如果您为 **CreateIAMRoles** 指定 **False**，这会指定要用作 Amazon ECS 任务角色的现有角色。
+ **ExecutionRoleName** – 如果您为 **CreateIAMRoles** 指定 **True**，这会指定用于新 Amazon ECS 任务执行角色的名称。如果您为 **CreateIAMRoles** 指定 **False**，这会指定要用作 Amazon ECS 任务执行角色的现有角色。
+ **ECSNetworkMode** – 如果您使用 EC2 启动类型，请在此处指定网络模式。必须是 **bridge** 或 **host**。
+ **ECSLaunchType** – 指定 **fargate** 或 **EC2**。
+ **SecurityGroupID** – 如果 **ECSNetworkMode** 是 **awsvpc**，请在此处指定安全组 ID。
+ **SubnetID** – 如果 **ECSNetworkMode** 是 **awsvpc**，请在此处指定子网 ID。

### 命令示例
<a name="ContainerInsights-Prometheus-Setup-ECS-CFNcommands"></a>

本节包含在各种情况下安装带有 Prometheus 监控功能的 Container Insights 的 CloudFormation 示例命令。

**在桥式网络模式下为 Amazon ECS 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_NETWORK_MODE=bridge
export CREATE_IAM_ROLES=True
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name

curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
    --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSNetworkMode,ParameterValue=${ECS_NETWORK_MODE} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

**在主机网络模式下为 Amazon ECS 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_NETWORK_MODE=host
export CREATE_IAM_ROLES=True
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name


curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
    --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSNetworkMode,ParameterValue=${ECS_NETWORK_MODE} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \ 
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

**在 awsvpc 网络模式下为 Amazon ECS 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_LAUNCH_TYPE=EC2
export CREATE_IAM_ROLES=True
export ECS_CLUSTER_SECURITY_GROUP=your_security_group_eg_sg-xxxxxxxxxx
export ECS_CLUSTER_SUBNET=your_subnet_eg_subnet-xxxxxxxxxx
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name

curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-${ECS_LAUNCH_TYPE}-awsvpc \
    --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSLaunchType,ParameterValue=${ECS_LAUNCH_TYPE} \
                 ParameterKey=SecurityGroupID,ParameterValue=${ECS_CLUSTER_SECURITY_GROUP} \
                 ParameterKey=SubnetID,ParameterValue=${ECS_CLUSTER_SUBNET} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

**在 awsvpc 网络模式下为 Fargate 集群创建 CloudFormation 堆栈**

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export ECS_CLUSTER_NAME=your_ec2_ecs_cluster_name
export ECS_LAUNCH_TYPE=FARGATE
export CREATE_IAM_ROLES=True
export ECS_CLUSTER_SECURITY_GROUP=your_security_group_eg_sg-xxxxxxxxxx
export ECS_CLUSTER_SUBNET=your_subnet_eg_subnet-xxxxxxxxxx
export ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
export ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name            

curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml

aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-${ECS_LAUNCH_TYPE}-awsvpc \
    --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                 ParameterKey=CreateIAMRoles,ParameterValue=${CREATE_IAM_ROLES} \
                 ParameterKey=ECSLaunchType,ParameterValue=${ECS_LAUNCH_TYPE} \
                 ParameterKey=SecurityGroupID,ParameterValue=${ECS_CLUSTER_SECURITY_GROUP} \
                 ParameterKey=SubnetID,ParameterValue=${ECS_CLUSTER_SUBNET} \
                 ParameterKey=TaskRoleName,ParameterValue=${ECS_TASK_ROLE_NAME} \
                 ParameterKey=ExecutionRoleName,ParameterValue=${ECS_EXECUTION_ROLE_NAME} \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${AWS_DEFAULT_REGION} \
    --profile ${AWS_PROFILE}
```

### CloudFormation 堆栈创建的 AWS 资源
<a name="ContainerInsights-Prometheus-Setup-ECS-resources"></a>

下表列出了 AWS 资源，该资源在 Amazon ECS 集群上使用 CloudFormation 设置 带有 Prometheus 监控功能的 Container Insights 时创建。


| 资源类型 | 资源名称 | 评论 | 
| --- | --- | --- | 
|  AWS::SSM::Parameter  |  AmazonCloudWatch-CWAgentConfig-\$1*ECS\$1CLUSTER\$1NAME*-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*  |  这是具有默认 App Mesh 和 Java/JMX 嵌入式指标格式定义的 CloudWatch 代理。  | 
|  AWS::SSM::Parameter  |  AmazonCloudWatch-PrometheusConfigName-\$1*ECS\$1CLUSTER\$1NAME*-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*  |  这是 Prometheus 抓取配置。  | 
|  AWS::IAM::Role  |  **\$1ECS\$1TASK\$1ROLE\$1NAME**。  |  Amazon ECS 任务角色。这仅在您为 `CREATE_IAM_ROLES` 指定 **True** 时创建。  | 
|  AWS::IAM::Role  |  **\$1\$1ECS\$1EXECUTION\$1ROLE\$1NAME\$1**   |  Amazon ECS 任务执行角色。这仅在您为 `CREATE_IAM_ROLES` 指定 **True** 时创建。  | 
|  AWS::ECS::TaskDefinition  |  cwagent-prometheus-\$1*ECS\$1CLUSTER\$1NAME*-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*   |   | 
|  AWS::ECS::Service  |  cwagent-prometheus-replica-service-\$1*ECS\$1LAUNCH\$1TYPE*-\$1*ECS\$1NETWORK\$1MODE*  |   | 

### 使用 Prometheus 监控功能删除 CloudWatch 代理的 CloudFormation 堆栈
<a name="ContainerInsights-Prometheus-ECS-delete"></a>

要从 Amazon ECS 集群中删除 CloudWatch 代理，请输入以下命令。

```
export AWS_PROFILE=your_aws_config_profile_eg_default
export AWS_DEFAULT_REGION=your_aws_region_eg_ap-southeast-1
export CLOUDFORMATION_STACK_NAME=your_cloudformation_stack_name

aws cloudformation delete-stack \
--stack-name ${CLOUDFORMATION_STACK_NAME} \
--region ${AWS_DEFAULT_REGION} \
--profile ${AWS_PROFILE}
```

# 抓取其他 Prometheus 源并导入这些指标
<a name="ContainerInsights-Prometheus-Setup-configure-ECS"></a>

具有 Prometheus 监控功能的 CloudWatch 代理需要两种配置来抓取 Prometheus 指标。一个用于 Prometheus 文档中 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 记录的标准 Prometheus 配置。另一种配置是 CloudWatch 代理配置文件。

对于 Amazon ECS 集群，配置通过 Amazon ECS 任务定义中的密钥与 AWS Systems Manager 的 Parameter Store 集成：
+ 密钥 `PROMETHEUS_CONFIG_CONTENT` 用于 Prometheus 抓取配置。
+ 密钥 `CW_CONFIG_CONTENT` 用于 CloudWatch 代理配置。

要抓取其他 Prometheus 指标源并将这些指标导入 CloudWatch，您需要修改 Prometheus 抓取配置和 CloudWatch 代理配置，然后使用更新的配置重新部署代理。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

## Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Setup-config-global"></a>

CloudWatch 代理支持标准的 Prometheus 抓取配置，如 Prometheus 文档中的 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 所述。您可以编辑此部分以更新此文件中已有的配置，并添加其他 Prometheus 抓取目标。默认情况下，示例配置文件包含以下全局配置行：

```
global:
  scrape_interval: 1m
  scrape_timeout: 10s
```
+ **scrape\$1interval** – 定义抓取目标的频率。
+ **scrape\$1timeout** – 定义抓取请求超时之前的等待时间。

您还可以在作业级别为这些设置定义不同的值，以覆盖全局配置。

### Prometheus 抓取任务
<a name="ContainerInsights-Prometheus-Setup-config-scrape"></a>

CloudWatch 代理 YAML 文件已配置了一些默认的抓取任务。例如，在 Amazon ECS 的 YAML 文件（例如 `cwagent-ecs-prometheus-metric-for-bridge-host.yaml`）中，默认抓取任务在 `ecs_service_discovery` 部分中配置。

```
"ecs_service_discovery": {
                  "sd_frequency": "1m",
                  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
                  "docker_label": {
                  },
                  "task_definition_list": [
                    {
                      "sd_job_name": "ecs-appmesh-colors",
                      "sd_metrics_ports": "9901",
                      "sd_task_definition_arn_pattern": ".*:task-definition\/.*-ColorTeller-(white):[0-9]+",
                      "sd_metrics_path": "/stats/prometheus"
                    },
                    {
                      "sd_job_name": "ecs-appmesh-gateway",
                      "sd_metrics_ports": "9901",
                      "sd_task_definition_arn_pattern": ".*:task-definition/.*-ColorGateway:[0-9]+",
                      "sd_metrics_path": "/stats/prometheus"
                    }
                  ]
                }
```

这些默认目标中的每个目标都会被抓取，并使用嵌入式指标格式在日志事件中将指标发送到 CloudWatch。有关更多信息，请参阅 [在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。

来自 Amazon ECS 集群的日志事件存储在 **/aws/ecs/containerinsights/*cluster\$1name*/prometheus** 日志组中。

每个抓取作业都包含在此日志组中的不同日志流中。

要添加新的抓取目标，请在 YAML 文件 `ecs_service_discovery` 部分下的 `task_definition_list` 部分中添加一个新条目，然后重新启动代理。有关此过程的示例，请参阅 [添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](ContainerInsights-Prometheus-Setup-configure.md#ContainerInsights-Prometheus-Setup-new-exporters)。

## Prometheus 的 CloudWatch 代理配置
<a name="ContainerInsights-Prometheus-Setup-cw-agent-config"></a>

CloudWatch 代理配置文件在 `metrics_collected` 下面有一个 `prometheus` 部分用于 Prometheus 抓取配置。它包含以下配置选项：
+ **cluster\$1name** – 指定要在日志事件中添加为标签的集群名称。该字段是可选的。如果省略此项，代理可以检测 Amazon ECS 集群名称。
+ **log\$1group\$1name** – 指定已抓取 Prometheus 指标的日志组名称。该字段是可选的。如果省略此项，CloudWatch 会将 **/aws/ecs/containerinsights/*cluster\$1name*/prometheus** 用于来自 Amazon ECS 集群的日志。
+ **prometheus\$1config\$1path** – 指定 Prometheus 抓取配置文件路径。如果此字段的值以 `env:` 开头，Prometheus 抓取配置文件内容将从容器的环境变量中检索。请勿更改此字段。
+ **ecs\$1service\$1discovery** – 是指定 Amazon ECS Prometheus 目标自动发现功能配置的部分。支持两种模式来发现 Prometheus 目标：根据容器的 docker 标签的发现或根据 Amazon ECS 任务定义 ARN 正则表达式的发现。您可以同时使用这两种模式，CloudWatch 代理将根据 *\$1private\$1ip\$1:\$1port\$1/\$1metrics\$1path\$1* 对发现的目标进行重复去除。

  `ecs_service_discovery` 部分包含以下字段：
  + `sd_frequency` 是发现 Prometheus 导出器的频率。指定数字和单位后缀。例如，`1m` 表示每分钟一次或 `30s` 表示每 30 秒一次。有效的单位后缀为 `ns`、`us`、`ms`、`s`、`m` 和 `h`。

    该字段是可选的。默认值为 60 秒（1 分钟）。
  + `sd_target_cluster` 是用于自动发现的目标 Amazon ECS 集群名称。该字段是可选的。默认名称为安装 CloudWatch 代理的 Amazon ECS 集群的名称。
  + `sd_cluster_region` 是目标 Amazon ECS 集群的区域。该字段是可选的。默认区域为安装 CloudWatch 代理的 Amazon ECS 集群的区域。
  + `sd_result_file` 是 Prometheus 目标结果的 YAML 文件的路径。Prometheus 抓取配置将引用此文件。
  + `docker_label` 是可选部分，您可以使用它来指定基于 docker 标签的服务发现的配置。如果省略此部分，则不会使用基于 docker 标签的发现。此部分包含以下字段：
    + `sd_port_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标的容器端口。默认值为 `ECS_PROMETHEUS_EXPORTER_PORT`。如果容器没有此 docker 标签，CloudWatch 代理将跳过它。
    + `sd_metrics_path_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标路径。默认值为 `ECS_PROMETHEUS_METRICS_PATH`。如果容器没有此 docker 标签，则代理会采用默认路径 `/metrics`。
    + `sd_job_name_label` 是容器的 docker 标签名称，用于指定 Prometheus 抓取任务名称。默认值为 `job`。如果容器没有此 docker 标签，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
  + `task_definition_list` 是可选部分，可用于指定基于任务定义的服务发现的配置。如果省略此部分，则不会使用基于任务定义的发现。此部分包含以下字段：
    + `sd_task_definition_arn_pattern` 是用于指定要发现的 Amazon ECS 任务定义的模式。这是正则表达式。
    + `sd_metrics_ports` 列出 Prometheus 指标的 containerPort。用分号分隔 containerPorts。
    + `sd_container_name_pattern` 指定 Amazon ECS 任务容器名称。这是正则表达式。
    + `sd_metrics_path` 指定 Prometheus 指标路径。如果省略此项，代理会采用默认路径 `/metrics`
    + `sd_job_name` 指定 Prometheus 抓取任务名称。如果省略此字段，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
  + `service_name_list_for_tasks` 是可选部分，可用于指定基于服务名称的发现的配置。如果省略此部分，则不会使用基于服务名称的发现。此部分包含以下字段：
    + `sd_service_name_pattern` 是用于指定要在其中发现任务的 Amazon ECS 服务的模式。这是正则表达式。
    + `sd_metrics_ports` 列出 Prometheus 指标的 `containerPort`。用分号分隔多个 `containerPorts`。
    + `sd_container_name_pattern` 指定 Amazon ECS 任务容器名称。这是正则表达式。
    + `sd_metrics_path` 指定 Prometheus 指标路径。如果省略此项，代理会采用默认路径 `/metrics`。
    + `sd_job_name` 指定 Prometheus 抓取任务名称。如果省略此字段，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
+ **metric\$1declaration** – 是指定要生成的采用嵌入式指标格式的日志数组的部分。默认情况下，CloudWatch 代理从中进行导入的每个 Prometheus 源都有 `metric_declaration` 部分。这些部分各包括以下字段：
  + `label_matcher` 是一个正则表达式，用于检查 `source_labels` 中列出的标签的值。匹配的指标将启用，以包含在发送到 CloudWatch 的嵌入式指标格式中。

    如果您在 `source_labels` 中指定了多个标签，我们建议您不要在 `label_matcher` 的正则表达式中使用 `^` 或 `$` 字符。
  + `source_labels` 指定由 `label_matcher` 行检查的标签的值。
  + `label_separator` 指定要在 ` label_matcher` 行中使用的分隔符（如果指定了多个 `source_labels`）。默认值为 `;`。您可以在以下示例中看到 `label_matcher` 行中使用的此默认值。
  + `metric_selectors` 是一个正则表达式，用于指定要收集并发送到 CloudWatch 的指标。
  + `dimensions` 是要用作每个选定指标的 CloudWatch 维度的标签列表。

请参阅以下 `metric_declaration` 示例。

```
"metric_declaration": [
  {
     "source_labels":[ "Service", "Namespace"],
     "label_matcher":"(.*node-exporter.*|.*kube-dns.*);kube-system$",
     "dimensions":[
        ["Service", "Namespace"]
     ],
     "metric_selectors":[
        "^coredns_dns_request_type_count_total$"
     ]
  }
]
```

此示例配置嵌入式指标格式部分，以便在满足以下条件时作为日志事件发送：
+ `Service` 的值包含 `node-exporter` 或 `kube-dns`。
+ `Namespace` 的值为 `kube-system`。
+ Prometheus 指标 `coredns_dns_request_type_count_total` 同时包含 `Service` 和 `Namespace` 标签。

发送的日志事件包括以下突出显示的部分：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"coredns_dns_request_type_count_total"
            }
         ],
         "Dimensions":[
            [
               "Namespace",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "Namespace":"kube-system",
   "Service":"kube-dns",
   "coredns_dns_request_type_count_total":2562,
   "eks_amazonaws_com_component":"kube-dns",
   "instance":"192.168.61.254:9153",
   "job":"kubernetes-service-endpoints",
   ...
}
```

# Amazon ECS 集群上自动发现的详细指南
<a name="ContainerInsights-Prometheus-Setup-autodiscovery-ecs"></a>

Prometheus 提供了数十种动态服务发现机制，如 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 中所述。但是，Amazon ECS 没有内置服务发现。CloudWatch 代理添加了此机制。

启用 Amazon ECS Prometheus 服务发现后，CloudWatch 代理会定期对 Amazon ECS 和 Amazon EC2 前端进行以下 API 调用，以检索目标 ECS 集群中正在运行的 ECS 任务的元数据。

```
EC2:DescribeInstances
ECS:ListTasks
ECS:ListServices
ECS:DescribeContainerInstances
ECS:DescribeServices
ECS:DescribeTasks
ECS:DescribeTaskDefinition
```

CloudWatch 代理使用元数据来扫描 ECS 集群内的 Prometheus 目标。CloudWatch 代理支持三种服务发现模式：
+ 基于容器 docker 标签的服务发现
+ 基于 ECS 任务定义 ARN 正则表达式的服务发现
+ 基于 ECS 服务名称正则表达式的服务发现

所有模式均可同时使用。CloudWatch 代理会根据 `{private_ip}:{port}/{metrics_path}` 对发现的目标进行重复去除。

所有发现的目标均写入由 CloudWatch 代理容器内的 `sd_result_file` 配置字段指定的结果文件。以下为示例结果文件：

```
- targets:
  - 10.6.1.95:32785
  labels:
    __metrics_path__: /metrics
    ECS_PROMETHEUS_EXPORTER_PORT: "9406"
    ECS_PROMETHEUS_JOB_NAME: demo-jar-ec2-bridge-dynamic
    ECS_PROMETHEUS_METRICS_PATH: /metrics
    InstanceType: t3.medium
    LaunchType: EC2
    SubnetId: subnet-123456789012
    TaskDefinitionFamily: demo-jar-ec2-bridge-dynamic-port
    TaskGroup: family:demo-jar-ec2-bridge-dynamic-port
    TaskRevision: "7"
    VpcId: vpc-01234567890
    container_name: demo-jar-ec2-bridge-dynamic-port
    job: demo-jar-ec2-bridge-dynamic
- targets:
  - 10.6.3.193:9404
  labels:
    __metrics_path__: /metrics
    ECS_PROMETHEUS_EXPORTER_PORT_SUBSET_B: "9404"
    ECS_PROMETHEUS_JOB_NAME: demo-tomcat-ec2-bridge-mapped-port
    ECS_PROMETHEUS_METRICS_PATH: /metrics
    InstanceType: t3.medium
    LaunchType: EC2
    SubnetId: subnet-123456789012
    TaskDefinitionFamily: demo-tomcat-ec2-bridge-mapped-port
    TaskGroup: family:demo-jar-tomcat-bridge-mapped-port
    TaskRevision: "12"
    VpcId: vpc-01234567890
    container_name: demo-tomcat-ec2-bridge-mapped-port
    job: demo-tomcat-ec2-bridge-mapped-port
```

您可以直接将此结果文件与基于 Prometheus 文件的服务发现集成。有关基于 Prometheus 文件的服务发现的更多信息，请参阅 [<file\$1sd\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#file_sd_config)。

 假设将结果文件写入 `/tmp/cwagent_ecs_auto_sd.yaml`。以下 Prometheus 抓取配置将使用它。

```
global:
  scrape_interval: 1m
  scrape_timeout: 10s
scrape_configs:
  - job_name: cwagent-ecs-file-sd-config
    sample_limit: 10000
    file_sd_configs:
      - files: [ "/tmp/cwagent_ecs_auto_sd.yaml" ]
```

CloudWatch 代理还会为发现的目标添加以下附加标签。
+ `container_name`
+ `TaskDefinitionFamily`
+ `TaskRevision`
+ `TaskGroup`
+ `StartedBy`
+ `LaunchType`
+ `job`
+ `__metrics_path__`
+ Docker 标签

当集群具有 EC2 启动类型时，会添加以下三个标签。
+ `InstanceType`
+ `VpcId`
+ `SubnetId`

**注意**  
与正则表达式 `[a-zA-Z_][a-zA-Z0-9_]*` 不匹配的 Docker 标签将被筛选掉。这与 Prometheus 文档中[配置文件](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#labelname)的 `label_name` 中列出的 Prometheus 惯例相匹配。

## ECS 服务发现配置示例
<a name="ContainerInsights-Prometheus-Setup-autodiscovery-ecs-examples"></a>

本节包括演示 ECS 服务发现的示例。

**示例 1**

```
"ecs_service_discovery": {
  "sd_frequency": "1m",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "docker_label": {
  }
}
```

此示例启用基于 docker 标签的服务发现。CloudWatch 代理将每分钟查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

`docker_label` 部分中 `sd_port_label` 的默认值为 `ECS_PROMETHEUS_EXPORTER_PORT`。如果 ECS 任务中任何正在运行的容器具有 `ECS_PROMETHEUS_EXPORTER_PORT` docker 标签，CloudWatch 代理将其值作为 `container port` 来扫描容器的所有公开端口。如果匹配，则使用映射的主机端口和容器的私有 IP，以 `private_ip:host_port` 格式来构建 Prometheus 导出器目标。

`docker_label` 部分中 `sd_metrics_path_label` 的默认值为 `ECS_PROMETHEUS_METRICS_PATH`。如果容器具有此 docker 标签，则其值将用作 `__metrics_path__`。如果容器没有此标签，则使用默认值 `/metrics`。

`docker_label` 部分中 `sd_job_name_label` 的默认值为 `job`。如果容器具有此 docker 标签，则其值将作为一个目标标签附加，以替换 Prometheus 配置中指定的默认任务名称。此 docker 标签的值用作 CloudWatch Logs 日志组中的日志流名称。

**示例 2**

```
"ecs_service_discovery": {
  "sd_frequency": "15s",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "docker_label": {
    "sd_port_label": "ECS_PROMETHEUS_EXPORTER_PORT_SUBSET_A",
    "sd_job_name_label": "ECS_PROMETHEUS_JOB_NAME"  
  }
}
```

此示例启用基于 docker 标签的服务发现。CloudWatch 代理将每 15 秒查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。带有 `ECS_PROMETHEUS_EXPORTER_PORT_SUBSET_A` 的 docker 标签的容器将被扫描。docker 标签 `ECS_PROMETHEUS_JOB_NAME` 的值用作任务名称。

**示例 3**

```
"ecs_service_discovery": {
  "sd_frequency": "5m",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "task_definition_list": [
    {
      "sd_job_name": "java-prometheus",
      "sd_metrics_path": "/metrics",
      "sd_metrics_ports": "9404; 9406",
      "sd_task_definition_arn_pattern": ".*:task-definition/.*javajmx.*:[0-9]+"
    },
    {
      "sd_job_name": "envoy-prometheus",
      "sd_metrics_path": "/stats/prometheus",
      "sd_container_name_pattern": "^envoy$", 
      "sd_metrics_ports": "9901",
      "sd_task_definition_arn_pattern": ".*:task-definition/.*appmesh.*:23"
    }
  ]
}
```

此示例启用基于 ECS 任务定义 ARN 正则表达式的服务发现。CloudWatch 代理将每五分钟查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

定义了两个任务定义 ARN 正则表达式部分：
+  对于第一部分，过滤 ECS 任务定义 ARN 中的 ECS 任务以及 `javajmx`，以进行容器端口扫描。如果这些 ECS 任务中的容器在 9404 或 9406 上公开容器端口，则映射的主机端口和容器的私有 IP 会用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/metrics`。因此 CloudWatch 代理将从 `private_ip:host_port/metrics` 中抓取 Prometheus 指标，抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中 CloudWatch Logs 中的 `java-prometheus` 日志流。
+  对于第二部分，过滤 ECS 任务定义 ARN 中带有 `appmesh` 的 ECS 任务以及 `:23` 的 `version`，以进行容器端口扫描。对于在 `9901` 上公开容器端口的、名称为 `envoy` 的容器，映射的主机端口以及容器的私有 IP 用于创建 Prometheus 导出器目标。这些 ECS 任务中的值会公开 9404 或 9406 上的容器端口，映射的主机端口以及容器的私有 IP 用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/stats/prometheus`。因此，CloudWatch 代理将从 `private_ip:host_port/stats/prometheus` 中抓取 Prometheus 指标，并将抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中的 CloudWatch Logs 中的 `envoy-prometheus` 日志流。

**示例 4**。

```
"ecs_service_discovery": {
  "sd_frequency": "5m",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "service_name_list_for_tasks": [
    {
      "sd_job_name": "nginx-prometheus",
      "sd_metrics_path": "/metrics",
      "sd_metrics_ports": "9113",
      "sd_service_name_pattern": "^nginx-.*"
    },
    {
      "sd_job_name": "haproxy-prometheus",
      "sd_metrics_path": "/stats/metrics",
      "sd_container_name_pattern": "^haproxy$",
      "sd_metrics_ports": "8404",
      "sd_service_name_pattern": ".*haproxy-service.*"
    }
  ]
}
```

本示例启用基于 ECS 服务名称正则表达式的服务发现。CloudWatch 代理将每五分钟查询一次 ECS 服务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

定义了两个服务名称正则表达式部分：
+  对于第一部分，过滤与 ECS 服务关联的 ECS 任务（名称与正则表达式 `^nginx-.*` 相匹配），以进行容器端口扫描。如果这些 ECS 任务中的容器在 9113 上公开容器端口，则映射的主机端口和容器的私有 IP 将用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/metrics`。因此，CloudWatch 代理将从 `private_ip:host_port/metrics` 中抓取 Prometheus 指标，并将抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中 CloudWatch Logs 中的 `nginx-prometheus` 日志流。
+  或第二部分，过滤与 ECS 服务关联的 ECS 任务（名称与正则表达式 `.*haproxy-service.*` 匹配），以进行容器端口扫描。对于在 8404 上公开容器端口、名称为 `haproxy` 的容器，映射的主机端口以及容器的私有 IP 用于创建 Prometheus 导出器目标。`sd_metrics_path` 的值将 `__metrics_path__` 设置为 `/stats/metrics`。因此，CloudWatch 代理将从 `private_ip:host_port/stats/metrics` 中抓取 Prometheus 指标，并将抓取的指标发送到日志组 `/aws/ecs/containerinsights/cluster_name/prometheus` 中 CloudWatch Logs 中的 `haproxy-prometheus` 日志流。

**示例 5**

```
"ecs_service_discovery": {
  "sd_frequency": "1m30s",
  "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
  "docker_label": {
    "sd_port_label": "MY_PROMETHEUS_EXPORTER_PORT_LABEL",
    "sd_metrics_path_label": "MY_PROMETHEUS_METRICS_PATH_LABEL",
    "sd_job_name_label": "MY_PROMETHEUS_METRICS_NAME_LABEL"  
  }
  "task_definition_list": [
    {
      "sd_metrics_ports": "9150",
      "sd_task_definition_arn_pattern": "*memcached.*"
    }
  ]
}
```

本示例启用了两种 ECS 服务发现模式。CloudWatch 代理将每 90 秒查询一次 ECS 任务的元数据，并将发现的目标写入 CloudWatch 代理容器内的 `/tmp/cwagent_ecs_auto_sd.yaml` 文件中。

对于基于 docker 的服务发现配置：
+ 过滤带有 docker 标签 `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的 ECS 任务，以进行 Prometheus 端口扫描。目标 Prometheus 容器端口由 label `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的值指定。
+ docker 标签 `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的值用于 `__metrics_path__`。如果容器没有此 docker 标签，则使用默认值 `/metrics`。
+ docker 标签 `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 的值用作任务标签。如果容器没有此 docker 标签，则使用 Prometheus 配置中定义的任务名称。

对于基于 ECS 任务定义 ARN 正则表达式的服务发现配置：
+ 过滤 ECS 任务定义 ARN 中带 `memcached` 的 ECS 任务，以进行容器端口扫描。根据 `sd_metrics_ports` 定义，目标 Prometheus 容器端口是 9150。使用默认指标路径 `/metrics`。使用 Prometheus 配置中定义的任务名称。

# （可选）为 Prometheus 指标测试设置示例容器化 Amazon ECS 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS"></a>

要测试 CloudWatch Container Insights 中的 Prometheus 指标支持，您可设置以下一个或多个容器化工作负载。具有 Prometheus 支持的 CloudWatch 代理会自动从这些工作负载中的每一个收集指标。要查看默认情况下收集的指标，请参阅 [CloudWatch 代理收集的 Prometheus 指标](ContainerInsights-Prometheus-metrics.md)。

**Topics**
+ [Amazon ECS 集群的示例 App Mesh 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS-appmesh.md)
+ [Amazon ECS 集群的示例 Java/JMX 工作负载](ContainerInsights-Prometheus-Sample-Workloads-ECS-javajmx.md)
+ [Amazon ECS 集群的示例 NGINX 工作负载](ContainerInsights-Prometheus-Setup-nginx-ecs.md)
+ [Amazon ECS 集群的示例 NGINX Plus 工作负载](ContainerInsights-Prometheus-Setup-nginx-plus-ecs.md)
+ [添加新 Prometheus 抓取目标的教程：Amazon ECS 上的 Memcached](ContainerInsights-Prometheus-Setup-memcached-ecs.md)
+ [在 Amazon ECS Fargate 上抓取 Redis OSS Prometheus 指标的教程](ContainerInsights-Prometheus-Setup-redis-ecs.md)

# Amazon ECS 集群的示例 App Mesh 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS-appmesh"></a>

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

首先，按照本[演练](https://github.com/aws/aws-app-mesh-examples/tree/main/examples/apps/colorapp#app-mesh-walkthrough-deploy-the-color-app-on-ecs)在 Amazon ECS 集群上部署示例颜色应用程序。完成后，您将在端口 9901 上公开 App Mesh Prometheus 指标。

接下来，按照以下步骤在安装颜色应用程序的同一 Amazon ECS 集群上，安装带有 Prometheus 监控功能的 CloudWatch 代理。本节中的步骤以桥式网络模式安装 CloudWatch 代理。

您在演练中设置的环境变量 `ENVIRONMENT_NAME`、`AWS_PROFILE` 和 `AWS_DEFAULT_REGION`也将在以下步骤中使用。

**安装带有 Prometheus 监控功能的 CloudWatch 代理以进行测试**

1. 通过输入以下命令，下载 CloudFormation 模板。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml
   ```

1. 通过输入以下命令，设置网络模式。

   ```
   export ECS_CLUSTER_NAME=${ENVIRONMENT_NAME}
   export ECS_NETWORK_MODE=bridge
   ```

1. 输入以下命令以创建 CloudFormation 堆栈。

   ```
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=${ECS_CLUSTER_NAME} \
                    ParameterKey=CreateIAMRoles,ParameterValue=True \
                    ParameterKey=ECSNetworkMode,ParameterValue=${ECS_NETWORK_MODE} \
                    ParameterKey=TaskRoleName,ParameterValue=CWAgent-Prometheus-TaskRole-${ECS_CLUSTER_NAME} \
                    ParameterKey=ExecutionRoleName,ParameterValue=CWAgent-Prometheus-ExecutionRole-${ECS_CLUSTER_NAME} \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION} \
       --profile ${AWS_PROFILE}
   ```

1. （可选）创建 CloudFormation 堆栈后，您会看到 `CREATE_COMPLETE` 消息。如果要在看到该消息之前检查状态，请输入以下命令。

   ```
   aws cloudformation describe-stacks \
   --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
   --query 'Stacks[0].StackStatus' \
   --region ${AWS_DEFAULT_REGION} \
   --profile ${AWS_PROFILE}
   ```

**故障排查**

演练中的步骤使用 jq 来分析 AWS CLI 的输出结果。有关安装 jq 代理的更多信息，请参阅 [ jq](https://stedolan.github.io/jq/)。使用以下命令将 AWS CLI 的默认输出格式设置为 JSON，以便 jq 可以对其进行正确分析。

```
$ aws configure
```

当响应变为 `Default output format` 时，输入 **json**。

## 使用 Prometheus 监控功能卸载 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS-appmesh-uninstall"></a>

完成测试后，输入以下命令以通过 CloudFormation 删除堆栈来卸载 CloudWatch 代理。

```
aws cloudformation delete-stack \
--stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
--region ${AWS_DEFAULT_REGION} \
--profile ${AWS_PROFILE}
```

# Amazon ECS 集群的示例 Java/JMX 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-ECS-javajmx"></a>

JMX Exporter 是 Prometheus 的官方导出程序，可以将 JMX MBeans 作为 Prometheus 指标进行抓取和公开。有关详细信息，请参阅 [prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter)。

支持 Prometheus 的 CloudWatch 代理根据 Amazon ECS 集群中的服务发现配置抓取 Java/JMX Prometheus 指标。您可以将 JMX Exporter 配置为在不同端口或 metrics\$1path 上公开指标。如果您更改了端口或路径，请更新 CloudWatch 代理配置中的默认 `ecs_service_discovery` 部分。

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

**为 Amazon ECS 集群安装 Java/JMX 示例工作负载**

1. 按照这些部分中的步骤创建 Docker 镜像。
   + [示例：具有 Prometheus 指标的 Java Jar 应用程序 Docker 镜像](ContainerInsights-Prometheus-Sample-Workloads-javajmx.md#ContainerInsights-Prometheus-Sample-Workloads-javajmx-jar)
   + [示例：具有 Prometheus 指标的 Apache Tomcat Docker 镜像](ContainerInsights-Prometheus-Sample-Workloads-javajmx.md#ContainerInsights-Prometheus-Sample-Workloads-javajmx-tomcat)

1. 在 Amazon ECS 任务定义文件中指定以下两个 docker 标签。然后，您可以将任务定义作为集群中的 Amazon ECS 服务或 Amazon ECS 任务运行。
   + 将 `ECS_PROMETHEUS_EXPORTER_PORT` 设置为指向公开 Prometheus 指标的 containerPort。
   + 将 `Java_EMF_Metrics` 设置为 `true`。CloudWatch 代理使用此标志在日志事件中生成嵌入的指标格式。

   以下是示例：

   ```
   {
     "family": "workload-java-ec2-bridge",
     "taskRoleArn": "{{task-role-arn}}",
     "executionRoleArn": "{{execution-role-arn}}",
     "networkMode": "bridge",
     "containerDefinitions": [
       {
         "name": "tomcat-prometheus-workload-java-ec2-bridge-dynamic-port",
         "image": "your_docker_image_tag_for_tomcat_with_prometheus_metrics",
         "portMappings": [
           {
             "hostPort": 0,
             "protocol": "tcp",
             "containerPort": 9404
           }
         ],
         "dockerLabels": {
           "ECS_PROMETHEUS_EXPORTER_PORT": "9404",
           "Java_EMF_Metrics": "true"
         }
       }
     ],
     "requiresCompatibilities": [
       "EC2"  ],
     "cpu": "256",
     "memory": "512"
     }
   ```

CloudFormation 模板中 CloudWatch 代理的默认设置同时启用基于 docker 标签的服务发现和基于任务定义 ARN 的服务发现。要查看这些默认设置，请参阅 [CloudWatch 代理 YAML 配置文件](https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml#L65)的第 65 行。带有 `ECS_PROMETHEUS_EXPORTER_PORT` 标签的容器将根据 Prometheus 抓取的指定容器端口自动发现。

CloudWatch 代理的默认设置在同一文件的第 112 行也有 Java/JMX `metric_declaration` 设置。目标容器的所有 docker 标签将作为附加标签添加到 Prometheus 指标中并发送到 CloudWatch Logs。对于带有 docker 标签 `Java_EMF_Metrics=“true”` 的 Java/JMX 容器，将生成嵌入式指标格式。

# Amazon ECS 集群的示例 NGINX 工作负载
<a name="ContainerInsights-Prometheus-Setup-nginx-ecs"></a>

NGINX Prometheus 导出器可以抓取和公开 NGINX 数据作为 Prometheus 指标。此示例将导出器与适用于 Amazon ECS 的 NGINX 反向代理服务结合使用。

有关 NGINX Prometheus 导出器的更多信息，请参阅 Github 上的 [nginx-prometheus-exporter](https://github.com/nginxinc/nginx-prometheus-exporter)。有关 NGINX 反向代理的更多信息，请参阅 Github 上的 [ecs-nginx-reverse-proxy](https://github.com/awslabs/ecs-nginx-reverse-proxy)。

支持 Prometheus 的 CloudWatch 代理根据 Amazon ECS 集群中的服务发现配置抓取 NGINX Prometheus 指标。您可以将 NGINX Prometheus Exporter 配置为在不同端口或路径上公开指标。如果您更改端口或路径，请更新 CloudWatch 代理配置文件中的 `ecs_service_discovery` 部分。

## 为 Amazon ECS 集群安装 NGINX 反向代理示例工作负载
<a name="ContainerInsights-Prometheus-nginx-ecs-setup"></a>

按照以下步骤安装 NGINX 反向代理示例工作负载。

### 创建 Docker 镜像
<a name="ContainerInsights-Prometheus-nginx-ecs-setup-docker"></a>

**为 NGINX 反向代理示例工作负载创建 Docker 镜像**

1. 从 NGINX 反向代理存储库下载以下文件夹：[https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/)。

1. 查找 `app` 目录并从该目录构建镜像：

   ```
   docker build -t web-server-app ./path-to-app-directory
   ```

1. 为 NGINX 构建自定义镜像。首先，创建一个包含以下两个文件的目录：
   + 示例 Dockerfile：

     ```
     FROM nginx
     COPY nginx.conf /etc/nginx/nginx.conf
     ```
   + 一个 `nginx.conf` 文件，修改自 [https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/)：

     ```
     events {
       worker_connections 768;
     }
     
     http {
       # Nginx will handle gzip compression of responses from the app server
       gzip on;
       gzip_proxied any;
       gzip_types text/plain application/json;
       gzip_min_length 1000;
     
       server{
         listen 8080;
         location /stub_status {
             stub_status   on;
         }
       }
     
       server {
         listen 80;
     
         # Nginx will reject anything not matching /api
         location /api {
           # Reject requests with unsupported HTTP method
           if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE)$) {
             return 405;
           }
     
           # Only requests matching the whitelist expectations will
           # get sent to the application server
           proxy_pass http://app:3000;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection 'upgrade';
           proxy_set_header Host $host;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_cache_bypass $http_upgrade;
         }
       }
     }
     ```
**注意**  
`stub_status` 必须在将 `nginx-prometheus-exporter` 配置为从中抓取指标的同一端口上启用。在我们的示例任务定义中，将 `nginx-prometheus-exporter` 配置为从端口 8080 抓取指标。

1. 从新目录中的文件构建镜像：

   ```
   docker build -t nginx-reverse-proxy ./path-to-your-directory
   ```

1. 将新镜像上传到镜像存储库以供日后使用。

### 创建任务定义以在 Amazon ECS 中运行 NGINX 和 web 服务器应用程序
<a name="ContainerInsights-Prometheus-nginx-ecs-setup-task"></a>

接下来，设置任务定义。

此任务定义启用 NGINX Prometheus 指标的收集和导出。NGINX 容器跟踪来自应用程序的输入，并将该数据公开到端口 8080，如 `nginx.conf` 中所设置。NGINX prometheus 导出器容器抓取这些指标，并将其发布到端口 9113，以在 CloudWatch 中使用。

**为 NGINX 示例 Amazon ECS 工作负载设置任务定义**

1. 使用以下内容创建任务定义 JSON 文件。将 *your-customized-nginx-iamge* 替换为您自定义的 NGINX 镜像的镜像 URI，并将 *your-web-server-app-image* 替换为您 web 服务器应用程序镜像的镜像 URI。

   ```
   {
     "containerDefinitions": [
       {
         "name": "nginx",
         "image": "your-customized-nginx-image",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "portMappings": [
           {
             "containerPort": 80,
             "protocol": "tcp"
           }
         ],
         "links": [
           "app"
         ]
       },
       {
         "name": "app",
         "image": "your-web-server-app-image",
         "memory": 256,
         "cpu": 256,
         "essential": true
       },
       {
         "name": "nginx-prometheus-exporter",
         "image": "docker.io/nginx/nginx-prometheus-exporter:0.8.0",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "command": [
           "-nginx.scrape-uri",
           "http://nginx:8080/stub_status"
       ],
       "links":[
         "nginx"
       ],
         "portMappings":[
           {
             "containerPort": 9113,
             "protocol": "tcp"
           }
         ]
       }
     ],
     "networkMode": "bridge",
     "placementConstraints": [],
     "family": "nginx-sample-stack"
   }
   ```

1. 使用以下命令注册任务定义。

   ```
   aws ecs register-task-definition --cli-input-json file://path-to-your-task-definition-json
   ```

1. 通过输入以下命令创建服务以运行任务：

   确保不要更改服务名称。我们将使用配置来运行 CloudWatch 代理服务，该配置使用启动它们的服务的名称模式来搜索任务。例如，要让 CloudWatch 代理查找此命令启动的任务，您可以将 `sd_service_name_pattern` 的值指定为 `^nginx-service$`。下一部分将提供更多详细信息。

   ```
   aws ecs create-service \
    --cluster your-cluster-name \
    --service-name nginx-service \
    --task-definition nginx-sample-stack:1 \
    --desired-count 1
   ```

### 配置 CloudWatch 代理以抓取 NGINX Prometheus 指标
<a name="ContainerInsights-Prometheus-nginx-ecs-setup-agent"></a>

最后一步是配置 CloudWatch 代理以抓取 NGINX 指标。在此示例中，CloudWatch 代理通过服务名称模式和端口 9113 发现任务，导出器在该端口公开 NGINX 的 prometheus 指标。发现任务且指标可用后，CloudWatch 代理开始将收集的指标发布到日志流 **nginx-prometheus-exporter**。

**配置 CloudWatch 代理以抓取 NGINX 指标**

1. 通过输入以下命令，下载必要 YAML 文件的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml
   ```

1. 使用文本编辑器打开文件，然后在 `resource:CWAgentConfigSSMParameter` 部分的 `value` 密钥中查找完整的 CloudWatch 代理配置。然后，在 `ecs_service_discovery` 部分中，添加以下 `service_name_list_for_tasks` 部分。

   ```
   "service_name_list_for_tasks": [
     {
       "sd_job_name": "nginx-prometheus-exporter",
       "sd_metrics_path": "/metrics",
       "sd_metrics_ports": "9113",
       "sd_service_name_pattern": "^nginx-service$"
      }
   ],
   ```

1. 在同一文件中，在 `metric_declaration` 部分中添加以下部分以允许 NGINX 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["job"],
     "label_matcher": ".*nginx.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName"]],
     "metric_selectors": [
       "^nginx_.*$"
     ]
   },
   ```

1. 如果您尚未在此集群中部署 CloudWatch 代理，请跳至步骤 8。

   如果您已经使用 AWS CloudFormation 将 CloudWatch 代理部署在 Amazon ECS 集群中，您可以通过输入以下命令来创建更改集：

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION \
       --change-set-name nginx-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 **nginx-scraping-support**。您会看到一项应用于 **CWAgentConfigSSMParameter** 资源的更改。通过输入以下命令，运行变更集并重新启动 CloudWatch 代理任务：

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 如果您是首次在集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令。

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

## 查看您的 NGINX 指标和日志
<a name="ContainerInsights-Prometheus-Setup-nginx-view"></a>

您现在可以查看正在收集的 NGINX 指标。

**查看示例 NGINX 工作负载的指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在运行集群的区域中，选择左侧导航窗格中的 **Metrics（指标）**。查找 **ContainerInsights/Prometheus** 命名空间以查看指标。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。这些事件位于日志流 *nginx-prometheus-exporter* 中的日志组 **/aws/containerinsights/*your\$1cluster\$1name*/prometheus** 中。

# Amazon ECS 集群的示例 NGINX Plus 工作负载
<a name="ContainerInsights-Prometheus-Setup-nginx-plus-ecs"></a>

NGINX Plus 是 NGINX 的商业版本。您必须拥有许可证方可使用它。有关更多信息，请参阅 [NGINX Plus](https://www.nginx.com/products/nginx/)

NGINX Prometheus 导出器可以抓取和公开 NGINX 数据作为 Prometheus 指标。此示例将导出器与适用于 Amazon ECS 的 NGINX Plus 反向代理服务结合使用。

有关 NGINX Prometheus 导出器的更多信息，请参阅 Github 上的 [nginx-prometheus-exporter](https://github.com/nginxinc/nginx-prometheus-exporter)。有关 NGINX 反向代理的更多信息，请参阅 Github 上的 [ecs-nginx-reverse-proxy](https://github.com/awslabs/ecs-nginx-reverse-proxy)。

支持 Prometheus 的 CloudWatch 代理根据 Amazon ECS 集群中的服务发现配置抓取 NGINX Plus Prometheus 指标。您可以将 NGINX Prometheus Exporter 配置为在不同端口或路径上公开指标。如果您更改端口或路径，请更新 CloudWatch 代理配置文件中的 `ecs_service_discovery` 部分。

## 为 Amazon ECS 集群安装 NGINX Plus 反向代理示例工作负载
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup"></a>

按照以下步骤安装 NGINX 反向代理示例工作负载。

### 创建 Docker 镜像
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup-docker"></a>

**为 NGINX Plus 反向代理示例工作负载创建 Docker 镜像**

1. 从 NGINX 反向代理存储库下载以下文件夹：[https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/)。

1. 查找 `app` 目录并从该目录构建镜像：

   ```
   docker build -t web-server-app ./path-to-app-directory
   ```

1. 为 NGINX Plus 构建自定义镜像。在为 NGINX Plus 构建镜像之前，您需要为您的 NGINX Plus 许可获取名为 `nginx-repo.key` 的密钥和 SSL 证书 `nginx-repo.crt`。创建目录并将您的 `nginx-repo.key` 和 `nginx-repo.crt` 文件存储在其中。

   在刚刚创建的目录中，创建以下两个文件：
   + 使用以下内容创建示例 Dockerfile。此 docker 文件取自 [https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-docker/\$1docker\$1plus\$1image](https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-docker/#docker_plus_image) 上提供的示例文件。我们所做的重要更改是我们加载了一个名为 `nginx.conf` 的单独文件，该文件将在下一步中创建。

     ```
     FROM debian:buster-slim
     
     LABEL maintainer="NGINX Docker Maintainers <docker-maint@nginx.com>“
     
     # Define NGINX versions for NGINX Plus and NGINX Plus modules
     # Uncomment this block and the versioned nginxPackages block in the main RUN
     # instruction to install a specific release
     # ENV NGINX_VERSION 21
     # ENV NJS_VERSION 0.3.9
     # ENV PKG_RELEASE 1~buster
     
     # Download certificate and key from the customer portal (https://cs.nginx.com (https://cs.nginx.com/))
     # and copy to the build context
     COPY nginx-repo.crt /etc/ssl/nginx/
     COPY nginx-repo.key /etc/ssl/nginx/
     # COPY nginx.conf /etc/ssl/nginx/nginx.conf
     
     RUN set -x \
     # Create nginx user/group first, to be consistent throughout Docker variants
     && addgroup --system --gid 101 nginx \
     && adduser --system --disabled-login --ingroup nginx --no-create-home --home /nonexistent --gecos "nginx user" --shell /bin/false --uid 101 nginx \
     && apt-get update \
     && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates gnupg1 \
     && \
     NGINX_GPGKEY=573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62; \
     found=''; \
     for server in \
     ha.pool.sks-keyservers.net (http://ha.pool.sks-keyservers.net/) \
     hkp://keyserver.ubuntu.com:80 \
     hkp://p80.pool.sks-keyservers.net:80 \
     pgp.mit.edu (http://pgp.mit.edu/) \
     ; do \
     echo "Fetching GPG key $NGINX_GPGKEY from $server"; \
     apt-key adv --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$NGINX_GPGKEY" && found=yes && break; \
     done; \
     test -z "$found" && echo >&2 "error: failed to fetch GPG key $NGINX_GPGKEY" && exit 1; \
     apt-get remove --purge --auto-remove -y gnupg1 && rm -rf /var/lib/apt/lists/* \
     # Install the latest release of NGINX Plus and/or NGINX Plus modules
     # Uncomment individual modules if necessary
     # Use versioned packages over defaults to specify a release
     && nginxPackages=" \
     nginx-plus \
     # nginx-plus=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-xslt \
     # nginx-plus-module-xslt=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-geoip \
     # nginx-plus-module-geoip=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-image-filter \
     # nginx-plus-module-image-filter=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-perl \
     # nginx-plus-module-perl=${NGINX_VERSION}-${PKG_RELEASE} \
     # nginx-plus-module-njs \
     # nginx-plus-module-njs=${NGINX_VERSION}+${NJS_VERSION}-${PKG_RELEASE} \
     " \
     && echo "Acquire::https::plus-pkgs.nginx.com::Verify-Peer \"true\";" >> /etc/apt/apt.conf.d/90nginx \
     && echo "Acquire::https::plus-pkgs.nginx.com::Verify-Host \"true\";" >> /etc/apt/apt.conf.d/90nginx \
     && echo "Acquire::https::plus-pkgs.nginx.com::SslCert \"/etc/ssl/nginx/nginx-repo.crt\";" >> /etc/apt/apt.conf.d/90nginx \
     && echo "Acquire::https::plus-pkgs.nginx.com::SslKey \"/etc/ssl/nginx/nginx-repo.key\";" >> /etc/apt/apt.conf.d/90nginx \
     && printf "deb https://plus-pkgs.nginx.com/debian buster nginx-plus\n" > /etc/apt/sources.list.d/nginx-plus.list \
     && apt-get update \
     && apt-get install --no-install-recommends --no-install-suggests -y \
     $nginxPackages \
     gettext-base \
     curl \
     && apt-get remove --purge --auto-remove -y && rm -rf /var/lib/apt/lists/* /etc/apt/sources.list.d/nginx-plus.list \
     && rm -rf /etc/apt/apt.conf.d/90nginx /etc/ssl/nginx
     
     # Forward request logs to Docker log collector
     RUN ln -sf /dev/stdout /var/log/nginx/access.log \
     && ln -sf /dev/stderr /var/log/nginx/error.log
     
     COPY nginx.conf /etc/nginx/nginx.conf
     
     EXPOSE 80
     
     STOPSIGNAL SIGTERM
     
     CMD ["nginx", "-g", "daemon off;"]
     ```
   + 一个修改自 [ https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/nginx](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/nginx) 的 `nginx.conf` 文件。

     ```
     events {
       worker_connections 768;
     }
     
     http {
       # Nginx will handle gzip compression of responses from the app server
       gzip on;
       gzip_proxied any;
       gzip_types text/plain application/json;
       gzip_min_length 1000;
     
       upstream backend {
         zone name 10m;
         server app:3000    weight=2;
         server app2:3000    weight=1;
       }
     
       server{
         listen 8080;
         location /api {
           api write=on;
         }
       }
     
       match server_ok {
         status 100-599;
       }
     
       server {
         listen 80;
         status_zone zone;
         # Nginx will reject anything not matching /api
         location /api {
           # Reject requests with unsupported HTTP method
           if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE)$) {
             return 405;
           }
     
           # Only requests matching the whitelist expectations will
           # get sent to the application server
           proxy_pass http://backend;
           health_check uri=/lorem-ipsum match=server_ok;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection 'upgrade';
           proxy_set_header Host $host;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_cache_bypass $http_upgrade;
         }
       }
     }
     ```

1. 从新目录中的文件构建镜像：

   ```
   docker build -t nginx-plus-reverse-proxy ./path-to-your-directory
   ```

1. 将新镜像上传到镜像存储库以供日后使用。

### 创建任务定义以在 Amazon ECS 中运行 NGINX Plus 和 web 服务器应用程序
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup-task"></a>

接下来，设置任务定义。

此任务定义启用 NGINX Plus Prometheus 指标的收集和导出。NGINX 容器跟踪来自应用程序的输入，并将该数据公开到端口 8080，如 `nginx.conf` 中所设置。NGINX prometheus 导出器容器抓取这些指标，并将其发布到端口 9113，以在 CloudWatch 中使用。

**为 NGINX 示例 Amazon ECS 工作负载设置任务定义**

1. 使用以下内容创建任务定义 JSON 文件。将 *your-customized-nginx-plus-image* 替换为自定义 NGINX Plus 镜像的镜像 URI，并将 *your-web-server-app-image* 替换为 Web 服务器应用程序镜像的镜像 URI。

   ```
   {
     "containerDefinitions": [
       {
         "name": "nginx",
         "image": "your-customized-nginx-plus-image",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "portMappings": [
           {
             "containerPort": 80,
             "protocol": "tcp"
           }
         ],
         "links": [
           "app",
           "app2"
         ]
       },
       {
         "name": "app",
         "image": "your-web-server-app-image",
         "memory": 256,
         "cpu": 128,
         "essential": true
       },
       {
         "name": "app2",
         "image": "your-web-server-app-image",
         "memory": 256,
         "cpu": 128,
         "essential": true
       },
       {
         "name": "nginx-prometheus-exporter",
         "image": "docker.io/nginx/nginx-prometheus-exporter:0.8.0",
         "memory": 256,
         "cpu": 256,
         "essential": true,
         "command": [
           "-nginx.plus",
           "-nginx.scrape-uri",
            "http://nginx:8080/api"
       ],
       "links":[
         "nginx"
       ],
         "portMappings":[
           {
             "containerPort": 9113,
             "protocol": "tcp"
           }
         ]
       }
     ],
     "networkMode": "bridge",
     "placementConstraints": [],
     "family": "nginx-plus-sample-stack"
   }
   ```

1. 注册任务定义：

   ```
   aws ecs register-task-definition --cli-input-json file://path-to-your-task-definition-json
   ```

1. 通过输入以下命令创建服务以运行任务：

   ```
   aws ecs create-service \
    --cluster your-cluster-name \
    --service-name nginx-plus-service \
    --task-definition nginx-plus-sample-stack:1 \
    --desired-count 1
   ```

   确保不要更改服务名称。我们将使用配置来运行 CloudWatch 代理服务，该配置使用启动它们的服务的名称模式来搜索任务。例如，要让 CloudWatch 代理查找此命令启动的任务，您可以将 `sd_service_name_pattern` 的值指定为 `^nginx-plus-service$`。下一部分将提供更多详细信息。

### 配置 CloudWatch 代理以抓取 NGINX Plus Prometheus 指标
<a name="ContainerInsights-Prometheus-nginx-plus-ecs-setup-agent"></a>

最后一步是配置 CloudWatch 代理以抓取 NGINX 指标。在此示例中，CloudWatch 代理通过服务名称模式和端口 9113 发现任务，导出器在该端口公开 NGINX 的 prometheus 指标。发现任务且指标可用后，CloudWatch 代理开始将收集的指标发布到日志流 **nginx-prometheus-exporter**。

**配置 CloudWatch 代理以抓取 NGINX 指标**

1. 通过输入以下命令，下载必要 YAML 文件的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml
   ```

1. 使用文本编辑器打开文件，然后在 `resource:CWAgentConfigSSMParameter` 部分的 `value` 密钥中查找完整的 CloudWatch 代理配置。然后，在 `ecs_service_discovery` 部分中，添加以下 `service_name_list_for_tasks` 部分。

   ```
   "service_name_list_for_tasks": [
     {
       "sd_job_name": "nginx-plus-prometheus-exporter",
       "sd_metrics_path": "/metrics",
       "sd_metrics_ports": "9113",
       "sd_service_name_pattern": "^nginx-plus.*"
      }
   ],
   ```

1. 在同一个文件中，在 `metric_declaration` 的部分中添加以下部分，以允许 NGINX Plus 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["job"],
     "label_matcher": "^nginx-plus.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName"]],
     "metric_selectors": [
       "^nginxplus_connections_accepted$",
       "^nginxplus_connections_active$",
       "^nginxplus_connections_dropped$",
       "^nginxplus_connections_idle$",
       "^nginxplus_http_requests_total$",
       "^nginxplus_ssl_handshakes$",
       "^nginxplus_ssl_handshakes_failed$",
       "^nginxplus_up$",
       "^nginxplus_upstream_server_health_checks_fails$"
     ]
   },
   {
     "source_labels": ["job"],
     "label_matcher": "^nginx-plus.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName", "upstream"]],
     "metric_selectors": [
       "^nginxplus_upstream_server_response_time$"
     ]
   },
   {
     "source_labels": ["job"],
     "label_matcher": "^nginx-plus.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily", "ServiceName", "code"]],
     "metric_selectors": [
       "^nginxplus_upstream_server_responses$",
       "^nginxplus_server_zone_responses$"
     ]
   },
   ```

1. 如果您尚未在此集群中部署 CloudWatch 代理，请跳至步骤 8。

   如果您已经使用 AWS CloudFormation 将 CloudWatch 代理部署在 Amazon ECS 集群中，您可以通过输入以下命令来创建更改集：

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION \
       --change-set-name nginx-plus-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 **nginx-plus-scraping-support**。您会看到一项应用于 **CWAgentConfigSSMParameter** 资源的更改。通过输入以下命令，运行变更集并重新启动 CloudWatch 代理任务：

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 如果您是首次在集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令。

   ```
   ECS_CLUSTER_NAME=your_cluster_name
   AWS_REGION=your_aws_region
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

## 查看您的 NGINX Plus 指标和日志
<a name="ContainerInsights-Prometheus-Setup-nginx-plus-view"></a>

您现在可以查看正在收集的 NGINX Plus 指标。

**查看示例 NGINX 工作负载的指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在运行集群的区域中，选择左侧导航窗格中的 **Metrics（指标）**。查找 **ContainerInsights/Prometheus** 命名空间以查看指标。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。事件位于日志流 *nginx-plus-prometheus-exporter* 中的日志组 **/aws/containerinsights/*your\$1cluster\$1name*/prometheus** 中。

# 添加新 Prometheus 抓取目标的教程：Amazon ECS 上的 Memcached
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs"></a>

本教程提供实践介绍，关于如何在 Amazon ECS 集群上使用 EC2 启动类型抓取示例 Memcached 应用程序的 Prometheus 指标。Memcached Prometheus 导出器目标将由 CloudWatch 代理通过基于 ECS 任务定义的服务发现自动发现。

Memcached 是一个通用型分布式内存缓存系统。它通常用于通过在 RAM 中缓存数据和对象来加速动态数据库驱动的网站，以减少必须读取的外部数据源（例如数据库或 API）的次数。有关更多信息，请参阅[什么是 Memcached？](https://www.memcached.org/)

[memchached\$1exporter](https://github.com/prometheus/memcached_exporter)（Apache 许可证 2.0）是 Prometheus 一款官方导出器。默认情况下，memcache\$1exporter 在 `/metrics.` 的端口 0.0.0.0:9150 上提供服务

本教程使用了以下两个 Docker Hub 存储库中的 Docker 镜像：
+ [ Memcached](https://hub.docker.com/_/memcached?tab=description)
+ [prom/memcached-exporter](https://hub.docker.com/r/prom/memcached-exporter/)

**先决条件**

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

**Topics**
+ [设置 Amazon ECS EC2 集群环境变量](#ContainerInsights-Prometheus-Setup-memcached-ecs-environment)
+ [安装 Memcached 示例工作负载](#ContainerInsights-Prometheus-Setup-memcached-ecs-install-workload)
+ [配置 CloudWatch 代理以抓取 Memcached Prometheus 指标](#ContainerInsights-Prometheus-Setup-memcached-ecs-agent)
+ [查看您的 Memcached 指标](#ContainerInsights-Prometheus-ECS-memcached-view)

## 设置 Amazon ECS EC2 集群环境变量
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs-environment"></a>

**设置 Amazon ECS EC2 集群环境变量**

1. 请安装 Amazon ECS CLI（如果尚未安装）。有关更多信息，请参阅[安装 Amazon ECS CLI](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_CLI_installation.html)。

1. 设置新的 Amazon ECS 集群名称和区域。例如：

   ```
   ECS_CLUSTER_NAME=ecs-ec2-memcached-tutorial
   AWS_DEFAULT_REGION=ca-central-1
   ```

1. （可选）如果您还没有要在其中安装示例 Memcached 工作负载和 CloudWatch 代理的、带有 EC2 启动类型的 Amazon ECS 集群，您可以通过输入以下命令来创建一个。

   ```
   ecs-cli up --capability-iam --size 1 \
   --instance-type t3.medium \
   --cluster $ECS_CLUSTER_NAME \
   --region $AWS_REGION
   ```

   此命令的预期结果如下所示：

   ```
   WARN[0000] You will not be able to SSH into your EC2 instances without a key pair. 
   INFO[0000] Using recommended Amazon Linux 2 AMI with ECS Agent 1.44.4 and Docker version 19.03.6-ce 
   INFO[0001] Created cluster                               cluster=ecs-ec2-memcached-tutorial region=ca-central-1
   INFO[0002] Waiting for your cluster resources to be created... 
   INFO[0002] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS
   INFO[0063] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS
   INFO[0124] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS
   VPC created: vpc-xxxxxxxxxxxxxxxxx
   Security Group created: sg-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Cluster creation succeeded.
   ```

## 安装 Memcached 示例工作负载
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs-install-workload"></a>

**安装公开 Prometheus 指标的示例 Memcached 工作负载**

1. 通过输入以下命令，下载 Memcached CloudFormation 模板。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/sample_traffic/memcached/memcached-traffic-sample.yaml
   ```

1. 通过输入以下命令，设置要为 Memcached 创建的 IAM 角色名称。

   ```
   MEMCACHED_ECS_TASK_ROLE_NAME=memcached-prometheus-demo-ecs-task-role-name
   MEMCACHED_ECS_EXECUTION_ROLE_NAME=memcached-prometheus-demo-ecs-execution-role-name
   ```

1. 通过输入以下命令，安装示例 Memcached 工作负载。此示例在 `host` 网络模式下安装工作负载。

   ```
   MEMCACHED_ECS_NETWORK_MODE=host
   
   aws cloudformation create-stack --stack-name Memcached-Prometheus-Demo-ECS-$ECS_CLUSTER_NAME-EC2-$MEMCACHED_ECS_NETWORK_MODE \
       --template-body file://memcached-traffic-sample.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=ECSNetworkMode,ParameterValue=$MEMCACHED_ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$MEMCACHED_ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$MEMCACHED_ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

CloudFormation 堆栈创建四种资源：
+ 一个 ECS 任务角色
+ 一个 ECS 任务执行角色
+ 一个 Memcached 任务定义
+ 一项 Memcached 服务

在 Memcached 任务定义中，定义了两个容器：
+ 主容器运行一个简单的 Memcached 应用程序并打开端口 11211 以供访问。
+ 另一个容器运行 Redis OSS 导出器进程，以在端口 9150 上公开 Prometheus 指标。该容器将由 CloudWatch 代理发现和抓取。

## 配置 CloudWatch 代理以抓取 Memcached Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-memcached-ecs-agent"></a>

**配置 CloudWatch 代理以抓取 Memcached Prometheus 指标**

1. 通过输入以下命令，下载 `cwagent-ecs-prometheus-metric-for-awsvpc.yaml` 的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml
   ```

1. 使用文本编辑器打开该文件，并在 `resource:CWAgentConfigSSMParameter` 部分中的 `value` 密钥后面查找完整的 CloudWatch 代理配置。

   然后，在 `ecs_service_discovery` 部分中，将以下配置添加到 `task_definition_list` 部分中。

   ```
   {
       "sd_job_name": "ecs-memcached",
       "sd_metrics_ports": "9150",
       "sd_task_definition_arn_pattern": ".*:task-definition/memcached-prometheus-demo.*:[0-9]+"
   },
   ```

   对于 `metric_declaration` 部分，默认设置不允许任何 Memcached 指标。添加以下部分以允许 Memcached 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["container_name"],
     "label_matcher": "memcached-exporter-.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily"]],
     "metric_selectors": [
       "^memcached_current_(bytes|items|connections)$",
       "^memcached_items_(reclaimed|evicted)_total$",
       "^memcached_(written|read)_bytes_total$",
       "^memcached_limit_bytes$",
       "^memcached_commands_total$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "memcached-exporter-.*",
     "dimensions": [["ClusterName", "TaskDefinitionFamily","status","command"], ["ClusterName", "TaskDefinitionFamily","command"]],
     "metric_selectors": [
       "^memcached_commands_total$"
     ]
   },
   ```

1. 如果 CloudFormation 已在 Amazon ECS 集群中部署 CloudWatch 代理，您可以通过输入以下命令来创建更改集。

   ```
   ECS_NETWORK_MODE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION \
       --change-set-name memcached-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 `memcached-scraping-support`。您会看到一项应用于 `CWAgentConfigSSMParameter` 资源的更改。通过输入以下命令执行变更集并重新启动 CloudWatch 代理任务。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \
   --region $AWS_REGION
   ```

1. 如果您是首次为集群安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令：

   ```
   ECS_NETWORK_MODEE=bridge
   CREATE_IAM_ROLES=True
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
       --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_REGION
   ```

## 查看您的 Memcached 指标
<a name="ContainerInsights-Prometheus-ECS-memcached-view"></a>

本教程会将以下指标发送到 CloudWatch 中的 **ECS/ContainerInsights/Prometheus** 命名空间。您可以使用 CloudWatch 控制台查看该命名空间中的指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `memcached_current_items` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_current_connections` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_limit_bytes` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_current_bytes` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_written_bytes_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_read_bytes_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_items_evicted_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_items_reclaimed_total` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `memcached_commands_total` |  `ClusterName`, `TaskDefinitionFamily` `ClusterName`、TaskDefinitionFinitionFamy、command `ClusterName`、TaskDefinitionFamily、status、command  | 

**注意**  
**命令**维度的值可以是 `delete`、`get`、`cas`、`set`、`decr`、`touch`、`incr` 或 `flush`。  
**状态**维度的值可以是 `hit`、`miss` 或 `badval`。

您还可以为 Memcached Prometheus 指标创建 CloudWatch 控制面板。

**为 Memcached Prometheus 指标创建控制面板**

1. 创建环境变量，替换以下值以匹配部署。

   ```
   DASHBOARD_NAME=your_memcached_cw_dashboard_name
   ECS_TASK_DEF_FAMILY=memcached-prometheus-demo-$ECS_CLUSTER_NAME-EC2-$MEMCACHED_ECS_NETWORK_MOD
   ```

1. 输入以下命令以创建控制面板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/sample_cloudwatch_dashboards/memcached/cw_dashboard_memcached.json \
   | sed "s/{{YOUR_AWS_REGION}}/$AWS_REGION/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/$ECS_CLUSTER_NAME/g" \
   | sed "s/{{YOUR_TASK_DEF_FAMILY}}/$ECS_TASK_DEF_FAMILY/g" \
   | xargs -0 aws cloudwatch put-dashboard --dashboard-name ${DASHBOARD_NAME} --region $AWS_REGION --dashboard-body
   ```

# 在 Amazon ECS Fargate 上抓取 Redis OSS Prometheus 指标的教程
<a name="ContainerInsights-Prometheus-Setup-redis-ecs"></a>

本教程提供实践介绍，关于如何在 Amazon ECS Fargate 集群中抓取示例 Redis OSS 应用程序的 Prometheus 指标。Redis OSS Prometheus 导出器目标将由 CloudWatch 代理自动发现，并根据容器的 docker 标签提供 Prometheus 指标支持。

Redis OSS（https://redis.io/）是一个开源（获得 BSD 许可）的内存数据结构存储，用作数据库、缓存和消息代理。有关更多信息，请参阅 [ redis](https://redis.io/)。

redis\$1exporter（获得 MIT 许可证）用于在指定端口（默认值：0.0.0.0:9121）上公开 Redis OSS prometheus 指标。有关更多信息，请参阅 [redis\$1exporter](https://github.com/oliver006/redis_exporter)。

本教程使用了以下两个 Docker Hub 存储库中的 Docker 镜像：
+ [redis](https://hub.docker.com/_/redis?tab=description)
+ [redis\$1exporter](https://hub.docker.com/r/oliver006/redis_exporter)

**先决条件**

要从 Amazon ECS 的示例 Prometheus 工作负载收集指标，您必须在集群中运行 Container Insights。有关安装 Container Insights 的信息，请参阅 [在 Amazon ECS 上设置 Container Insights](deploy-container-insights-ECS.md)。

**Topics**
+ [设置 Amazon ECS Fargate 集群环境变量](#ContainerInsights-Prometheus-Setup-redis-ecs-variable)
+ [为 Amazon ECS Fargate 集群设置网络环境变量](#ContainerInsights-Prometheus-Setup-redis-ecs-variable2)
+ [安装 Redis OSS 示例工作负载](#ContainerInsights-Prometheus-Setup-redis-ecs-install-workload)
+ [配置 CloudWatch 代理以抓取 Redis OSS Prometheus 指标](#ContainerInsights-Prometheus-Setup-redis-ecs-agent)
+ [查看您的 Redis OSS 指标](#ContainerInsights-Prometheus-Setup-redis-view)

## 设置 Amazon ECS Fargate 集群环境变量
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-variable"></a>

**设置 Amazon ECS Fargate 集群环境变量**

1. 请安装 Amazon ECS CLI（如果尚未安装）。有关更多信息，请参阅[安装 Amazon ECS CLI](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_CLI_installation.html)。

1. 设置新的 Amazon ECS 集群名称和区域。例如：

   ```
   ECS_CLUSTER_NAME=ecs-fargate-redis-tutorial
   AWS_DEFAULT_REGION=ca-central-1
   ```

1. （可选）如果您还没有要在其中安装示例 Redis OSS 工作负载和 CloudWatch 代理的 Amazon ECS Fargate 集群，可以通过输入以下命令来创建一个。

   ```
   ecs-cli up --capability-iam \
   --cluster $ECS_CLUSTER_NAME \
   --launch-type FARGATE \
   --region $AWS_DEFAULT_REGION
   ```

   此命令的预期结果如下所示：

   ```
   INFO[0000] Created cluster   cluster=ecs-fargate-redis-tutorial region=ca-central-1
   INFO[0001] Waiting for your cluster resources to be created...
   INFO[0001] Cloudformation stack status   stackStatus=CREATE_IN_PROGRESS
   VPC created: vpc-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Subnet created: subnet-xxxxxxxxxxxxxxxxx
   Cluster creation succeeded.
   ```

## 为 Amazon ECS Fargate 集群设置网络环境变量
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-variable2"></a>

**为 Amazon ECS Fargate 集群设置网络环境变量**

1. 设置 Amazon ECS 集群的 VPC 和子网 ID。如果您在上一步骤中创建了新集群，您将在最终命令的结果中看到这些值。否则，请使用要与 Redis 一起使用的现有集群的 ID。

   ```
   ECS_CLUSTER_VPC=vpc-xxxxxxxxxxxxxxxxx
   ECS_CLUSTER_SUBNET_1=subnet-xxxxxxxxxxxxxxxxx
   ECS_CLUSTER_SUBNET_2=subnet-xxxxxxxxxxxxxxxxx
   ```

1. 在本教程中，我们将在 Amazon ECS 集群的 VPC 的默认安全组中安装 Redis OSS 应用程序和 CloudWatch 代理。默认安全组允许同一安全组内的所有网络连接，因此 CloudWatch 代理可以抓取 Redis OSS 容器上公开的 Prometheus 指标。在实际生产环境中，您可能希望为 Redis OSS 应用程序和 CloudWatch 代理创建专用安全组并为其设置自定义权限。

   要获取默认安全组 ID，请输入以下命令。

   ```
   aws ec2 describe-security-groups \
   --filters Name=vpc-id,Values=$ECS_CLUSTER_VPC  \
   --region $AWS_DEFAULT_REGION
   ```

   然后通过输入以下命令设置 Fargate 集群默认安全组变量，将 *my-default-security-group* 替换为您在上一个命令中找到的值。

   ```
   ECS_CLUSTER_SECURITY_GROUP=my-default-security-group
   ```

## 安装 Redis OSS 示例工作负载
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-install-workload"></a>

**安装公开 Prometheus 指标的示例 Redis OSS 工作负载**

1. 通过输入以下命令，下载 Redis OSS CloudFormation 模板。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/sample_traffic/redis/redis-traffic-sample.yaml
   ```

1. 通过输入以下命令，设置要为 Redis OSS 创建的 IAM 角色名称。

   ```
   REDIS_ECS_TASK_ROLE_NAME=redis-prometheus-demo-ecs-task-role-name
   REDIS_ECS_EXECUTION_ROLE_NAME=redis-prometheus-demo-ecs-execution-role-name
   ```

1. 通过输入以下命令安装 Redis OSS 示例工作负载。

   ```
   aws cloudformation create-stack --stack-name Redis-Prometheus-Demo-ECS-$ECS_CLUSTER_NAME-fargate-awsvpc \
       --template-body file://redis-traffic-sample.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET_1 \
                    ParameterKey=TaskRoleName,ParameterValue=$REDIS_ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$REDIS_ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region $AWS_DEFAULT_REGION
   ```

CloudFormation 堆栈创建四种资源：
+ 一个 ECS 任务角色
+ 一个 ECS 任务执行角色
+ 一个 Redis OSS 任务定义
+ 一项 Redis OSS 服务

在 Redis OSS 任务定义中，定义了两个容器：
+ 主容器运行一个简单的 Redis OSS 应用程序并打开端口 6379 以供访问。
+ 另一个容器运行 Redis OSS 导出器进程，以在端口 9121 上公开 Prometheus 指标。该容器将由 CloudWatch 代理发现和抓取。定义了以下 docker 标签，以便 CloudWatch 代理可以根据它发现该容器。

  ```
  ECS_PROMETHEUS_EXPORTER_PORT: 9121
  ```

## 配置 CloudWatch 代理以抓取 Redis OSS Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-redis-ecs-agent"></a>

**配置 CloudWatch 代理以抓取 Redis OSS Prometheus 指标**

1. 通过输入以下命令，下载 `cwagent-ecs-prometheus-metric-for-awsvpc.yaml` 的最新版本。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml
   ```

1. 使用文本编辑器打开该文件，并在 `resource:CWAgentConfigSSMParameter` 部分中的 `value` 密钥后面查找完整的 CloudWatch 代理配置。

   然后，在此处显示的 `ecs_service_discovery` 部分中，使用基于 `ECS_PROMETHEUS_EXPORTER_PORT` 的默认设置启用基于 `docker_label` 的服务发现，这与我们在 Redis OSS ECS 任务定义中定义的 Docker 标签相匹配。因此，我们无需在此部分进行任何更改：

   ```
   ecs_service_discovery": {
     "sd_frequency": "1m",
     "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
   *  "docker_label": {
     },*
     ...
   ```

   对于 `metric_declaration` 部分，默认设置不允许任何 Redis OSS 指标。添加以下部分以允许 Redis OSS 指标。请务必遵循现有的缩进模式。

   ```
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily"]],
     "metric_selectors": [
       "^redis_net_(in|out)put_bytes_total$",
       "^redis_(expired|evicted)_keys_total$",
       "^redis_keyspace_(hits|misses)_total$",
       "^redis_memory_used_bytes$",
       "^redis_connected_clients$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily","cmd"]],
     "metric_selectors": [
       "^redis_commands_total$"
     ]
   },
   {
     "source_labels": ["container_name"],
     "label_matcher": "^redis-exporter-.*$",
     "dimensions": [["ClusterName","TaskDefinitionFamily","db"]],
     "metric_selectors": [
       "^redis_db_keys$"
     ]
   },
   ```

1. 如果 CloudFormation 已在 Amazon ECS 集群中部署 CloudWatch 代理，您可以通过输入以下命令来创建更改集。

   ```
   ECS_LAUNCH_TYPE=FARGATE
   CREATE_IAM_ROLES=True
   ECS_CLUSTER_SUBNET=$ECS_CLUSTER_SUBNET_1
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-$ECS_CLUSTER_NAME-$ECS_LAUNCH_TYPE-awsvpc \
       --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSLaunchType,ParameterValue=$ECS_LAUNCH_TYPE \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION} \
       --change-set-name redis-scraping-support
   ```

1. 通过以下网址打开 CloudFormation 控制台：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 查看新创建的变更集 `redis-scraping-support`。您会看到一项应用于 `CWAgentConfigSSMParameter` 资源的更改。通过输入以下命令执行变更集并重新启动 CloudWatch 代理任务。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 0 \
   --service cwagent-prometheus-replica-service-$ECS_LAUNCH_TYPE-awsvpc \
   --region ${AWS_DEFAULT_REGION}
   ```

1. 等待大约 10 秒，然后输入以下命令。

   ```
   aws ecs update-service --cluster $ECS_CLUSTER_NAME \
   --desired-count 1 \
   --service cwagent-prometheus-replica-service-$ECS_LAUNCH_TYPE-awsvpc \
   --region ${AWS_DEFAULT_REGION}
   ```

1. 如果您是首次为集群安装带有 Prometheus 指标收集功能的 CloudWatch 代理，请输入以下命令：

   ```
   ECS_LAUNCH_TYPE=FARGATE
   CREATE_IAM_ROLES=True
   ECS_CLUSTER_SUBNET=$ECS_CLUSTER_SUBNET_1
   ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
   ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
   
   aws cloudformation create-stack --stack-name CWAgent-Prometheus-ECS-$ECS_CLUSTER_NAME-$ECS_LAUNCH_TYPE-awsvpc \
       --template-body file://cwagent-ecs-prometheus-metric-for-awsvpc.yaml \
       --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                    ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                    ParameterKey=ECSLaunchType,ParameterValue=$ECS_LAUNCH_TYPE \
                    ParameterKey=SecurityGroupID,ParameterValue=$ECS_CLUSTER_SECURITY_GROUP \
                    ParameterKey=SubnetID,ParameterValue=$ECS_CLUSTER_SUBNET \
                    ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                    ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
       --capabilities CAPABILITY_NAMED_IAM \
       --region ${AWS_DEFAULT_REGION}
   ```

## 查看您的 Redis OSS 指标
<a name="ContainerInsights-Prometheus-Setup-redis-view"></a>

本教程会将以下指标发送到 CloudWatch 中的 **ECS/ContainerInsights/Prometheus** 命名空间。您可以使用 CloudWatch 控制台查看该命名空间中的指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `redis_net_input_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_net_output_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_expired_keys_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_evicted_keys_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_keyspace_hits_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_keyspace_misses_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_memory_used_bytes` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_connected_clients` |  ClusterName、`TaskDefinitionFamily`  | 
|  `redis_commands_total` |  ` ClusterName`, `TaskDefinitionFamily`, `cmd`  | 
|  `redis_db_keys` |  `ClusterName`, `TaskDefinitionFamily`, `db`  | 

**注意**  
**cmd** 维度的值可以是 `append`、`client`、`command`、`config`、`dbsize`、`flushall`、`get`、`incr`、`info`、`latency` 或 `slowlog`。  
**db** 维度的值可以从 `db0` 到 `db15`。

您还可以为 Redis OSS Prometheus 指标创建 CloudWatch 控制面板。

**为 Redis OSS Prometheus 指标创建控制面板**

1. 创建环境变量，替换以下值以匹配部署。

   ```
   DASHBOARD_NAME=your_cw_dashboard_name
   ECS_TASK_DEF_FAMILY=redis-prometheus-demo-$ECS_CLUSTER_NAME-fargate-awsvpc
   ```

1. 输入以下命令以创建控制面板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/redis/cw_dashboard_redis.json \
   | sed "s/{{YOUR_AWS_REGION}}/${REGION_NAME}/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/${CLUSTER_NAME}/g" \
   | sed "s/{{YOUR_NAMESPACE}}/${NAMESPACE}/g" \
   ```

# 在 Amazon EKS 和 Kubernetes 集群上设置和配置 Prometheus 指标收集
<a name="ContainerInsights-Prometheus-install-EKS"></a>

要从运行 Amazon EKS 或 Kubernetes 的集群收集 Prometheus 指标，您可以使用 CloudWatch 代理作为收集器或使用 AWS Distro for OpenTelemetry 收集器。有关使用 AWS Distro for OpenTelemetry 收集器的信息，请参阅 [https://aws-otel.github.io/docs/getting-started/container-insights/eks-prometheus](https://aws-otel.github.io/docs/getting-started/container-insights/eks-prometheus)。

下面几节介绍如何使用 CloudWatch 代理收集 Prometheus 指标。他们说明了如何在运行 Amazon EKS 或 Kubernetes 的集群上安装带有 Prometheus 监控功能的 CloudWatch 代理，以及如何配置该代理以抓取其他目标。他们还提供用于设置示例工作负载的可选教程，以使用 Prometheus 监控进行测试。

**Topics**
+ [在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理](ContainerInsights-Prometheus-Setup.md)

# 在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup"></a>

本节介绍如何在运行 Amazon EKS 或 Kubernetes 的集群中设置带有 Prometheus 监控功能的 CloudWatch 代理。执行此操作后，代理会自动抓取并导入该集群中运行的以下工作负载的指标。
+ AWS App Mesh
+ NGINX
+ Memcached
+ Java/JMX
+ HAProxy
+ Fluent Bit

您还可以将代理配置为抓取和导入其他 Prometheus 工作负载和源。

在按照下面这些步骤安装 CloudWatch 代理来收集 Prometheus 指标之前，您必须有在 Amazon EKS 上运行的集群或者在 Amazon EC2 实例上运行的 Kubernetes 集群。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

**Topics**
+ [在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理](#ContainerInsights-Prometheus-Setup-roles)
+ [抓取其他 Prometheus 源并导入这些指标](ContainerInsights-Prometheus-Setup-configure.md)
+ [（可选）为 Prometheus 指标测试设置示例容器化 Amazon EKS 工作负载](ContainerInsights-Prometheus-Sample-Workloads.md)

## 在 Amazon EKS 和 Kubernetes 集群上安装带有 Prometheus 指标收集功能的 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-roles"></a>

本节介绍如何在运行 Amazon EKS 或 Kubernetes 的集群中设置带有 Prometheus 监控功能的 CloudWatch 代理。执行此操作后，代理会自动抓取并导入该集群中运行的以下工作负载的指标。
+ AWS App Mesh
+ NGINX
+ Memcached
+ Java/JMX
+ HAProxy
+ Fluent Bit

您还可以将代理配置为抓取和导入其他 Prometheus 工作负载和源。

在按照下面这些步骤安装 CloudWatch 代理来收集 Prometheus 指标之前，您必须有在 Amazon EKS 上运行的集群或者在 Amazon EC2 实例上运行的 Kubernetes 集群。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

**Topics**
+ [设置 IAM 角色](#ContainerInsights-Prometheus-Setup-roles)
+ [安装 CloudWatch 代理以收集 Prometheus 指标](#ContainerInsights-Prometheus-Setup-install-agent)

### 设置 IAM 角色
<a name="ContainerInsights-Prometheus-Setup-roles"></a>

第一步是在集群中设置必要的 IAM 角色。有两种方法：
+ 为服务账户设置 IAM 角色，也称为*服务角色*。此方法适用于 EC2 启动类型和 Fargate 启动类型。
+ 将 IAM 策略添加到集群的 IAM 角色。这仅适用于 EC2 启动类型。

**设置服务角色（EC2 启动类型和 Fargate 启动类型）**

要设置服务角色，请输入以下命令。将 *MyCluster* 替换为集群的名称。

```
eksctl create iamserviceaccount \
 --name cwagent-prometheus \
--namespace amazon-cloudwatch \
 --cluster MyCluster \
--attach-policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy \
--approve \
--override-existing-serviceaccounts
```

**向节点组的 IAM 角色添加策略（仅限 EC2 启动类型）**

**在节点组中为 Prometheus 支持设置 IAM 策略**

1. 通过以下网址打开 Amazon EC2 控制台：[https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/)。

1. 在导航窗格中，选择 **Instances (实例)**。

1. 您需要查找集群的 IAM 角色名称的前缀。为此，请选中集群中实例名称旁边的复选框，然后依次选择**操作**、**安全性**、**修改 IAM 角色**。然后复制 IAM 角色的前缀，例如 `eksctl-dev303-workshop-nodegroup`。

1. 通过以下网址打开 IAM 控制台：[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在导航窗格中，选择**角色**。

1. 使用搜索框查找您在此过程前面复制的前缀，然后选择该角色。

1. 选择**附加策略**。

1. 使用搜索框查找 **CloudWatchAgentServerPolicy**。选中 **CloudWatchAgentServerPolicy** 旁边的复选框，然后选择**附加策略**。

### 安装 CloudWatch 代理以收集 Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-install-agent"></a>

您必须在集群中安装 CloudWatch 代理才能收集指标。对于 Amazon EKS 集群和 Kubernetes 集群，安装代理的方式有所不同。

**删除具有 Prometheus 支持的 CloudWatch 代理的早期版本**

如果您的集群中已安装了具有 Prometheus 支持的 CloudWatch 代理版本，则必须通过输入以下命令删除该版本。这仅对具有 Prometheus 支持的以前版本的代理是必要的。您无需删除启用了 Container Insights 但没有 Prometheus 支持的 CloudWatch 代理。

```
kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
```

#### 在具有 EC2 启动类型的 Amazon EKS 集群上安装 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-install-agent-EKS"></a>

要在 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理，请按照下列步骤操作。

**在 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理**

1. 输入以下命令，检查是否已创建 `amazon-cloudwatch` 命名空间：

   ```
   kubectl get namespace
   ```

1. 如果结果中未显示 `amazon-cloudwatch`，请输入以下命令来创建它：

   ```
   kubectl create namespace amazon-cloudwatch
   ```

1. 要使用默认配置部署代理并使其将数据发送到所在的 AWS 区域，请输入以下命令：

   ```
   kubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
   ```

   要让代理将数据发送到不同的区域，请按照下列步骤操作：

   1. 输入以下命令，下载代理的 YAML 文件：

      ```
      curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
      ```

   1. 使用文本编辑器打开文件，然后搜索文件的 `cwagentconfig.json` 块。

   1. 添加突出显示的行，并指定所需的区域：

      ```
      cwagentconfig.json: |
          {
            "agent": {
              "region": "us-east-2"
            },
            "logs": { ...
      ```

   1. 保存文件并使用更新后的文件部署代理。

      ```
      kubectl apply -f prometheus-eks.yaml
      ```

#### 在具有 Fargate 启动类型的 Amazon EKS 集群上安装 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-install-agent-EKS-fargate"></a>

要在具有 Fargate 启动类型的 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理，请按照下列步骤操作。

**在具有 Fargate 启动类型的 Amazon EKS 集群上安装具有 Prometheus 支持的 CloudWatch 代理**

1. 输入以下命令为 CloudWatch 代理创建 Fargate 配置文件，以便它可以在集群内运行。将 *MyCluster* 替换为集群的名称。

   ```
   eksctl create fargateprofile --cluster MyCluster \
   --name amazon-cloudwatch \
   --namespace amazon-cloudwatch
   ```

1. 要安装 CloudWatch 代理，请输入以下命令。将 *MyCluster* 替换为集群的名称。此名称在存储代理收集的日志事件的日志组名称中使用，也用作代理收集的指标的维度。

   将 *region（区域）*替换为要将指标发送到的区域的名称。例如 `us-west-1`。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks-fargate.yaml | 
   sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" | 
   kubectl apply -f -
   ```

#### 在 Kubernetes 集群上安装 CloudWatch 代理
<a name="ContainerInsights-Prometheus-Setup-install-agent-Kubernetes"></a>

要在运行 Kubernetes 的集群上安装具有 Prometheus 支持的 CloudWatch 代理，请输入以下命令：

```
curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-k8s.yaml | 
sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" | 
kubectl apply -f -
```

将 *MyCluster* 替换为集群的名称。此名称在存储代理收集的日志事件的日志组名称中使用，也用作代理收集的指标的维度。

将 *region（区域）*替换为要将指标发送到的 AWS 区域的名称。例如 **us-west-1**。

#### 验证代理是否正在运行
<a name="ContainerInsights-Prometheus-Setup-install-agent-verify"></a>

在 Amazon EKS 和 Kubernetes 集群上，您可以输入以下命令以确认代理正在运行。

```
kubectl get pod -l "app=cwagent-prometheus" -n amazon-cloudwatch
```

如果结果包含处于 `Running` 状态的单个 CloudWatch 代理 pod，则代理会运行并收集 Prometheus 指标。默认情况下，CloudWatch 代理每分钟会收集 App Mesh、NGINX、Memcached、Java/JMX 和 HAProxy 的指标。有关这些指标的更多信息，请参阅 [CloudWatch 代理收集的 Prometheus 指标](ContainerInsights-Prometheus-metrics.md)。有关如何在 CloudWatch 中查看 Prometheus 指标的说明，请参阅 [查看 Prometheus 指标](ContainerInsights-Prometheus-viewmetrics.md)

您还可以将 CloudWatch 代理配置为从其他 Prometheus 导出程序收集指标。有关更多信息，请参阅 [抓取其他 Prometheus 源并导入这些指标](ContainerInsights-Prometheus-Setup-configure.md)。

# 抓取其他 Prometheus 源并导入这些指标
<a name="ContainerInsights-Prometheus-Setup-configure"></a>

具有 Prometheus 监控功能的 CloudWatch 代理需要两种配置来抓取 Prometheus 指标。一个用于 Prometheus 文档中 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 记录的标准 Prometheus 配置。另一种配置是 CloudWatch 代理配置文件。

对于 Amazon EKS 集群，配置在 `prometheus-eks.yaml`（适用于 EC2 启动类型）或 `prometheus-eks-fargate.yaml`（适用于 Fargate 启动类型）中定义为两个 Config 映射：
+ `name: prometheus-config` 部分包含 Prometheus 抓取的设置。
+ `name: prometheus-cwagentconfig` 部分包含 CloudWatch 代理的配置。您可以使用此部分配置 CloudWatch 如何收集 Prometheus 指标。例如，您指定要导入 CloudWatch 的指标，并定义其维度。

对于在 Amazon EC2 实例上运行的 Kubernetes 集群，配置在 `prometheus-k8s.yaml` YAML 文件中定义为两个 config 映射：
+ `name: prometheus-config` 部分包含 Prometheus 抓取的设置。
+ `name: prometheus-cwagentconfig` 部分包含 CloudWatch 代理的配置。

要抓取其他 Prometheus 指标源并将这些指标导入 CloudWatch，您需要修改 Prometheus 抓取配置和 CloudWatch 代理配置，然后使用更新的配置重新部署代理。

**VPC 安全组要求**

Prometheus 工作负载的安全组的入口规则必须向 CloudWatch 代理打开 Prometheus 端口，以便通过私有 IP 抓取 Prometheus 指标。

CloudWatch 代理的安全组的出口规则必须允许 CloudWatch 代理通过私有 IP 连接到 Prometheus 工作负载的端口。

## Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Setup-config-global"></a>

CloudWatch 代理支持标准的 Prometheus 抓取配置，如 Prometheus 文档中的 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 所述。您可以编辑此部分以更新此文件中已有的配置，并添加其他 Prometheus 抓取目标。默认情况下，示例配置文件包含以下全局配置行：

```
global:
  scrape_interval: 1m
  scrape_timeout: 10s
```
+ **scrape\$1interval** – 定义抓取目标的频率。
+ **scrape\$1timeout** – 定义抓取请求超时之前的等待时间。

您还可以在作业级别为这些设置定义不同的值，以覆盖全局配置。

### Prometheus 抓取任务
<a name="ContainerInsights-Prometheus-Setup-config-scrape"></a>

CloudWatch 代理 YAML 文件已配置了一些默认的抓取任务。例如在 `prometheus-eks.yaml` 中，在 `scrape_configs` 部分中的 `job_name` 行中配置了默认的抓取任务。在此文件中，以下默认 `kubernetes-pod-jmx` 部分会抓取 JMX Exporter 指标。

```
   - job_name: 'kubernetes-pod-jmx'
      sample_limit: 10000
      metrics_path: /metrics
      kubernetes_sd_configs:
      - role: pod
      relabel_configs:
      - source_labels: [__address__]
        action: keep
        regex: '.*:9404$'
      - action: labelmap
        regex: __meta_kubernetes_pod_label_(.+)
      - action: replace
        source_labels:
        - __meta_kubernetes_namespace
        target_label: Namespace
      - source_labels: [__meta_kubernetes_pod_name]
        action: replace
        target_label: pod_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_container_name
        target_label: container_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_controller_name
        target_label: pod_controller_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_controller_kind
        target_label: pod_controller_kind
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_phase
        target_label: pod_phase
```

这些默认目标中的每个目标都会被抓取，并使用嵌入式指标格式在日志事件中将指标发送到 CloudWatch。有关更多信息，请参阅 [在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。

来自 Amazon EKS 和 Kubernetes 集群的日志事件存储在 CloudWatch Logs 的 **/aws/containerinsights/*cluster\$1name*/prometheus** 日志组中。来自 Amazon ECS 集群的日志事件存储在 **/aws/ecs/containerinsights/*cluster\$1name*/prometheus** 日志组中。

每个抓取作业都包含在此日志组中的不同日志流中。例如，为 App Mesh 定义了 Prometheus 抓取任务 `kubernetes-pod-appmesh-envoy`。所有来自 Amazon EKS 和 Kubernetes 集群的 App Mesh Prometheus 指标都发送到名为 **/aws/containerinsights/*cluster\$1name*>prometheus/kubernetes-pod-appmesh-envoy/** 的日志流。

要添加新的抓取目标，请将新的 `job_name` 部分添加到 YAML 文件的 `scrape_configs` 部分，然后重新启动代理。有关此过程的示例，请参阅 [添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](#ContainerInsights-Prometheus-Setup-new-exporters)。

## Prometheus 的 CloudWatch 代理配置
<a name="ContainerInsights-Prometheus-Setup-cw-agent-config2"></a>

CloudWatch 代理配置文件在 `metrics_collected` 下面有一个 `prometheus` 部分用于 Prometheus 抓取配置。它包含以下配置选项：
+ **cluster\$1name** – 指定要在日志事件中添加为标签的集群名称。该字段是可选的。如果省略它，代理可以检测到 Amazon EKS 或 Kubernetes 集群名称。
+ **log\$1group\$1name** – 指定已抓取 Prometheus 指标的日志组名称。该字段是可选的。如果省略它，CloudWatch 会将 **/aws/containerinsights/*cluster\$1name*/prometheus** 用于来自 Amazon EKS 和 Kubernetes 集群的日志。
+ **prometheus\$1config\$1path** – 指定 Prometheus 抓取配置文件路径。如果此字段的值以 `env:` 开头，Prometheus 抓取配置文件内容将从容器的环境变量中检索。请勿更改此字段。
+ **ecs\$1service\$1discovery** – 是指定 Amazon ECS Prometheus 服务发现配置的部分。有关更多信息，请参阅 [Amazon ECS 集群上自动发现的详细指南](ContainerInsights-Prometheus-Setup-autodiscovery-ecs.md)。

  `ecs_service_discovery` 部分包含以下字段：
  + `sd_frequency` 是发现 Prometheus 导出器的频率。指定数字和单位后缀。例如，`1m` 表示每分钟一次或 `30s` 表示每 30 秒一次。有效的单位后缀为 `ns`、`us`、`ms`、`s`、`m` 和 `h`。

    该字段是可选的。默认值为 60 秒（1 分钟）。
  + `sd_target_cluster` 是用于自动发现的目标 Amazon ECS 集群名称。该字段是可选的。默认名称为安装 CloudWatch 代理的 Amazon ECS 集群的名称。
  + `sd_cluster_region` 是目标 Amazon ECS 集群的区域。该字段是可选的。默认区域为安装 CloudWatch 代理的 Amazon ECS 集群的区域。
  + `sd_result_file` 是 Prometheus 目标结果的 YAML 文件的路径。Prometheus 抓取配置将引用此文件。
  + `docker_label` 是可选部分，您可以使用它来指定基于 docker 标签的服务发现的配置。如果省略此部分，则不会使用基于 docker 标签的发现。此部分包含以下字段：
    + `sd_port_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标的容器端口。默认值为 `ECS_PROMETHEUS_EXPORTER_PORT`。如果容器没有此 docker 标签，CloudWatch 代理将跳过它。
    + `sd_metrics_path_label` 是容器的 docker 标签名称，用于指定 Prometheus 指标路径。默认值为 `ECS_PROMETHEUS_METRICS_PATH`。如果容器没有此 docker 标签，则代理会采用默认路径 `/metrics`。
    + `sd_job_name_label` 是容器的 docker 标签名称，用于指定 Prometheus 抓取任务名称。默认值为 `job`。如果容器没有此 docker 标签，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
  + `task_definition_list` 是可选部分，可用于指定基于任务定义的服务发现的配置。如果省略此部分，则不会使用基于任务定义的发现。此部分包含以下字段：
    + `sd_task_definition_arn_pattern` 是用于指定要发现的 Amazon ECS 任务定义的模式。这是正则表达式。
    + `sd_metrics_ports` 列出 Prometheus 指标的 containerPort。用分号分隔 containerPorts。
    + `sd_container_name_pattern` 指定 Amazon ECS 任务容器名称。这是正则表达式。
    + `sd_metrics_path` 指定 Prometheus 指标路径。如果省略此项，代理会采用默认路径 `/metrics`
    + `sd_job_name` 指定 Prometheus 抓取任务名称。如果省略此字段，CloudWatch 代理会使用 Prometheus 抓取配置中的任务名称。
+ **metric\$1declaration** – 是指定要生成的采用嵌入式指标格式的日志数组的部分。默认情况下，CloudWatch 代理从中进行导入的每个 Prometheus 源都有 `metric_declaration` 部分。这些部分各包括以下字段：
  + `label_matcher` 是一个正则表达式，用于检查 `source_labels` 中列出的标签的值。匹配的指标将启用，以包含在发送到 CloudWatch 的嵌入式指标格式中。

    如果您在 `source_labels` 中指定了多个标签，我们建议您不要在 `label_matcher` 的正则表达式中使用 `^` 或 `$` 字符。
  + `source_labels` 指定由 `label_matcher` 行检查的标签的值。
  + `label_separator` 指定要在 ` label_matcher` 行中使用的分隔符（如果指定了多个 `source_labels`）。默认值为 `;`。您可以在以下示例中看到 `label_matcher` 行中使用的此默认值。
  + `metric_selectors` 是一个正则表达式，用于指定要收集并发送到 CloudWatch 的指标。
  + `dimensions` 是要用作每个选定指标的 CloudWatch 维度的标签列表。

请参阅以下 `metric_declaration` 示例。

```
"metric_declaration": [
  {
     "source_labels":[ "Service", "Namespace"],
     "label_matcher":"(.*node-exporter.*|.*kube-dns.*);kube-system",
     "dimensions":[
        ["Service", "Namespace"]
     ],
     "metric_selectors":[
        "^coredns_dns_request_type_count_total$"
     ]
  }
]
```

此示例配置嵌入式指标格式部分，以便在满足以下条件时作为日志事件发送：
+ `Service` 的值包含 `node-exporter` 或 `kube-dns`。
+ `Namespace` 的值为 `kube-system`。
+ Prometheus 指标 `coredns_dns_request_type_count_total` 同时包含 `Service` 和 `Namespace` 标签。

发送的日志事件包括以下突出显示的部分：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"coredns_dns_request_type_count_total"
            }
         ],
         "Dimensions":[
            [
               "Namespace",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "Namespace":"kube-system",
   "Service":"kube-dns",
   "coredns_dns_request_type_count_total":2562,
   "eks_amazonaws_com_component":"kube-dns",
   "instance":"192.168.61.254:9153",
   "job":"kubernetes-service-endpoints",
   ...
}
```

## 添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标
<a name="ContainerInsights-Prometheus-Setup-new-exporters"></a>

默认情况下，Kubernetes API 服务器会在端点上公开 Prometheus 指标。Kubernetes API 服务器抓取配置的官方示例可在 [Github](https://github.com/prometheus/prometheus/blob/main/documentation/examples/prometheus-kubernetes.yml) 上找到。

以下教程演示如何执行以下步骤以开始将 Kubernetes API 服务器指标导入到 CloudWatch 中：
+ 将 Kubernetes API 服务器的 Prometheus 抓取配置添加到 CloudWatch 代理 YAML 文件。
+ 在 CloudWatch 代理 YAML 文件中配置嵌入式指标格式指标定义。
+ （可选）为 Kubernetes API 服务器指标创建 CloudWatch 控制面板。

**注意**  
Kubernetes API 服务器公开计量表、计数器、直方图和摘要指标。在此版本的 Prometheus 指标支持中，CloudWatch 仅导入具有计量表、计数器和汇总类型的指标。

**开始在 CloudWatch 中收集 Kubernetes API 服务器 Prometheus 指标**

1. 通过输入以下命令之一，下载 `prometheus-eks.yaml`、`prometheus-eks-fargate.yaml` 或 `prometheus-k8s.yaml` 文件的最新版本。

   对于具有 EC2 启动类型的 Amazon EKS 集群，请输入以下命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入以下命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks-fargate.yaml
   ```

   对于在 Amazon EC2 实例上运行的 Kubernetes 集群，请输入以下命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-k8s.yaml
   ```

1. 使用文本编辑器打开文件，找到 `prometheus-config` 部分，然后在该部分中添加以下部分。然后，保存更改：

   ```
       # Scrape config for API servers
       - job_name: 'kubernetes-apiservers'
         kubernetes_sd_configs:
           - role: endpoints
             namespaces:
               names:
                 - default
         scheme: https
         tls_config:
           ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
           insecure_skip_verify: true
         bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
         relabel_configs:
         - source_labels: [__meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
           action: keep
           regex: kubernetes;https
         - action: replace
           source_labels:
           - __meta_kubernetes_namespace
           target_label: Namespace
         - action: replace
           source_labels:
           - __meta_kubernetes_service_name
           target_label: Service
   ```

1. 当 YAML 文件仍在文本编辑器中处于打开状态时，找到 `cwagentconfig.json` 部分。添加以下子部分并保存更改。此部分将 API 服务器指标放到 CloudWatch 代理允许列表中。将三种类型的 API 服务器指标添加到允许列表中：
   + etcd 对象计数
   + API 服务器注册控制器指标
   + API 服务器请求指标

   ```
   {"source_labels": ["job", "resource"],
     "label_matcher": "^kubernetes-apiservers;(services|daemonsets.apps|deployments.apps|configmaps|endpoints|secrets|serviceaccounts|replicasets.apps)",
     "dimensions": [["ClusterName","Service","resource"]],
     "metric_selectors": [
     "^etcd_object_counts$"
     ]
   },
   {"source_labels": ["job", "name"],
      "label_matcher": "^kubernetes-apiservers;APIServiceRegistrationController$",
      "dimensions": [["ClusterName","Service","name"]],
      "metric_selectors": [
      "^workqueue_depth$",
      "^workqueue_adds_total$",
      "^workqueue_retries_total$"
     ]
   },
   {"source_labels": ["job","code"],
     "label_matcher": "^kubernetes-apiservers;2[0-9]{2}$",
     "dimensions": [["ClusterName","Service","code"]],
     "metric_selectors": [
      "^apiserver_request_total$"
     ]
   },
   {"source_labels": ["job"],
     "label_matcher": "^kubernetes-apiservers",
     "dimensions": [["ClusterName","Service"]],
     "metric_selectors": [
     "^apiserver_request_total$"
     ]
   },
   ```

1. 如果您已在集群中部署了具有 Prometheus 支持的 CloudWatch 代理，则必须通过输入以下命令将其删除：

   ```
   kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
   ```

1. 通过输入以下任一命令，使用更新的配置部署 CloudWatch 代理。对于具有 EC2 启动类型的 Amazon EKS 集群，请输入：

   ```
   kubectl apply -f prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入以下命令。将 *MyCluster* 和 *region（区域）*替换为值以匹配您的部署。

   ```
   cat prometheus-eks-fargate.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

   对于 Kubernetes 集群，请输入以下命令。将 *MyCluster* 和 *region（区域）*替换为值以匹配您的部署。

   ```
   cat prometheus-k8s.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

完成此操作后，您应该会看到 **/aws/containerinsights/*cluster\$1name*/prometheus** 日志组中名为 **kubernetes-apiservers** 的新日志流。此日志流应使用嵌入式指标格式定义来嵌入日志事件，如下所示：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"apiserver_request_total"
            }
         ],
         "Dimensions":[
            [
               "ClusterName",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "ClusterName":"my-cluster-name",
   "Namespace":"default",
   "Service":"kubernetes",
   "Timestamp":"1592267020339",
   "Version":"0",
   "apiserver_request_count":0,
   "apiserver_request_total":0,
   "code":"0",
   "component":"apiserver",
   "contentType":"application/json",
   "instance":"192.0.2.0:443",
   "job":"kubernetes-apiservers",
   "prom_metric_type":"counter",
   "resource":"pods",
   "scope":"namespace",
   "verb":"WATCH",
   "version":"v1"
}
```

您可以在 **ContainerInsights/Prometheus** 命名空间中的 CloudWatch 控制台中查看您的指标。（可选）还可以为 Prometheus Kubernetes API 服务器指标创建 CloudWatch 控制面板。

### （可选）为 Kubernetes API 服务器指标创建控制面板
<a name="ContainerInsights-Prometheus-Setup-KPI-dashboard"></a>

要在控制面板中查看 Kubernetes API 服务器指标，您必须先完成前面几个部分中的步骤，然后才能开始在 CloudWatch 中收集这些指标。

**为 Kubernetes API 服务器指标创建控制面板**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 确保选择了正确的 AWS 区域。

1. 在导航窗格中，选择**控制面板**。

1. 选择**创建控制面板**。输入新控制面板的名称，然后选择**创建控制面板**。

1. 在**添加到该控制面板**中，选择**取消**。

1. 依次选择**操作**、**编辑控制面板**。

1. 下载以下 JSON 文件：[Kubernetes API 控制面板源](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/kubernetes_api_server/cw_dashboard_kubernetes_api_server.json)。

1. 使用文本编辑器打开下载的 JSON 文件，然后执行以下更改：
   + 将所有 `{{YOUR_CLUSTER_NAME}}` 字符串替换为您的集群的确切名称。请勿在文本之前或之后添加空格。
   + 将所有 `{{YOUR_AWS_REGION}}` 字符串替换为在其中收集指标的区域的名称。例如 `us-west-2`。请勿在文本之前或之后添加空格。

1. 复制整个 JSON blob 并将其粘贴到 CloudWatch 控制台的文本框中，替换框中已有的内容。

1. 选择**更新**、**保存控制面板**。

# （可选）为 Prometheus 指标测试设置示例容器化 Amazon EKS 工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads"></a>

要测试 CloudWatch Container Insights 中的 Prometheus 指标支持，您可设置以下一个或多个容器化工作负载。具有 Prometheus 支持的 CloudWatch 代理会自动从这些工作负载中的每一个收集指标。要查看默认情况下收集的指标，请参阅 [CloudWatch 代理收集的 Prometheus 指标](ContainerInsights-Prometheus-metrics.md)。

在安装任意这些工作负载之前，您必须输入以下命令来安装 Helm 3.x：

```
brew install helm
```

有关更多信息，请参阅 [Helm](https://helm.sh)。

**Topics**
+ [为 Amazon EKS 和 Kubernetes 设置 AWS App Mesh 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-appmesh.md)
+ [使用 Amazon EKS 和 Kubernetes 上的示例流量设置 NGINX](ContainerInsights-Prometheus-Sample-Workloads-nginx.md)
+ [使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 memcached](ContainerInsights-Prometheus-Sample-Workloads-memcached.md)
+ [在 Amazon EKS 和 Kubernetes 上设置 Java/JMX 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-javajmx.md)
+ [使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 HAProxy](ContainerInsights-Prometheus-Sample-Workloads-haproxy.md)
+ [添加新 Prometheus 抓取目标的教程：Amazon EKS 和 Kubernetes 集群上的 Redis OSS](ContainerInsights-Prometheus-Setup-redis-eks.md)

# 为 Amazon EKS 和 Kubernetes 设置 AWS App Mesh 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh"></a>

CloudWatch Container Insights 支持 AWS App Mesh 中的 Prometheus 支持。以下部分介绍了如何设置 App Mesh。

**Topics**
+ [在具有 EC2 启动类型或 Kubernetes 集群的 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-appmesh-EKS.md)
+ [使用 Fargate 启动类型在 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载](ContainerInsights-Prometheus-Sample-Workloads-appmesh-Fargate.md)

# 在具有 EC2 启动类型或 Kubernetes 集群的 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-EKS"></a>

如果您要在运行 Amazon EKS 且具有 EC2 启动类型的集群或 Kubernetes 集群上设置 App Mesh，请使用这些说明。

## 配置 IAM 权限
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-iam"></a>

必须将 **AWSAppMeshFullAccess** 策略添加到您的 Amazon EKS 或 Kubernetes 节点组的 IAM 角色中。在 Amazon EKS 上，此节点组名称类似于 `eksctl-integ-test-eks-prometheus-NodeInstanceRole-ABCDEFHIJKL`。在 Kubernetes 上，它可能类似于 `nodes.integ-test-kops-prometheus.k8s.local`。

## 安装 App Mesh
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-install"></a>

要安装 App Mesh Kubernetes 控制器，请按照 [App Mesh 控制器](https://github.com/aws/eks-charts/tree/master/stable/appmesh-controller#app-mesh-controller)中的说明进行操作。

## 安装示例应用程序
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-application"></a>

[aws-app-mesh-examples](https://github.com/aws/aws-app-mesh-examples) 包含多个 Kubernetes App Mesh 演练。在本教程中，您将安装一个示例颜色应用程序，该应用程序会展示 http 路由如何使用标头来匹配传入请求。

**使用示例 App Mesh 应用程序来测试 Container Insights**

1. 按照以下说明安装应用程序：[https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-http-headers](https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-http-headers)。

1. 启动 curler pod 以生成流量：

   ```
   kubectl -n default run -it curler --image=tutum/curl /bin/bash
   ```

1. 通过更改 HTTP 标头来对不同的端点执行 curl。多次运行 curl 命令，如下所示：

   ```
   curl -H "color_header: blue" front.howto-k8s-http-headers.svc.cluster.local:8080/; echo;
   
   curl -H "color_header: red" front.howto-k8s-http-headers.svc.cluster.local:8080/; echo;
   
   curl -H "color_header: yellow" front.howto-k8s-http-headers.svc.cluster.local:8080/; echo;
   ```

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在集群运行的 AWS 区域的导航窗格中，选择 **Metrics（指标）**。指标位于 **ContainerInsights/Prometheus** 命名空间中。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。事件位于日志流 `kubernetes-pod-appmesh-envoy` 的日志组 ` /aws/containerinsights/your_cluster_name/prometheus ` 中。

## 删除 App Mesh 测试环境
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-delete"></a>

App Mesh 和示例应用程序使用完成后，请使用以下命令删除不必要的资源。输入以下命令删除示例应用程序：

```
cd aws-app-mesh-examples/walkthroughs/howto-k8s-http-headers/
kubectl delete -f _output/manifest.yaml
```

输入以下命令删除 App Mesh 控制器：

```
helm delete appmesh-controller -n appmesh-system
```

# 使用 Fargate 启动类型在 Amazon EKS 集群上设置 AWS App Mesh 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-Fargate"></a>

如果您要在运行 Amazon EKS 且具有 Fargate 启动类型的集群上设置 App Mesh，请遵循这些说明。

## 配置 IAM 权限
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh--fargate-iam"></a>

要设置 IAM 权限，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create iamserviceaccount --cluster MyCluster \
 --namespace howto-k8s-fargate \
 --name appmesh-pod \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshEnvoyAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapDiscoverInstanceAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchLogsFullAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshFullAccess \
 --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapFullAccess \
 --override-existing-serviceaccounts \
 --approve
```

## 安装 App Mesh
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-fargate-install"></a>

要安装 App Mesh Kubernetes 控制器，请按照 [App Mesh 控制器](https://github.com/aws/eks-charts/tree/master/stable/appmesh-controller#app-mesh-controller)中的说明进行操作。请务必按照有关 Fargate 启动类型的 Amazon EKS 的说明进行操作。

## 安装示例应用程序
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-fargate-application"></a>

[aws-app-mesh-examples](https://github.com/aws/aws-app-mesh-examples) 包含多个 Kubernetes App Mesh 演练。在本教程中，您将安装适用于 Fargate 启动类型的 Amazon EKS 集群的示例颜色应用程序。

**使用示例 App Mesh 应用程序来测试 Container Insights**

1. 按照以下说明安装应用程序：[https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-fargate](https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-fargate)。

   这些说明假定您正在使用正确的 Fargate 配置文件创建新集群。如果您想使用已设置的 Amazon EKS 集群，您可以使用以下命令为本演示设置该集群。将 *MyCluster* 替换为您的集群的名称。

   ```
   eksctl create iamserviceaccount --cluster MyCluster \
    --namespace howto-k8s-fargate \
    --name appmesh-pod \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshEnvoyAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapDiscoverInstanceAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/CloudWatchLogsFullAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSAppMeshFullAccess \
    --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapFullAccess \
    --override-existing-serviceaccounts \
    --approve
   ```

   ```
   eksctl create fargateprofile --cluster MyCluster \
   --namespace howto-k8s-fargate --name howto-k8s-fargate
   ```

1. 端口转发前端应用程序部署：

   ```
   kubectl -n howto-k8s-fargate port-forward deployment/front 8080:8080
   ```

1. Curl 前端应用程序：

   ```
   while true; do  curl -s http://localhost:8080/color; sleep 0.1; echo ; done
   ```

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在集群运行的 AWS 区域的导航窗格中，选择 **Metrics（指标）**。指标位于 **ContainerInsights/Prometheus** 命名空间中。

1. 要查看 CloudWatch Logs 事件，请在导航窗格中选择 **Log groups（日志组）**。事件位于日志流 `kubernetes-pod-appmesh-envoy` 的日志组 ` /aws/containerinsights/your_cluster_name/prometheus ` 中。

## 删除 App Mesh 测试环境
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-fargate-delete"></a>

App Mesh 和示例应用程序使用完成后，请使用以下命令删除不必要的资源。输入以下命令删除示例应用程序：

```
cd aws-app-mesh-examples/walkthroughs/howto-k8s-fargate/
kubectl delete -f _output/manifest.yaml
```

输入以下命令删除 App Mesh 控制器：

```
helm delete appmesh-controller -n appmesh-system
```

# 使用 Amazon EKS 和 Kubernetes 上的示例流量设置 NGINX
<a name="ContainerInsights-Prometheus-Sample-Workloads-nginx"></a>

NGINX 是一个 Web 服务器，也可以用作负载均衡器和反向代理。有关 Kubernetes 如何使用 NGINX for ingress 的更多信息，请参阅 [kubernetes/ingress-nginx](https://github.com/kubernetes/ingress-nginx)。

**安装带有示例流量服务的 Ingress-NGINX 以测试 Container Insights Prometheus 支持**

1. 输入以下命令以添加 Helm ingress-nginx 存储库：

   ```
   helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
   ```

1. 输入以下命令：

   ```
   kubectl create namespace nginx-ingress-sample
   
   helm install my-nginx ingress-nginx/ingress-nginx \
   --namespace nginx-ingress-sample \
   --set controller.metrics.enabled=true \
   --set-string controller.metrics.service.annotations."prometheus\.io/port"="10254" \
   --set-string controller.metrics.service.annotations."prometheus\.io/scrape"="true"
   ```

1. 通过输入以下命令检查服务是否正确启动：

   ```
   kubectl get service -n nginx-ingress-sample
   ```

   此命令的输出应显示多列，包括一个 `EXTERNAL-IP` 列。

1. 将 `EXTERNAL-IP` 变量设置为 NGINX 摄取控制器的行中 `EXTERNAL-IP` 列的值。

   ```
   EXTERNAL_IP=your-nginx-controller-external-ip
   ```

1. 输入以下命令启动一些示例 NGINX 流量。

   ```
   SAMPLE_TRAFFIC_NAMESPACE=nginx-sample-traffic
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_traffic/nginx-traffic/nginx-traffic-sample.yaml | 
   sed "s/{{external_ip}}/$EXTERNAL_IP/g" | 
   sed "s/{{namespace}}/$SAMPLE_TRAFFIC_NAMESPACE/g" | 
   kubectl apply -f -
   ```

1. 输入以下命令以确认所有三个 pod 都处于 `Running` 状态。

   ```
   kubectl get pod -n $SAMPLE_TRAFFIC_NAMESPACE
   ```

   如果它们正在运行，您应该很快在 **ContainerInsights/Prometheus** 命名空间中看到指标。

**卸载 NGINX 和示例流量应用程序**

1. 输入以下命令删除示例流量服务：

   ```
   kubectl delete namespace $SAMPLE_TRAFFIC_NAMESPACE
   ```

1. 按 Helm 版本名称删除 NGINX 出口。

   ```
   helm uninstall my-nginx --namespace nginx-ingress-sample
   kubectl delete namespace nginx-ingress-sample
   ```

# 使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 memcached
<a name="ContainerInsights-Prometheus-Sample-Workloads-memcached"></a>

memcached 是一个开源内存对象缓存系统。有关更多信息，请参阅[什么是 Memcached？](https://www.memcached.org)

如果您在具有 Fargate 启动类型的集群上运行 memcached，则需要在执行此过程中的步骤之前设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create fargateprofile --cluster MyCluster \
--namespace memcached-sample --name memcached-sample
```

**安装带有 Metric Exporter 的 memcached 以测试 Container Insights Prometheus 支持**

1. 输入以下命令以添加存储库：

   ```
   helm repo add bitnami https://charts.bitnami.com/bitnami
   ```

1. 输入以下命令以创建新的命名空间：

   ```
   kubectl create namespace memcached-sample
   ```

1. 输入以下命令以安装 Memcached

   ```
   helm install my-memcached bitnami/memcached --namespace memcached-sample \
   --set metrics.enabled=true \
   --set-string serviceAnnotations.prometheus\\.io/port="9150" \
   --set-string serviceAnnotations.prometheus\\.io/scrape="true"
   ```

1. 输入以下命令以确认正在运行的服务的注释：

   ```
   kubectl describe service my-memcached-metrics -n memcached-sample
   ```

   您应该看到以下两个注释：

   ```
   Annotations:   prometheus.io/port: 9150
                  prometheus.io/scrape: true
   ```

**卸载 memcached**
+ 输入以下命令：

  ```
  helm uninstall my-memcached --namespace memcached-sample
  kubectl delete namespace memcached-sample
  ```

# 在 Amazon EKS 和 Kubernetes 上设置 Java/JMX 示例工作负载
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx"></a>

JMX Exporter 是 Prometheus 的官方导出程序，可以将 JMX MBeans 作为 Prometheus 指标进行抓取和公开。有关详细信息，请参阅 [prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter)。

Container Insights 可以使用 JMX Exporter 从 Java 虚拟机 (JVM)、Java 和 Tomcat (Catalina) 收集预定义的 Prometheus 指标。

## 默认 Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-default"></a>

默认情况下，支持 Prometheus 的 CloudWatch 代理从 Amazon EKS 或 Kubernetes 集群中的每个 pod 上的 `http://CLUSTER_IP:9404/metrics` 抓取 Java/JMX Prometheus 指标。这是通过 Prometheus `kubernetes_sd_config` 的 `role: pod` 发现来完成的。9404 是 Prometheus 为 JMX Exporter 分配的默认端口。有关 `role: pod` 发现的更多信息，请参阅 [pod](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#pod)。您可以将 JMX Exporter 配置为在不同端口或 metrics\$1path 上公开指标。如果您更改了端口或路径，请更新 CloudWatch 代理 config 映射中的默认 jmx scrape\$1config。运行以下命令以获取当前 CloudWatch 代理 Prometheus 配置：

```
kubectl describe cm prometheus-config -n amazon-cloudwatch
```

要更改的字段是 `/metrics` 和 `regex: '.*:9404$'` 字段，如以下示例中突出显示所示。

```
job_name: 'kubernetes-jmx-pod'
sample_limit: 10000
metrics_path: /metrics
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__address__]
  action: keep
  regex: '.*:9404$'
- action: replace
  regex: (.+)
  source_labels:
```

## 其他 Prometheus 抓取配置
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-other"></a>

如果您通过 Kubernetes Service 使用 Java/JMX Prometheus 导出器公开在一组 pod 上运行的应用程序，您还可以切换到使用 Prometheus `kubernetes_sd_config` 的 `role: service` 发现或 `role: endpoint` 发现。有关这些发现方法的更多信息，请参阅[服务](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#service)、[端点](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#endpoints) 和 [<kubernetes\$1sd\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#kubernetes_sd_config)。

这两种服务发现模式提供了更多元标签，这对构建 CloudWatch 指标维度大有裨益。例如，您可以将 `__meta_kubernetes_service_name` 其重新标记为 `Service` 并将其包含在指标维度中。有关自定义 CloudWatch 指标及其维度的更多信息，请参阅 [Prometheus 的 CloudWatch 代理配置](ContainerInsights-Prometheus-Setup-configure-ECS.md#ContainerInsights-Prometheus-Setup-cw-agent-config)。

## 带有 JMX Exporter 的 Docker 镜像
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-docker"></a>

接下来，构建 Docker 镜像。以下各节提供了两个示例 Dockerfiles。

构建镜像后，请将其加载到 Amazon EKS 或 Kubernetes 中，然后运行以下命令以验证 `JMX_EXPORTER` 是否在端口 9404 上公开 Prometheus 指标。使用正在运行的 pod 名称替换 *\$1JAR\$1SAMPLE\$1TRAFFIC\$1POD*，并使用您的应用程序命名空间替换 *\$1JAR\$1SAMPLE\$1TRAFFIC\$1NAMESPACE*。

如果您在具有 Fargate 启动类型的集群上运行 JMX Exporter，则在执行此过程中的步骤之前，您还需要设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create fargateprofile --cluster MyCluster \
--namespace $JAR_SAMPLE_TRAFFIC_NAMESPACE\
 --name $JAR_SAMPLE_TRAFFIC_NAMESPACE
```

```
kubectl exec $JAR_SAMPLE_TRAFFIC_POD -n $JARCAT_SAMPLE_TRAFFIC_NAMESPACE -- curl http://localhost:9404
```

## 示例：具有 Prometheus 指标的 Apache Tomcat Docker 镜像
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-tomcat"></a>

默认情况下，Apache Tomcat 服务器公开 JMX MBeans。您可以将 JMX Exporter 与 Tomcat 集成，以便将 JMX MBeans 作为 Prometheus 指标公开。以下示例 Dockerfile 显示了构建测试镜像的步骤：

```
# From Tomcat 9.0 JDK8 OpenJDK 
FROM tomcat:9.0-jdk8-openjdk 

RUN mkdir -p /opt/jmx_exporter

COPY ./jmx_prometheus_javaagent-0.12.0.jar /opt/jmx_exporter
COPY ./config.yaml /opt/jmx_exporter
COPY ./setenv.sh /usr/local/tomcat/bin 
COPY your web application.war /usr/local/tomcat/webapps/

RUN chmod  o+x /usr/local/tomcat/bin/setenv.sh

ENTRYPOINT ["catalina.sh", "run"]
```

下面的列表解释了此 Dockerfile 中的四个 `COPY` 行。
+ 从 [https://github.com/prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter) 下载最新的 JMX Exporter jar 文件。
+ `config.yaml` 是 JMX Exporter 配置文件。有关更多信息，请参阅 [https://github.com/prometheus/jmx\$1exporter\$1Configuration](https://github.com/prometheus/jmx_exporter#Configuration )。

  以下是 Java 和 Tomcat 的示例配置文件：

  ```
  lowercaseOutputName: true
  lowercaseOutputLabelNames: true
  
  rules:
  - pattern: 'java.lang<type=OperatingSystem><>(FreePhysicalMemorySize|TotalPhysicalMemorySize|FreeSwapSpaceSize|TotalSwapSpaceSize|SystemCpuLoad|ProcessCpuLoad|OpenFileDescriptorCount|AvailableProcessors)'
    name: java_lang_OperatingSystem_$1
    type: GAUGE
  
  - pattern: 'java.lang<type=Threading><>(TotalStartedThreadCount|ThreadCount)'
    name: java_lang_threading_$1
    type: GAUGE
  
  - pattern: 'Catalina<type=GlobalRequestProcessor, name=\"(\w+-\w+)-(\d+)\"><>(\w+)'
    name: catalina_globalrequestprocessor_$3_total
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina global $3
    type: COUNTER
  
  - pattern: 'Catalina<j2eeType=Servlet, WebModule=//([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), name=([-a-zA-Z0-9+/$%~_-|!.]*), J2EEApplication=none, J2EEServer=none><>(requestCount|maxTime|processingTime|errorCount)'
    name: catalina_servlet_$3_total
    labels:
      module: "$1"
      servlet: "$2"
    help: Catalina servlet $3 total
    type: COUNTER
  
  - pattern: 'Catalina<type=ThreadPool, name="(\w+-\w+)-(\d+)"><>(currentThreadCount|currentThreadsBusy|keepAliveCount|pollerThreadCount|connectionCount)'
    name: catalina_threadpool_$3
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina threadpool $3
    type: GAUGE
  
  - pattern: 'Catalina<type=Manager, host=([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), context=([-a-zA-Z0-9+/$%~_-|!.]*)><>(processingTime|sessionCounter|rejectedSessions|expiredSessions)'
    name: catalina_session_$3_total
    labels:
      context: "$2"
      host: "$1"
    help: Catalina session $3 total
    type: COUNTER
  
  - pattern: ".*"
  ```
+ `setenv.sh` 是一个 Tomcat 启动脚本，用于启动 JMX Exporter 和 Tomcat，并在本地主机的端口 9404 上公开 Prometheus 指标。它还为 JMX Exporter 提供 `config.yaml` 文件路径。

  ```
  $ cat setenv.sh 
  export JAVA_OPTS="-javaagent:/opt/jmx_exporter/jmx_prometheus_javaagent-0.12.0.jar=9404:/opt/jmx_exporter/config.yaml $JAVA_OPTS"
  ```
+ 您的 Web 应用程序 .war 是由 Tomcat 加载的 Web 应用程序 `war` 文件。

使用此配置构建 Docker 镜像并将其上载到镜像存储库。

## 示例：具有 Prometheus 指标的 Java Jar 应用程序 Docker 镜像
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-jar"></a>

以下示例 Dockerfile 显示了构建测试镜像的步骤：

```
# Alpine Linux with OpenJDK JRE
FROM openjdk:8-jre-alpine

RUN mkdir -p /opt/jmx_exporter

COPY ./jmx_prometheus_javaagent-0.12.0.jar /opt/jmx_exporter
COPY ./SampleJavaApplication-1.0-SNAPSHOT.jar /opt/jmx_exporter
COPY ./start_exporter_example.sh /opt/jmx_exporter
COPY ./config.yaml /opt/jmx_exporter

RUN chmod -R o+x /opt/jmx_exporter
RUN apk add curl

ENTRYPOINT exec /opt/jmx_exporter/start_exporter_example.sh
```

下面的列表解释了此 Dockerfile 中的四个 `COPY` 行。
+ 从 [https://github.com/prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter) 下载最新的 JMX Exporter jar 文件。
+ `config.yaml` 是 JMX Exporter 配置文件。有关更多信息，请参阅 [https://github.com/prometheus/jmx\$1exporter\$1Configuration](https://github.com/prometheus/jmx_exporter#Configuration )。

  以下是 Java 和 Tomcat 的示例配置文件：

  ```
  lowercaseOutputName: true
  lowercaseOutputLabelNames: true
  
  rules:
  - pattern: 'java.lang<type=OperatingSystem><>(FreePhysicalMemorySize|TotalPhysicalMemorySize|FreeSwapSpaceSize|TotalSwapSpaceSize|SystemCpuLoad|ProcessCpuLoad|OpenFileDescriptorCount|AvailableProcessors)'
    name: java_lang_OperatingSystem_$1
    type: GAUGE
  
  - pattern: 'java.lang<type=Threading><>(TotalStartedThreadCount|ThreadCount)'
    name: java_lang_threading_$1
    type: GAUGE
  
  - pattern: 'Catalina<type=GlobalRequestProcessor, name=\"(\w+-\w+)-(\d+)\"><>(\w+)'
    name: catalina_globalrequestprocessor_$3_total
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina global $3
    type: COUNTER
  
  - pattern: 'Catalina<j2eeType=Servlet, WebModule=//([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), name=([-a-zA-Z0-9+/$%~_-|!.]*), J2EEApplication=none, J2EEServer=none><>(requestCount|maxTime|processingTime|errorCount)'
    name: catalina_servlet_$3_total
    labels:
      module: "$1"
      servlet: "$2"
    help: Catalina servlet $3 total
    type: COUNTER
  
  - pattern: 'Catalina<type=ThreadPool, name="(\w+-\w+)-(\d+)"><>(currentThreadCount|currentThreadsBusy|keepAliveCount|pollerThreadCount|connectionCount)'
    name: catalina_threadpool_$3
    labels:
      port: "$2"
      protocol: "$1"
    help: Catalina threadpool $3
    type: GAUGE
  
  - pattern: 'Catalina<type=Manager, host=([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), context=([-a-zA-Z0-9+/$%~_-|!.]*)><>(processingTime|sessionCounter|rejectedSessions|expiredSessions)'
    name: catalina_session_$3_total
    labels:
      context: "$2"
      host: "$1"
    help: Catalina session $3 total
    type: COUNTER
  
  - pattern: ".*"
  ```
+ `start_exporter_example.sh` 是用于启动导出了 Prometheus 指标的 JAR 应用程序的脚本。它还为 JMX Exporter 提供 `config.yaml` 文件路径。

  ```
  $ cat start_exporter_example.sh 
  java -javaagent:/opt/jmx_exporter/jmx_prometheus_javaagent-0.12.0.jar=9404:/opt/jmx_exporter/config.yaml -cp  /opt/jmx_exporter/SampleJavaApplication-1.0-SNAPSHOT.jar com.gubupt.sample.app.App
  ```
+ SampleJavaApplication-1.0-SNAPSHOT.jar 是示例 Java 应用程序 jar 文件。将其替换为要监控的 Java 应用程序。

使用此配置构建 Docker 镜像并将其上载到镜像存储库。

# 使用 Amazon EKS 和 Kubernetes 上的指标导出器设置 HAProxy
<a name="ContainerInsights-Prometheus-Sample-Workloads-haproxy"></a>

HAProxy 是一个开源代理应用程序。有关更多信息，请参阅 [HAProxy](https://www.haproxy.org)。

如果您在具有 Fargate 启动类型的集群上运行 HAProxy，则在执行此过程中的步骤之前，您需要设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

```
eksctl create fargateprofile --cluster MyCluster \
--namespace haproxy-ingress-sample --name haproxy-ingress-sample
```

**安装带有 Metric Exporter 的 HAProxy 以测试 Container Insights Prometheus 支持**

1. 输入以下命令以添加 Helm incubator 存储库：

   ```
   helm repo add haproxy-ingress https://haproxy-ingress.github.io/charts
   ```

1. 输入以下命令以创建新的命名空间：

   ```
   kubectl create namespace haproxy-ingress-sample
   ```

1. 输入以下命令来安装 HAProxy：

   ```
   helm install haproxy haproxy-ingress/haproxy-ingress \
   --namespace haproxy-ingress-sample \
   --set defaultBackend.enabled=true \
   --set controller.stats.enabled=true \
   --set controller.metrics.enabled=true \
   --set-string controller.metrics.service.annotations."prometheus\.io/port"="9101" \
   --set-string controller.metrics.service.annotations."prometheus\.io/scrape"="true"
   ```

1. 输入以下命令以确认服务的注释：

   ```
   kubectl describe service haproxy-haproxy-ingress-metrics -n haproxy-ingress-sample
   ```

   您应该看到以下注释。

   ```
   Annotations:   prometheus.io/port: 9101
                  prometheus.io/scrape: true
   ```

**卸载 HAProxy**
+ 输入以下命令：

  ```
  helm uninstall haproxy --namespace haproxy-ingress-sample
  kubectl delete namespace haproxy-ingress-sample
  ```

# 添加新 Prometheus 抓取目标的教程：Amazon EKS 和 Kubernetes 集群上的 Redis OSS
<a name="ContainerInsights-Prometheus-Setup-redis-eks"></a>

本教程提供了在 Amazon EKS 和 Kubernetes 上抓取示例 Redis OSS 应用程序的 Prometheus 指标的实践介绍。Redis OSS（https://redis.io/）是一个开源（获得 BSD 许可）的内存数据结构存储，用作数据库、缓存和消息代理。有关更多信息，请参阅 [ redis](https://redis.io/)。

redis\$1exporter（获得 MIT 许可证）用于在指定端口（默认值：0.0.0.0:9121）上公开 Redis OSS prometheus 指标。有关更多信息，请参阅 [redis\$1exporter](https://github.com/oliver006/redis_exporter)。

本教程使用了以下两个 Docker Hub 存储库中的 Docker 镜像：
+ [redis](https://hub.docker.com/_/redis?tab=description)
+ [redis\$1exporter](https://hub.docker.com/r/oliver006/redis_exporter)

**安装公开 Prometheus 指标的示例 Redis OSS 工作负载**

1. 为示例 Redis OSS 工作负载设置命名空间。

   ```
   REDIS_NAMESPACE=redis-sample
   ```

1. 如果您在具有 Fargate 启动类型的集群上运行 Redis OSS，则需要设置 Fargate 配置文件。要设置配置文件，请输入以下命令。将 *MyCluster* 替换为您的集群的名称。

   ```
   eksctl create fargateprofile --cluster MyCluster \
   --namespace $REDIS_NAMESPACE --name $REDIS_NAMESPACE
   ```

1. 输入以下命令以安装示例 Redis OSS 工作负载。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_traffic/redis/redis-traffic-sample.yaml \
   | sed "s/{{namespace}}/$REDIS_NAMESPACE/g" \
   | kubectl apply -f -
   ```

1. 安装包括一个名为 `my-redis-metrics` 的服务，该服务在端口 9121 上公开 Redis OSS Prometheus 指标。输入以下命令以获取该服务的详细信息：

   ```
   kubectl describe service/my-redis-metrics  -n $REDIS_NAMESPACE
   ```

   在结果的 `Annotations` 部分，您将看到与 CloudWatch 代理的 Prometheus 抓取配置相匹配的两个注释，以便其可以自动发现工作负载：

   ```
   prometheus.io/port: 9121
   prometheus.io/scrape: true
   ```

   相关的 Prometheus 抓取配置可以在 `kubernetes-eks.yaml` 或 `kubernetes-k8s.yaml` 部分的 `- job_name: kubernetes-service-endpoints` 中找到。

**开始在 CloudWatch 中收集 Redis OSS Prometheus 指标**

1. 通过输入以下任一命令，下载 `kubernetes-eks.yaml` 或 `kubernetes-k8s.yaml` 文件的最新版本。对于具有 EC2 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks-fargate.yaml
   ```

   对于在 Amazon EC2 实例上运行的 Kubernetes 集群，请输入此命令。

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-k8s.yaml
   ```

1. 使用文本编辑器打开文件，然后找到 `cwagentconfig.json` 部分。添加以下子部分并保存更改。确保遵循现有模式缩进。

   ```
   {
     "source_labels": ["pod_name"],
     "label_matcher": "^redis-instance$",
     "dimensions": [["Namespace","ClusterName"]],
     "metric_selectors": [
       "^redis_net_(in|out)put_bytes_total$",
       "^redis_(expired|evicted)_keys_total$",
       "^redis_keyspace_(hits|misses)_total$",
       "^redis_memory_used_bytes$",
       "^redis_connected_clients$"
     ]
   },
   {
     "source_labels": ["pod_name"],
     "label_matcher": "^redis-instance$",
     "dimensions": [["Namespace","ClusterName","cmd"]],
     "metric_selectors": [
       "^redis_commands_total$"
     ]
   },
   {
     "source_labels": ["pod_name"],
     "label_matcher": "^redis-instance$",
     "dimensions": [["Namespace","ClusterName","db"]],
     "metric_selectors": [
       "^redis_db_keys$"
     ]
   },
   ```

   您添加的部分会将 Redis OSS 指标放入 CloudWatch 代理允许列表中。有关这些指标的列表，请参阅以下部分。

1. 如果您已在此集群中部署了具有 Prometheus 支持的 CloudWatch 代理，则必须通过输入以下命令将其删除。

   ```
   kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
   ```

1. 通过输入以下任一命令，使用更新的配置部署 CloudWatch 代理。替换 *MyCluster* 和 *region（区域）*以匹配您的设置。

   对于具有 EC2 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   kubectl apply -f prometheus-eks.yaml
   ```

   对于具有 Fargate 启动类型的 Amazon EKS 集群，请输入此命令。

   ```
   cat prometheus-eks-fargate.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

   对于 Kubernetes 集群，请输入此命令。

   ```
   cat prometheus-k8s.yaml \
   | sed "s/{{cluster_name}}/MyCluster/;s/{{region_name}}/region/" \
   | kubectl apply -f -
   ```

## 查看 Redis OSS Prometheus 指标
<a name="ContainerInsights-Prometheus-Setup-redis-eks-view"></a>

本教程会将以下指标发送到 CloudWatch 中的 **ContainerInsights/Prometheus** 命名空间。您可以使用 CloudWatch 控制台查看该命名空间中的指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `redis_net_input_bytes_total` |  ClusterName、`Namespace`  | 
|  `redis_net_output_bytes_total` |  ClusterName、`Namespace`  | 
|  `redis_expired_keys_total` |  ClusterName、`Namespace`  | 
|  `redis_evicted_keys_total` |  ClusterName、`Namespace`  | 
|  `redis_keyspace_hits_total` |  ClusterName、`Namespace`  | 
|  `redis_keyspace_misses_total` |  ClusterName、`Namespace`  | 
|  `redis_memory_used_bytes` |  ClusterName、`Namespace`  | 
|  `redis_connected_clients` |  ClusterName、`Namespace`  | 
|  `redis_commands_total` |  ClusterName、`Namespace`、cmd  | 
|  `redis_db_keys` |  Cluster、`Namespace`、db  | 

**注意**  
**cmd** 维度的值可以是 `append`、`client`、`command`、`config`、`dbsize`、`flushall`、`get`、`incr`、`info`、`latency` 或 `slowlog`。  
**db** 维度的值可以从 `db0` 到 `db15`。

您还可以为 Redis OSS Prometheus 指标创建 CloudWatch 控制面板。

**为 Redis OSS Prometheus 指标创建控制面板**

1. 创建环境变量，替换以下值以匹配部署。

   ```
   DASHBOARD_NAME=your_cw_dashboard_name
   REGION_NAME=your_metric_region_such_as_us-east-1
   CLUSTER_NAME=your_k8s_cluster_name_here
   NAMESPACE=your_redis_service_namespace_here
   ```

1. 输入以下命令以创建控制面板。

   ```
   curl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/redis/cw_dashboard_redis.json \
   | sed "s/{{YOUR_AWS_REGION}}/${REGION_NAME}/g" \
   | sed "s/{{YOUR_CLUSTER_NAME}}/${CLUSTER_NAME}/g" \
   | sed "s/{{YOUR_NAMESPACE}}/${NAMESPACE}/g" \
   ```

# CloudWatch 代理的 Prometheus 指标类型转换
<a name="ContainerInsights-Prometheus-metrics-conversion"></a>

Prometheus 客户端库提供四种核心指标类型：
+ 计数器
+ 计量表
+ 摘要
+ 直方图

CloudWatch 代理支持计数器、计量表和汇总指标类型。

 CloudWatch 代理会删除具有不受支持的直方图指标类型的 Prometheus 指标。有关更多信息，请参阅 [录入丢弃的 Prometheus 指标](ContainerInsights-Prometheus-troubleshooting-EKS.md#ContainerInsights-Prometheus-troubleshooting-droppedmetrics)。

**计量表指标**

Prometheus 计量表指标是表示可以任意上下的单个数值的度量。CloudWatch 代理会抓取计量表指标并直接发送这些值。

**计数器指标**

Prometheus 计数器指标是一个累积指标，表示单个单调增加的计数器，其值只能增加或重置为零。CloudWatch 代理根据上次抓取计算增量，并将增量值作为日志事件中的指标值发送。因此，CloudWatch 代理将从第二次抓取开始生成一个日志事件，并继续进行后续抓取（如果有）。

**汇总指标**

Prometheus 汇总指标是一种复杂的指标类型，由多个数据点表示。它提供观察的总数和所有观察值的总和。它在滑动时间窗口内计算可配置的分位数。

汇总指标的总和和计数是累积的，但分位数不是。以下示例显示了分位数的方差。

```
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 7.123e-06
go_gc_duration_seconds{quantile="0.25"} 9.204e-06
go_gc_duration_seconds{quantile="0.5"} 1.1065e-05
go_gc_duration_seconds{quantile="0.75"} 2.8731e-05
go_gc_duration_seconds{quantile="1"} 0.003841496
go_gc_duration_seconds_sum 0.37630427
go_gc_duration_seconds_count 9774
```

CloudWatch 代理以与处理计数器指标相同的方式处理汇总指标的总和和计数，如上一节所述。CloudWatch 代理会保留最初报告的分位数值。

# CloudWatch 代理收集的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics"></a>

具有 Prometheus 支持的 CloudWatch 代理可自动从多个服务和工作负载收集指标。以下部分列出了默认情况下收集的指标。您还可以将代理配置为从这些服务收集更多指标，并从其他应用程序和服务收集 Prometheus 指标。有关可收集的其他指标的更多信息，请参阅 [Prometheus 的 CloudWatch 代理配置](ContainerInsights-Prometheus-Setup-configure-ECS.md#ContainerInsights-Prometheus-Setup-cw-agent-config)。

从 Amazon EKS 和 Kubernetes 集群收集的 Prometheus 指标位于 **ContainerInsights/Prometheus** 命名空间中。从 Amazon ECS 集群收集的 Prometheus 指标位于 **ECS/ContainerInsights/Prometheus** 命名空间中。

**Topics**
+ [App Mesh 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-appmesh)
+ [NGINX 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-nginx)
+ [Memcached 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-memcached)
+ [Java/JMX 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-jmx)
+ [HAProxy 的 Prometheus 指标](#ContainerInsights-Prometheus-metrics-haproxy)

## App Mesh 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-appmesh"></a>

从 App Mesh 自动收集以下指标。

**Amazon EKS 和 Kubernetes 集群上 App Mesh 的 Prometheus 指标**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `envoy_http_downstream_rq_total` |  ClusterName、`Namespace`  | 
|  `envoy_http_downstream_rq_xx` |  ClusterName、`Namespace` ClusterName、`Namespace`、envoy\$1http\$1conn\$1manager\$1prefix、envoy\$1response\$1code\$1class  | 
|  `envoy_cluster_upstream_cx_rx_bytes_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_tx_bytes_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_membership_healthy` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_membership_total` |  ClusterName、`Namespace`  | 
|  `envoy_server_memory_heap_size` |  ClusterName、`Namespace`  | 
|  `envoy_server_memory_allocated` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_connect_timeout` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_pending_failure_eject` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_pending_overflow` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_timeout` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_try_per_timeout` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_rx_reset` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_destroy_local_with_active_rq` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_cx_destroy_remote_active_rq` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_maintenance_mode` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_paused_reading_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_resumed_reading_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_backed_up_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_flow_control_drained_total` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_retry` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_retry_success` |  ClusterName、`Namespace`  | 
|  `envoy_cluster_upstream_rq_retry_overflow` |  ClusterName、`Namespace`  | 
|  `envoy_server_live` |  ClusterName、`Namespace`  | 
|  `envoy_server_uptime` |  ClusterName、`Namespace`  | 

**Amazon ECS 集群上 App Mesh 的 Prometheus 指标**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `envoy_http_downstream_rq_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_http_downstream_rq_xx` |  ClusterName、`TaskDefinitionFamily` | 
|  `envoy_cluster_upstream_cx_rx_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_tx_bytes_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_membership_healthy` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_membership_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_memory_heap_size` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_memory_allocated` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_connect_timeout` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_pending_failure_eject` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_pending_overflow` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_timeout` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_try_per_timeout` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_rx_reset` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_destroy_local_with_active_rq` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_cx_destroy_remote_active_rq` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_maintenance_mode` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_paused_reading_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_resumed_reading_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_backed_up_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_flow_control_drained_total` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_retry` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_retry_success` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_cluster_upstream_rq_retry_overflow` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_live` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_server_uptime` |  ClusterName、`TaskDefinitionFamily`  | 
|  `envoy_http_downstream_rq_xx` |  ClusterName、TaskDefinitionFamily、envoy\$1http\$1conn\$1manager\$1prefix、envoy\$1response\$1code\$1class ClusterName、TaskDefinitionFamily、envoy\$1response\$1code\$1class | 

**注意**  
`TaskDefinitionFamily` 是网格的 Kubernetes 命名空间。  
`envoy_http_conn_manager_prefix` 的值可以是 `ingress`、`egress` 或 `admin`。  
`envoy_response_code_class` 的值可以是 `1`（代表 `1xx`）、`2`（代表 `2xx`）、`3`（代表 `3xx`）、`4`（代表 `4xx`）或 `5`（代表 `5xx`）。

## NGINX 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-nginx"></a>

从 Amazon EKS 和 Kubernetes 集群上的 NGINX 自动收集以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `nginx_ingress_controller_nginx_process_cpu_seconds_total` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_success` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_requests` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_nginx_process_connections` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_nginx_process_connections_total` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_nginx_process_resident_memory_bytes` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_config_last_reload_successful` |  ClusterName、`Namespace`、Service  | 
|  `nginx_ingress_controller_requests` |  ClusterName、`Namespace`、Service、status  | 

## Memcached 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-memcached"></a>

从 Amazon EKS 和 Kubernetes 集群上的 Memcached 中自动收集以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `memcached_current_items` |  ClusterName、`Namespace`、Service  | 
|  `memcached_current_connections` |  ClusterName、`Namespace`、Service  | 
|  `memcached_limit_bytes` |  ClusterName、`Namespace`、Service  | 
|  `memcached_current_bytes` |  ClusterName、`Namespace`、Service  | 
|  `memcached_written_bytes_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_read_bytes_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_items_evicted_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_items_reclaimed_total` |  ClusterName、`Namespace`、Service  | 
|  `memcached_commands_total` |  ClusterName、`Namespace`、Service ClusterName、`Namespace`、Service、command ClusterName、`Namespace`、Service、status、command  | 

## Java/JMX 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-jmx"></a>

**在 Amazon EKS 和 Kubernetes 集群上收集的指标**

在 Amazon EKS 和 Kubernetes 集群上，Container Insights 可以使用 JMX Exporter 从 Java 虚拟机 (JVM)、Java 和 Tomcat (Catalina) 收集以下预定义的 Prometheus 指标。有关更多信息，请参阅 Github 上的 [ prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter)。

**Amazon EKS 和 Kubernetes 集群上的 Java/JMX**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `jvm_classes_loaded` |  `ClusterName`, `Namespace`  | 
|  `jvm_threads_current` |  `ClusterName`, `Namespace`  | 
|  `jvm_threads_daemon` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_totalswapspacesize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_systemcpuload` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_processcpuload` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_freeswapspacesize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_totalphysicalmemorysize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_freephysicalmemorysize` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_openfiledescriptorcount` |  `ClusterName`, `Namespace`  | 
|  `java_lang_operatingsystem_availableprocessors` |  `ClusterName`, `Namespace`  | 
|  `jvm_memory_bytes_used` |  `ClusterName`、`Namespace`、area  | 
|  `jvm_memory_pool_bytes_used` |  `ClusterName`、`Namespace`、pool  | 

**注意**  
`area` 维度的值可以是 `heap` 或 `nonheap`。  
`pool` 维度的值可以是 `Tenured Gen`、`Compress Class Space`、`Survivor Space`、`Eden Space`、`Code Cache` 或 `Metaspace`。

**Amazon EKS 和 Kubernetes 集群上的 Tomcat/JMX**

除了上表中的 Java/JMX 指标外，还收集 Tomcat 工作负载的以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `catalina_manager_activesessions` |  `ClusterName`, `Namespace`  | 
|  `catalina_manager_rejectedsessions` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_bytesreceived` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_bytessent` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_requestcount` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_errorcount` |  `ClusterName`, `Namespace`  | 
|  `catalina_globalrequestprocessor_processingtime` |  `ClusterName`, `Namespace`  | 

**Amazon ECS 集群上的 Java/JMX**


| 指标名称 | Dimensions | 
| --- | --- | 
|  `jvm_classes_loaded` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `jvm_threads_current` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `jvm_threads_daemon` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_totalswapspacesize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_systemcpuload` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_processcpuload` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_freeswapspacesize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_totalphysicalmemorysize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_freephysicalmemorysize` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_openfiledescriptorcount` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `java_lang_operatingsystem_availableprocessors` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `jvm_memory_bytes_used` |  `ClusterName`、TaskDefinitionFamily、area  | 
|  `jvm_memory_pool_bytes_used` |  `ClusterName`、TaskDefinitionFamily、pool  | 

**注意**  
`area` 维度的值可以是 `heap` 或 `nonheap`。  
`pool` 维度的值可以是 `Tenured Gen`、`Compress Class Space`、`Survivor Space`、`Eden Space`、`Code Cache` 或 `Metaspace`。

**Amazon ECS 集群上的 Tomcat/JMX**

除上表中的 Java/JMX 指标外，还收集了 Amazon ECS 集群上 Tomcat 工作负载的以下指标。


| 指标名称 | Dimensions | 
| --- | --- | 
|  `catalina_manager_activesessions` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_manager_rejectedsessions` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_bytesreceived` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_bytessent` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_requestcount` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_errorcount` |  `ClusterName`, `TaskDefinitionFamily`  | 
|  `catalina_globalrequestprocessor_processingtime` |  `ClusterName`, `TaskDefinitionFamily`  | 

## HAProxy 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-metrics-haproxy"></a>

从 Amazon EKS 和 Kubernetes 集群上的 HAProxy 自动收集以下指标。

收集的指标取决于您使用的 HAProxy Ingress 版本。有关 HAProxy Ingress 及其版本的更多信息，请参阅 [haproxy-ingress](https://artifacthub.io/packages/helm/haproxy-ingress/haproxy-ingress)。


| 指标名称 | Dimensions | 可用性 | 
| --- | --- | --- | 
|  `haproxy_backend_bytes_in_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_bytes_out_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_connection_errors_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_connections_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_current_sessions` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_http_responses_total` |  `ClusterName`、`Namespace`、Service、code、backend  | 所有版本的 HAProxy Ingress | 
|  `haproxy_backend_status` |  `ClusterName`、`Namespace`、Service  |  仅在 HAProxy Ingress 0.10 或更高版本中  | 
|  `haproxy_backend_up` |  `ClusterName`、`Namespace`、Service  |  仅在 HAProxy Ingress 0.10 的更早版本中  | 
|  `haproxy_frontend_bytes_in_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_bytes_out_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_connections_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_current_sessions` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_http_requests_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_http_responses_total` |  `ClusterName`、`Namespace`、Service、code、frontend  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_request_errors_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 
|  `haproxy_frontend_requests_denied_total` |  `ClusterName`、`Namespace`、Service  | 所有版本的 HAProxy Ingress | 

**注意**  
`code` 维度的值可以是 `1xx`、`2xx`、`3xx`、`4xx`、`5xx` 或 `other`。  
`backend` 维度的值可以是：  
适用于 HAProxy Ingress 0.0.27 或更早版本的 `http-default-backend`、`http-shared-backend` 或 `httpsback-shared-backend`。
适用于高于 HAProxy Ingress 0.0.27 版本的 `_default_backend`。
`frontend` 维度的值可以是：  
适用于 HAProxy Ingress 0.0.27 或更早版本的 `httpfront-default-backend`、`httpfront-shared-frontend` 或 `httpfronts`。
适用于高于 HAProxy Ingress 0.0.27 版本的 `_front_http` 或 `_front_https`。

# 查看 Prometheus 指标
<a name="ContainerInsights-Prometheus-viewmetrics"></a>

您可以监控所有 Prometheus 指标并发出告警，包括来自 App Mesh、NGINX、Java/JMX、Memcached 和 HAProxy 的精选预聚合指标，以及任何其他您可能已添加的手动配置的 Prometheus 导出程序。有关从其他 Prometheus 导出程序收集指标的更多信息，请参阅[添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](ContainerInsights-Prometheus-Setup-configure.md#ContainerInsights-Prometheus-Setup-new-exporters)。

在 CloudWatch 控制台中，Container Insights 提供以下预构建报告：
+ 对于 Amazon EKS 和 Kubernetes 集群，有针对 App Mesh、NGINX、HAPROXY、Memcached 和 Java/JMX 的预构建报告。
+ 对于 Amazon ECS 集群，有针对 App Mesh 和 Java/JMX 的预构建报告。

Container Insights 还为 Container Insights 从中收集策管指标的每个工作负载提供自定义控制面板。您可以从 GitHub 下载这些控制面板 

**查看所有 Prometheus 指标**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**指标**。

1. 在命名空间列表中，选择 **ContainerInsights/Prometheus** 或 **ECS/ContainerInsights/Prometheus**。

1. 在以下列表中选择一组维度。然后选中您要查看的指标旁边的复选框。

**查看有关 Prometheus 指标的预构建报告**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择**性能监控**。

1. 在页面顶部附近的下拉框中，选择任一 Prometheus 选项。

   在另一个下拉框中，选择要查看的集群

我们还为 NGINX、App Mesh、Memcached、HAProxy 和 Java/JMX 提供了自定义控制面板。

**使用 Amazon 提供的自定义控制面板**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择 **Dashboards（控制面板）**。

1. 选择**创建控制面板**。输入新控制面板的名称，然后选择**创建控制面板**。

1. 在**添加到该控制面板**中，选择**取消**。

1. 依次选择**操作**、**编辑控制面板**。

1. 下载以下 JSON 文件之一：
   + [Github 上的 NGINX 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/nginx-ingress/cw_dashboard_nginx_ingress_controller.json)。
   + [Github 上的 App Mesh 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/appmesh/cw_dashboard_awsappmesh.json)。
   + [Github 上的 Memcached 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/memcached/cw_dashboard_memcached.json)
   + [Github 上的 HAProxy-Ingress 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/haproxy-ingress/cw_dashboard_haproxy_ingress.json)
   + [Github 上的 Java/JMX 自定义控制面板源代码](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/javajmx/cw_dashboard_javajmx.json)。

1. 使用文本编辑器打开下载的 JSON 文件，然后执行以下更改：
   + 将所有 `{{YOUR_CLUSTER_NAME}}` 字符串替换为您的集群的确切名称。请勿在文本之前或之后添加空格。
   + 将所有 `{{YOUR_REGION}}` 字符串替换为正在运行集群的 AWS 区域。例如，**us-west-1** 请勿在文本之前或之后添加空格。
   + 将所有 `{{YOUR_NAMESPACE}}` 字符串替换为您的工作负载的确切命名空间。
   + 将所有 `{{YOUR_SERVICE_NAME}}` 字符串替换为您的工作负载的确切服务名称。例如，**haproxy-haproxy-ingress-controller-metrics**

1. 复制整个 JSON blob 并将其粘贴到 CloudWatch 控制台的文本框中，替换框中已有的内容。

1. 选择**更新**、**保存控制面板**。

# Prometheus 指标故障排除
<a name="ContainerInsights-Prometheus-troubleshooting"></a>

本节提供有关排除 Prometheus 指标设置故障排除的帮助。

**Topics**
+ [对 Amazon ECS 上的 Prometheus 指标进行故障排除](ContainerInsights-Prometheus-troubleshooting-ECS.md)
+ [Amazon EKS 和 Kubernetes 集群上的 Prometheus 指标故障排除](ContainerInsights-Prometheus-troubleshooting-EKS.md)

# 对 Amazon ECS 上的 Prometheus 指标进行故障排除
<a name="ContainerInsights-Prometheus-troubleshooting-ECS"></a>

本节提供有关对 Amazon ECS 集群上的 Prometheus 指标设置进行故障排除的帮助。

## 我没有看到发送到 CloudWatch Logs 的 Prometheus 指标
<a name="ContainerInsights-Prometheus-troubleshooting-ECS-nometrics"></a>

Prometheus 指标在日志组 **/aws/ecs/containerinsights/cluster-name/Prometheus** 中摄取作为日志事件。如果未创建日志组或未将 Prometheus 指标发送到日志组，您需要首先检查 CloudWatch 代理是否已成功发现 Prometheus 目标。然后检查 CloudWatch 代理的安全组和权限设置。以下步骤会指导您进行调试。

**步骤 1：启用 CloudWatch 代理调试模式**

首先，通过将以下粗体行添加到 CloudFormation 模版文件、`cwagent-ecs-prometheus-metric-for-bridge-host.yaml` 或 `cwagent-ecs-prometheus-metric-for-awsvpc.yaml` 中并保存文件，将 CloudWatch 代理更改为调试模式。然后保存文件。

```
cwagentconfig.json: |
    {
      "agent": {
        "debug": true
      },
      "logs": {
        "metrics_collected": {
```

针对现有堆栈创建一个新的 CloudFormation 变更集。将变更集中的其他参数设置为与现有 CloudFormation 堆栈中相同的值。以下示例适用于使用 EC2 启动类型和桥式网络模式安装在 Amazon ECS 集群中的 CloudWatch 代理。

```
ECS_NETWORK_MODE=bridge
 CREATE_IAM_ROLES=True
ECS_TASK_ROLE_NAME=your_selected_ecs_task_role_name
ECS_EXECUTION_ROLE_NAME=your_selected_ecs_execution_role_name
NEW_CHANGESET_NAME=your_selected_ecs_execution_role_name

aws cloudformation create-change-set --stack-name CWAgent-Prometheus-ECS-${ECS_CLUSTER_NAME}-EC2-${ECS_NETWORK_MODE} \
    --template-body file://cwagent-ecs-prometheus-metric-for-bridge-host.yaml \
    --parameters ParameterKey=ECSClusterName,ParameterValue=$ECS_CLUSTER_NAME \
                 ParameterKey=CreateIAMRoles,ParameterValue=$CREATE_IAM_ROLES \
                 ParameterKey=ECSNetworkMode,ParameterValue=$ECS_NETWORK_MODE \
                 ParameterKey=TaskRoleName,ParameterValue=$ECS_TASK_ROLE_NAME \
                 ParameterKey=ExecutionRoleName,ParameterValue=$ECS_EXECUTION_ROLE_NAME \
    --capabilities CAPABILITY_NAMED_IAM \
    --region $AWS_REGION \
    --change-set-name $NEW_CHANGESET_NAME
```

转至 CloudFormation 控制台查看新的变更集，请参阅 `$NEW_CHANGESET_NAME`。应该对 **CWAgentConfigSSMParameter** 资源应用一项更改。通过输入以下命令执行变更集并重新启动 CloudWatch 代理任务。

```
aws ecs update-service --cluster $ECS_CLUSTER_NAME \
--desired-count 0 \
--service your_service_name_here \
--region $AWS_REGION
```

等待大约 10 秒，然后输入以下命令。

```
aws ecs update-service --cluster $ECS_CLUSTER_NAME \
--desired-count 1 \
--service your_service_name_here \
--region $AWS_REGION
```

**步骤 2：检查 ECS 服务发现日志**

CloudWatch 代理的 ECS 任务定义默认启用以下部分中的日志。日志将发送到 **/ecs/ecs-cwagent-prometheus** 日志组中的 CloudWatch Logs。

```
LogConfiguration:
  LogDriver: awslogs
    Options:
      awslogs-create-group: 'True'
      awslogs-group: "/ecs/ecs-cwagent-prometheus"
      awslogs-region: !Ref AWS::Region
      awslogs-stream-prefix: !Sub 'ecs-${ECSLaunchType}-awsvpc'
```

根据字符串 `ECS_SD_Stats` 筛选日志以获取与 ECS 服务发现相关的指标，如下例所示。

```
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeContainerInstances: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeInstancesRequest: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeTaskDefinition: 2
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_DescribeTasks: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: AWSCLI_ListTasks: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: Exporter_DiscoveredTargetCount: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Get_EC2MetaData: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Get_TaskDefinition: 2
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Size_ContainerInstance: 1
2020-09-1T01:53:14Z D! ECS_SD_Stats: LRUCache_Size_TaskDefinition: 2
2020-09-1T01:53:14Z D! ECS_SD_Stats: Latency: 43.399783ms
```

特定 ECS 服务发现周期的每个指标的含义如下：
+ **AWSCLI\$1DescribeContainerInstances** – `ECS::DescribeContainerInstances` 进行的 API 调用次数。
+ **AWSCLI\$1DescribeInstancesRequest** – `ECS::DescribeInstancesRequest` 进行的 API 调用次数。
+ **AWSCLI\$1DescribeTaskDefinition** – `ECS::DescribeTaskDefinition` 进行的 API 调用次数。
+ **AWSCLI\$1DescribeTasks** – `ECS::DescribeTasks` 进行的 API 调用次数。
+ **AWSCLI\$1ListTasks** – `ECS::ListTasks` 进行的 API 调用次数。
+ **ExporterDiscoveredTargetCount** – 已发现并成功导出到容器内的目标结果文件中的 Prometheus 目标数量。
+ **LRUCache\$1Get\$1EC2MetaData** – 从缓存中检索容器实例元数据的次数。
+ **LRUCache\$1Get\$1TaskDefinition** – 从缓存中检索 ECS 任务定义元数据的次数。
+ **LRUCache\$1Size\$1ContainerInstance** – 缓存在内存中的唯一容器实例元数据的数量。
+ **LRUCache\$1Size\$1TaskDefinition** – 缓存在内存中的唯一 ECS 任务定义的数量。
+ **延迟** – 服务发现周期所需的时间。

检查 `ExporterDiscoveredTargetCount` 的值以查看发现的 Prometheus 目标是否符合您的预期。如果不符合，可能的原因如下：
+ ECS 服务发现的配置可能与应用程序的设置不匹配。对于基于 docker 标签的服务发现，您的目标容器可能并未在 CloudWatch 代理中配置必要的 docker 标签以将其自动发现。对于 ECS 任务定义 ARN 基于正则表达式的服务发现，CloudWatch 代理中的正则表达式设置可能与应用程序的任务定义不匹配。
+ CloudWatch 代理的 ECS 任务角色可能没有权限检索 ECS 任务的元数据。检查 CloudWatch 代理是否已被授予以下只读权限：
  + `ec2:DescribeInstances`
  + `ecs:ListTasks`
  + `ecs:DescribeContainerInstances`
  + `ecs:DescribeTasks`
  + `ecs:DescribeTaskDefinition`

**步骤 3：检查网络连接以及 ECS 任务角色策略**

如果即使 `Exporter_DiscoveredTargetCount` 的值表明已发现 Prometheus 目标，仍然没有日志事件发送到目标 CloudWatch Logs 日志组，这可能是由以下任一原因引起的：
+ CloudWatch 代理可能无法连接到 Prometheus 目标端口。检查 CloudWatch 代理背后的安全组设置。私有 IP 应允许 CloudWatch 代理连接到 Prometheus 导出器端口。
+ CloudWatch 代理的 ECS 任务角色可能没有 **CloudWatchAgentServerPolicy** 托管策略。CloudWatch 代理的 ECS 任务角色需要具有此策略才能将 Prometheus 指标作为日志事件发送。如果您使用示例 CloudFormation 模板自动创建 IAM 角色，则 ECS 任务角色和 ECS 执行角色都会被授予执行 Prometheus 监控的最低权限。

# Amazon EKS 和 Kubernetes 集群上的 Prometheus 指标故障排除
<a name="ContainerInsights-Prometheus-troubleshooting-EKS"></a>

本节提供有关对 Amazon EKS 和 Kubernetes 集群上的 Prometheus 指标设置进行故障排除的帮助。

## Amazon EKS 上的一般故障排除步骤
<a name="ContainerInsights-Prometheus-troubleshooting-general"></a>

要确认 CloudWatch 代理正在运行，请输入以下命令。

```
kubectl get pod -n amazon-cloudwatch
```

输出应包含其 `NAME` 列中包含 `cwagent-prometheus-id` 并且 `STATUS column.`中包含 `Running` 的行。

要显示有关正在运行的 pod 的详细信息，请输入以下命令。将 *pod-name* 替换为名称以 `cw-agent-prometheus` 开头的 pod 的完整名称。

```
kubectl describe pod pod-name -n amazon-cloudwatch
```

如果您安装了 CloudWatch Container Insights，则可以使用 CloudWatch Logs Insights 从收集 Prometheus 指标的 CloudWatch 代理查询日志。

**查询应用程序日志**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择 **CloudWatch Logs Insights**。

1. 选择应用程序日志的日志组 **/aws/containerinsights/*cluster-name*/application**

1. 使用以下查询替换搜索查询表达式，然后选择**运行查询**

   ```
   fields ispresent(kubernetes.pod_name) as haskubernetes_pod_name, stream, kubernetes.pod_name, log | 
   filter haskubernetes_pod_name and kubernetes.pod_name like /cwagent-prometheus
   ```

您还可以确认 Prometheus 指标和元数据是否摄取作为 CloudWatch Logs 事件。

**确认正在摄取 Prometheus 数据**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 在导航窗格中，选择 **CloudWatch Logs Insights**。

1. 选择 **/aws/containerinsights/*cluster-name*/prometheus**

1. 使用以下查询替换搜索查询表达式，然后选择**运行查询**

   ```
   fields @timestamp, @message | sort @timestamp desc | limit 20
   ```

## 录入丢弃的 Prometheus 指标
<a name="ContainerInsights-Prometheus-troubleshooting-droppedmetrics"></a>

此版本不会收集直方图的 Prometheus 指标。您可以使用 CloudWatch 代理来检查是否因为任何 Prometheus 指标是直方图指标而丢弃了这些指标。您还可以记录由于是直方图指标，因此丢弃而未发送到 CloudWatch 的前 500 个 Prometheus 指标列表。

要查看是否丢弃了任何指标，请输入以下命令：

```
kubectl logs -l "app=cwagent-prometheus" -n amazon-cloudwatch --tail=-1
```

如果丢弃了任何指标，您将在 `/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log` 文件中看到以下行。

```
I! Drop Prometheus metrics with unsupported types. Only Gauge, Counter and Summary are supported.
I! Please enable CWAgent debug mode to view the first 500 dropped metrics
```

如果您看到这些行并想知道丢弃了哪些指标，请使用以下步骤。

**记录已丢弃的 Prometheus 指标列表**

1. 通过将以下粗体行添加到 `prometheus-eks.yaml` 或 `prometheus-k8s.yaml` 文件中并保存文件，将 CloudWatch 代理更改为调试模式。

   ```
   {
         "agent": {
           "debug": true
         },
   ```

   该文件的这一部分随后应该如下所示：

   ```
   cwagentconfig.json: |
       {
         "agent": {
           "debug": true
         },
         "logs": {
           "metrics_collected": {
   ```

1. 通过输入以下命令重新安装 CloudWatch 代理以启用调试模式：

   ```
   kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
   kubectl apply -f prometheus.yaml
   ```

   丢弃的指标将在 CloudWatch 代理 pod 中录入。

1. 要从 CloudWatch 代理 pod 检索日志，请输入以下命令：

   ```
   kubectl logs -l "app=cwagent-prometheus" -n amazon-cloudwatch --tail=-1
   ```

   或者，如果您安装了 Container Insights Fluentd 日志记录，日志也会保存在 CloudWatch Logs 日志组 **/aws/containerinsights/*cluster\$1name*/application** 中。

   要查询这些日志，您可以按照[Amazon EKS 上的一般故障排除步骤](#ContainerInsights-Prometheus-troubleshooting-general)中的步骤查询应用程序日志。

## 在哪里摄取 Prometheus 指标作为 CloudWatch Logs 日志事件？
<a name="ContainerInsights-Prometheus-troubleshooting-metrics_ingested"></a>

CloudWatch 代理为每个 Prometheus 抓取任务配置创建一个日志流。例如，在 `prometheus-eks.yaml` 和 `prometheus-k8s.yaml` 文件中，`job_name: 'kubernetes-pod-appmesh-envoy'` 行将抓取 App Mesh 指标。Prometheus 目标被定义为 `kubernetes-pod-appmesh-envoy`。因此，所有 App Mesh Prometheus 指标都作为 CloudWatch Logs 事件摄取到名为 **/aws/containerinsights/cluster-name/Prometheus** 的日志组下的 **kubernetes-pod-appmesh-envoy** 日志流中。

## 我在 CloudWatch 指标中没有看到 Amazon EKS 或 Kubernetes Prometheus 指标
<a name="ContainerInsights-Prometheus-troubleshooting-no-metrics"></a>

首先，确保 Prometheus 指标在日志组 **/aws/containerinsights/cluster-name/Prometheus** 中摄取作为日志事件。使用[在哪里摄取 Prometheus 指标作为 CloudWatch Logs 日志事件？](#ContainerInsights-Prometheus-troubleshooting-metrics_ingested)中的信息可帮助您检查目标日志流。如果未创建日志流或日志流中没有新的日志事件，请检查以下内容：
+ 检查 Prometheus 指标导出程序端点是否正确设置
+ 检查 CloudWatch 代理 YAML 文件 `config map: cwagent-prometheus` 部分中的 Prometheus 抓取配置是否正确。该配置应与 Prometheus 配置文件中的配置相同。有关更多信息，请参阅 Prometheus 文档中的 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config)。

如果正确摄取了 Prometheus 指标作为日志事件，请检查嵌入式指标格式设置是否已添加到日志事件以生成 CloudWatch 指标。

```
"CloudWatchMetrics":[
   {
      "Metrics":[
         {
            "Name":"envoy_http_downstream_cx_destroy_remote_active_rq"
         }
      ],
      "Dimensions":[
         [
            "ClusterName",
            "Namespace"
         ]
      ],
      "Namespace":"ContainerInsights/Prometheus"
   }
],
```

有关嵌入式指标格式的更多信息，请参阅[规范：嵌入式指标格式](CloudWatch_Embedded_Metric_Format_Specification.md)。

如果日志事件中没有嵌入式指标格式，请检查在 CloudWatch 代理安装 YAML 文件的 `config map: prometheus-cwagentconfig` 部分是否正确配置了 `metric_declaration` 部分。有关更多信息，请参阅 [添加新 Prometheus 抓取目标的教程：Prometheus API 服务器指标](ContainerInsights-Prometheus-Setup-configure.md#ContainerInsights-Prometheus-Setup-new-exporters)。

# 与 Application Insights 集成
<a name="container-insights-appinsights"></a>

Amazon CloudWatch Application Insights 可帮助您监控应用程序，并在应用程序资源和技术堆栈中指定和设置关键指标、日志和告警。有关更多信息，请参阅 [使用 CloudWatch Application Insights 检测常见应用程序问题](cloudwatch-application-insights.md)。

您可以启用 Application Insights，从容器化应用程序和微服务中收集其他数据。如果您尚未执行此操作，可以通过在 Container Insights 控制面板中的性能视图下方选择 **Auto-configure Application Insights**（自动配置 Application Insights）将其启用。

如果您已设置 CloudWatch Application Insights 来监控容器化应用程序，Application Insights 控制面板将显示在 Container Insights 控制面板下方。

有关 Application Insights 和容器化应用程序的更多信息，请参阅 [为 Amazon ECS 和 Amazon EKS 资源监控启用 Application Insights](appinsights-setting-up-console.md#appinsights-container-insights)。

# 在 Container Insights 内查看 Amazon ECS 生命周期事件
<a name="container-insights-ECS-lifecycle-events"></a>

您可以在 Container Insights 控制台中查看 Amazon ECS 生命周期事件。这样有助于您在一个视图中将容器指标、日志和事件关联在一起，从而便于您更完整地了解运行情况。

事件包括容器实例状态更改事件、任务状态更改事件和服务操作事件。它们会由 Amazon ECS 自动发送到 Amazon EventBridge，同时以事件日志的形式收集到 CloudWatch 中。有关这些事件的更多信息，请参阅 [Amazon ECS 事件](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html)。

Amazon ECS 生命周期事件适用标准 Continer Insights 定价。有关更多信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

要配置生命周期事件表并为集群创建规则，您必须拥有 `events:PutRule`、`events:PutTargets` 和 `logs:CreateLogGroup` 权限。您还必须确保有资源策略让 EventBridge 能够创建日志流并将日志发送到 CloudWatch Logs。如果此资源策略不存在，则可以输入以下命令进行创建：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Principal": {
        "Service": ["events.amazonaws.com", "delivery.logs.amazonaws.com"]
      },
      "Resource": "arn:aws:logs:us-east-1:111122223333:log-group:/aws/events/ecs/containerinsights/*:*",
      "Condition": {
        "StringEquals": {
        "aws:SourceAccount": "111122223333"
        },
        "ArnLike": {
        "aws:SourceArn": "arn:aws:events:us-east-1:111122223333:rule/eventsToLog*"
        }
      },
      "Sid": "TrustEventBridgeToStoreECSLifecycleLogEvents"
    }
  ]
}
```

------

您可以使用以下命令来检查您是否已有此策略，并确认附加策略的操作已正确执行。

```
aws logs describe-resource-policies --region region --output json
```

要查看生命周期事件表，您必须拥有 `events:DescribeRule`、`events:ListTargetsByRule` 和 `logs:DescribeLogGroups` 权限。

**要在 CloudWatch Container Insights 控制台中查看 Amazon ECS 生命周期事件**

1. 通过 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 打开 CloudWatch 控制台。

1. 选择 **Insights**、**Container Insights**。

1. 选择**查看性能控制面板**。

1. 在下一个下拉列表中，选择 **ECS Clusters**（ECS 集群）、**ECS Services**（ECS 服务）或 **ECS Tasks**（ECS 任务）。

1. 如果您在上一步中选择了 **ECS Services**（ECS 服务）或 **ECS Tasks**（ECS 任务），则选择 **Lifecycle events**（生命周期事件）选项卡。

1. 在页面底部，如果您看到 **Configure lifecycle events**（配置生命周期事件），选择它来为您的集群创建 EventBridge 规则。

   这些事件会显示在 Container Insights 窗格的下方和 Application Insights 部分的上方。要对这些事件进行额外分析并创建其他可视化效果，请在生命周期事件表中选择 **View in Logs Insights**（在 Logs Insights 中查看）。

# Container Insights 问题排查
<a name="ContainerInsights-troubleshooting"></a>

如果在使用 Container Insights 时遇到问题，以下部分可为您提供帮助。

## 在 Amazon EKS 或 Kubernetes 上部署失败
<a name="ContainerInsights-setup-EKS-troubleshooting-general"></a>

如果未在 Kubernetes 集群上正确部署该代理，请尝试执行以下操作：
+ 运行以下命令以获取 pod 列表。

  ```
  kubectl get pods -n amazon-cloudwatch
  ```
+ 运行以下命令并在输出底部检查事件。

  ```
  kubectl describe pod pod-name -n amazon-cloudwatch
  ```
+ 运行以下命令以检查日志。

  ```
  kubectl logs pod-name -n amazon-cloudwatch
  ```

## 未经授权的 panic：无法从 kubelet 检索 cadvisor 数据
<a name="ContainerInsights-setup-EKS-troubleshooting-permissions"></a>

如果您的部署失败，并显示错误 `Unauthorized panic: Cannot retrieve cadvisor data from kubelet`，则您的 kubelet 可能未启用 Webhook 授权模式。Container Insights 需要此模式。有关更多信息，请参阅 [在 CloudWatch 中验证 Container Insights 的先决条件](Container-Insights-prerequisites.md)。

## 在 Amazon ECS 上已删除和重新创建的集群上部署 Container Insights
<a name="ContainerInsights-troubleshooting-recreate"></a>

如果删除未启用 Container Insights 的现有 Amazon ECS 集群，并使用相同名称重新创建它，则无法在重新创建此集群时在此新集群上启用 Container Insights。您可以通过重新创建来启用它，然后输入以下命令：

```
aws ecs update-cluster-settings --cluster myCICluster --settings name=container Insights,value=enabled
```

## 端点无效错误
<a name="ContainerInsights-setup-invalid-endpoint"></a>

如果您看到类似于以下内容的错误消息，请检查以确保已将正在使用的命令中的所有占位符（例如 *cluster-name* 和 *region-name*）替换为正确的部署信息。

```
"log": "2020-04-02T08:36:16Z E! cloudwatchlogs: code: InvalidEndpointURL, message: invalid endpoint uri, original error: &url.Error{Op:\"parse\", URL:\"https://logs.{{region_name}}.amazonaws.com/\", Err:\"{\"}, &awserr.baseError{code:\"InvalidEndpointURL\", message:\"invalid endpoint uri\", errs:[]error{(*url.Error)(0xc0008723c0)}}\n",
```

## 指标未显示在控制台中
<a name="ContainerInsights-setup-EKS-troubleshooting-nometrics"></a>

如果您在 AWS 管理控制台中未看到任何 Container Insights 指标，请确保已完成 Container Insights 的设置。在完全设置 Container Insights 之前，不会显示指标。有关更多信息，请参阅 [设置 Container Insights](deploy-container-insights.md)。

## 升级集群后，Amazon EKS 或 Kubernetes 上缺少 Pod 指标
<a name="ContainerInsights-troubleshooting-podmetrics-missing"></a>

如果在您将 CloudWatch 代理作为进程守护程序集部署在新的或升级的集群上后，全部或部分容器组（pod）指标丢失，或者您看到包含 `W! No pod metric collected` 消息的错误日志，则本节可能很有帮助。

这些错误可能是由容器运行时的更改引起的，例如 containerd 或 docker systemd cgroup 驱动程序。您通常可以通过更新部署清单来解决此问题，以便将主机的 containerd 套接字挂载到容器中。请参见以下示例：

```
# For full example see https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/cwagent/cwagent-daemonset.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: cloudwatch-agent
  namespace: amazon-cloudwatch
spec:
  template:
    spec:
      containers:
        - name: cloudwatch-agent
# ...
          # Don't change the mountPath
          volumeMounts:
# ...
            - name: dockersock
              mountPath: /var/run/docker.sock
              readOnly: true
            - name: varlibdocker
              mountPath: /var/lib/docker
              readOnly: true
            - name: containerdsock # NEW mount
              mountPath: /run/containerd/containerd.sock
              readOnly: true
# ...
      volumes:
# ...
        - name: dockersock
          hostPath:
            path: /var/run/docker.sock
        - name: varlibdocker
          hostPath:
            path: /var/lib/docker
        - name: containerdsock # NEW volume
          hostPath:
            path: /run/containerd/containerd.sock
```

## 使用 Bottlerocket for Amazon EKS 时没有 pod 指标
<a name="ContainerInsights-troubleshooting-bottlerocket"></a>

Bottlerocket 是一个基于 Linux 的开源操作系统，AWS 专为运行容器而构建。

Bottlerocket 在主机上使用不同的 `containerd` 路径，因此您需要将卷更改为其位置。如果未这样设置，包含 `W! No pod metric collected` 的日志会显示错误。请参阅以下示例。

```
volumes:
  # ... 
    - name: containerdsock
      hostPath:
        # path: /run/containerd/containerd.sock
        # bottlerocket does not mount containerd sock at normal place
        # https://github.com/bottlerocket-os/bottlerocket/commit/91810c85b83ff4c3660b496e243ef8b55df0973b
        path: /run/dockershim.sock
```

## 将 containerd 运行时用于 Amazon EKS 或 Kubernetes 时，没有容器文件系统指标
<a name="ContainerInsights-troubleshooting-containerd"></a>

这是一个已知问题，正在由社群贡献者解决。有关更多信息，请参阅 GitHub 上的 [containerd 的磁盘使用指标](https://github.com/google/cadvisor/issues/2785)和 [containerd 的 cadvisor 不支持容器文件系统指标](https://github.com/aws/amazon-cloudwatch-agent/issues/192)。

## 收集 Prometheus 指标时，CloudWatch 代理的日志卷意外增加
<a name="ContainerInsights-troubleshooting-log-volume-increase"></a>

这是 CloudWatch 代理的 1.247347.6b250880 版本中推出的回归。此回归已在代理的更新版本中得到修复。它的影响仅限于客户收集 CloudWatch 代理本身的日志并且仍在使用 Prometheus 的情况。有关更多信息，请参阅 GitHub 上的 [[prometheus] 代理正在日志中打印所有收集的指标](https://github.com/aws/amazon-cloudwatch-agent/issues/209)。

## 未从 Dockerhub 找到发布说明中提到的最新 docker 镜像
<a name="ContainerInsights-troubleshooting-docker-image"></a>

在内部开始实际发布之前，我们会更新 Github 上的发布说明和标签。在 Github 上增加版本号后，通常需要 1 – 2 周才能在注册表上看到最新的 Docker 镜像。CloudWatch 代理容器镜像不会在夜间发布。您可以在以下位置直接从源代码构建镜像：[https://github.com/aws/amazon-cloudwatch-agent/tree/main/amazon-cloudwatch-container-insights/cloudwatch-agent-dockerfile](https://github.com/aws/amazon-cloudwatch-agent/tree/main/amazon-cloudwatch-container-insights/cloudwatch-agent-dockerfile)

## CloudWatch 代理上的 CrashLoopBackoff 错误
<a name="ContainerInsights-troubleshooting-crashloopbackoff"></a>

如果您看到 CloudWatch 代理出现 `CrashLoopBackOff` 错误，请确保您的 IAM 权限设置正确。有关更多信息，请参阅 [在 CloudWatch 中验证 Container Insights 的先决条件](Container-Insights-prerequisites.md)。

## CloudWatch 代理或 Fluentd 容器组（pod）卡在待处理状态
<a name="ContainerInsights-troubleshooting-pending"></a>

如果您有一个 CloudWatch 代理或 Fluentd 容器组（pod）卡在 `Pending` 状态或出现 `FailedScheduling` 错误，请根据代理所需的内核数量和 RAM 量确定您的节点是否有足够的计算资源。使用以下命令描述此 pod：

```
kubectl describe pod cloudwatch-agent-85ppg -n amazon-cloudwatch
```

# 构建您自己的 CloudWatch 代理 Docker 镜像
<a name="ContainerInsights-build-docker-image"></a>

您可以通过引用位于以下网址的 Dockerfile 来构建自己的 CloudWatch 代理 Docker 镜像：[ https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/cloudwatch-agent-dockerfile/Dockerfile](https://github.com/aws-samples/amazon-cloudwatch-container-insights/blob/latest/cloudwatch-agent-dockerfile/Dockerfile)。

Dockerfile 支持直接使用 `docker buildx` 构建多架构镜像。

# 在容器中部署其他 CloudWatch 代理功能
<a name="ContainerInsights-other-agent-features"></a>

您可以使用 CloudWatch 代理在容器中部署其他监控功能。这些功能如下所示：
+ **嵌入式指标格式** – 有关更多信息，请参阅 [在日志中嵌入指标](CloudWatch_Embedded_Metric_Format.md)。
+ **StatsD** – 有关更多信息，请参阅 [使用 StatsD 检索自定义指标](CloudWatch-Agent-custom-metrics-statsd.md)。

说明和必要的文件位于 GitHub 上的以下位置：
+ 对于 Amazon ECS 容器，请参阅[基于部署模式的 Amazon ECS 任务定义示例](https://github.com/aws-samples/amazon-cloudwatch-container-insights/tree/latest/ecs-task-definition-templates/deployment-mode)。
+ 对于 Amazon EKS 和 Kubernetes 容器，请参阅[基于部署模式的 Kubernetes YAML 文件示例](https://github.com/aws-samples/amazon-cloudwatch-container-insights/tree/latest/k8s-deployment-manifest-templates/deployment-mode)。