

# 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)。