

# Amazon CloudWatch 解决方案：Amazon ECS 上的 Prometheus 指标收集
<a name="Solution-Prometheus-On-ECS"></a>

此解决方案可帮助您从 Amazon ECS 任务收集与 Prometheus 兼容的指标，而无需运行或扩展您自己的收集基础设施。任务通过 Prometheus 导出程序公开指标，Amazon CloudWatch 托管式 Prometheus 收集器通过基于 DNS 的服务发现来发现 VPC 中的任务，抓取其 `/metrics` 端点，并将指标传输至 CloudWatch。由于 Amazon ECS 任务是临时的，且其 IP 地址会发生变化，因此此解决方案使用 AWS Cloud Map 服务发现，以确保收集器始终抓取当前的任务集。有关所有 CloudWatch 可观测性解决方案的一般信息，请参阅 [CloudWatch 可观测性解决方案](Monitoring-Solutions.md)。有关托管式收集器的更多信息，请参阅 [Amazon CloudWatch 托管式 Prometheus 收集器](managed-prometheus-collectors.md)。

**Topics**
+ [要求](#Solution-Prometheus-On-ECS-Requirements)
+ [启用 Prometheus 导出程序](#Solution-Prometheus-On-ECS-Exporters)
+ [步骤 1：设置安全组](#Solution-Prometheus-On-ECS-Security-Groups)
+ [步骤 2：设置抓取配置](#Solution-Prometheus-On-ECS-Scrape-Config)
+ [步骤 3：设置抓取程序](#Solution-Prometheus-On-ECS-Create-Scraper)
+ [验证指标收集](#Solution-Prometheus-On-ECS-Validate)
+ [构建自定义控制面板](#Solution-Prometheus-On-ECS-Dashboards)
+ [成本](#Solution-Prometheus-On-ECS-Costs)

## 要求
<a name="Solution-Prometheus-On-ECS-Requirements"></a>

此解决方案适用于以下情况：
+ 计算：公开与 Prometheus 兼容的指标的 Amazon ECS 任务（在 Amazon EC2 或 AWS Fargate 上）。
+ 在 AWS Cloud Map 中注册的 Amazon ECS 服务，用于基于 DNS 的服务发现。
+ 已启用 DNS 的 Amazon VPC，以及至少两个位于不同可用区的子网，可供收集器使用。
+ 允许收集器访问任务中指标端口的安全组。如果任务与收集器共享安全组，则为指标端口添加自引用入站规则。

## 启用 Prometheus 导出程序
<a name="Solution-Prometheus-On-ECS-Exporters"></a>

Prometheus 导出程序是指在 HTTP `/metrics` 端点上以 Prometheus 展览格式公开指标的进程。在 Amazon ECS 上，通常将导出程序作为 Sidecar 容器，在与应用程序相同的任务定义中运行，或者对应用程序进行检测以直接公开指标。常用的导出程序如下：
+ **Node Exporter**：Amazon EC2 启动类型上任务的主机级基础设施指标（默认端口 9100）。有关更多信息，请参阅 GitHub 上的 [Node Exporter](https://github.com/prometheus/node_exporter) 存储库。
+ **JMX Exporter**：用于 Java 工作负载的 JVM 和 Java 应用程序指标。有关更多信息，请参阅 GitHub 上的 [JMX Exporter](https://github.com/prometheus/jmx_exporter) 存储库。
+ **NGINX Prometheus Exporter**：NGINX Web 服务器和反向代理指标。有关更多信息，请参阅 GitHub 上的 [NGINX Prometheus Exporter](https://github.com/nginx/nginx-prometheus-exporter) 存储库。
+ **DCGM Exporter**：GPU 工作负载的 NVIDIA GPU 指标（默认端口 9400）。有关更多信息，请参阅 GitHub 上的 [DCGM Exporter](https://github.com/NVIDIA/dcgm-exporter) 存储库。
+ **HAProxy Exporter**：HAProxy 负载均衡器指标。有关更多信息，请参阅 GitHub 上的 [HAProxy Exporter](https://github.com/prometheus/haproxy_exporter) 存储库。
+ **Apache Exporter**：Apache HTTP 服务器指标。有关更多信息，请参阅 GitHub 上的 [Apache Exporter](https://github.com/Lusitaniae/apache_exporter) 存储库。

将导出程序添加到任务定义中，并按照导出程序的官方文档公开其指标端口。有关可用导出程序的完整目录，请参阅 Prometheus 文档中的[导出程序和集成](https://prometheus.io/docs/instrumenting/exporters/)。

## 步骤 1：设置安全组
<a name="Solution-Prometheus-On-ECS-Security-Groups"></a>

确认 Amazon ECS 任务的安全组允许收集器通过指标端口接收入站流量。当任务和收集器共享安全组时，请添加自引用入站规则，以便同一安全组中的资源可以相互通信。以下命令允许来自同一安全组的端口 80 的入站流量：

```
aws ec2 authorize-security-group-ingress \
  --group-id {{sg-security-group-id}} \
  --ip-permissions IpProtocol=tcp,FromPort=80,ToPort=80,UserIdGroupPairs='[{GroupId={{sg-security-group-id}}}]'
```

## 步骤 2：设置抓取配置
<a name="Solution-Prometheus-On-ECS-Scrape-Config"></a>

对于在 AWS Cloud Map 中注册的 Amazon ECS 任务，请使用基于 DNS 的服务发现（`dns_sd_configs`），以在任务启动和停止时自动查找并抓取这些任务。`dns_sd_configs` 部分指示收集器查询 AWS Cloud Map DNS 名称，并抓取所有返回的 IP 地址。当 Amazon ECS 替换任务时，收集器会在下一次 DNS 查询时获取相关更改。`relabel_configs` 部分会为指标添加一致的标签，以便您可以跨服务进行查询和筛选。有关受支持的全部配置选项，请参阅 [抓取程序配置](managed-prometheus-collectors-scraper-configuration.md)。

```
global:
  scrape_interval: 30s
  scrape_timeout: 10s

scrape_configs:
  - job_name: 'ecs-payforadoption'
    dns_sd_configs:
      - names: ['{{payforadoption-go.Workshop-space}}']
        type: A
        port: 80
    metrics_path: '/metrics'
    relabel_configs:
      - target_label: service_name
        replacement: '{{payforadoption-go}}'
      - target_label: cloudmap_namespace
        replacement: '{{Workshop-space}}'
      - target_label: environment
        replacement: 'production'
      - target_label: compute_platform
        replacement: 'ecs-fargate'
```

## 步骤 3：设置抓取程序
<a name="Solution-Prometheus-On-ECS-Create-Scraper"></a>

创建连接 VPC 的托管式收集器，用于抓取 Amazon ECS 任务并将指标传输至 CloudWatch 数据集：

您可以使用 [GetDefaultScraperConfiguration](https://docs.aws.amazon.com/prometheus/latest/APIReference/API_GetDefaultScraperConfiguration.html) 以检索通用抓取程序配置，也可以提供自己的抓取程序配置。

------
#### [ AWS API ]

使用 `CreateScraper` API 操作，以便创建具有 CloudWatch 目标的抓取程序。将子网、安全组及数据集信息替换为您自己的值。

```
POST /scrapers HTTP/1.1

{
  "alias": "ecs-payforadoption-scraper",
  "source": {
    "vpcConfiguration": {
      "subnetIds": ["{{subnet-subnet-id-1}}", "{{subnet-subnet-id-2}}"],
      "securityGroupIds": ["{{sg-security-group-id}}"]
    }
  },
  "destination": {
    "cloudWatchConfiguration": {
      "datasetArn": "arn:aws:cloudwatch:{{us-west-2}}:{{123456789012}}:dataset/default"
    }
  },
  "scrapeConfiguration": {
    "configurationBlob": "{{base64-encoded-blob}}"
  }
}
```

------
#### [ AWS CLI ]

使用 `create-scraper` 命令，以便创建具有 CloudWatch 目标的抓取程序。将子网、安全组及数据集信息替换为您自己的值。

```
aws amp create-scraper \
  --alias "ecs-payforadoption-scraper" \
  --source '{
    "vpcConfiguration": {
      "subnetIds": ["{{subnet-subnet-id-1}}", "{{subnet-subnet-id-2}}"],
      "securityGroupIds": ["{{sg-security-group-id}}"]
    }
  }' \
  --scrape-configuration configurationBlob=$(cat {{ecs-scraper.yml}} | base64 -w 0) \
  --destination '{
    "cloudWatchConfiguration": {
      "datasetArn": "arn:aws:cloudwatch:{{us-west-2}}:{{123456789012}}:dataset/default"
    }
  }'
```

------

## 验证指标收集
<a name="Solution-Prometheus-On-ECS-Validate"></a>

收集器开始传输指标后，使用 [Query Studio](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-PromQL-QueryStudio.html) 在 CloudWatch 中运行临时查询，以确认指标是否已到达。例如，以下查询将返回过去五分钟内发送到 Amazon ECS 任务的平均每秒请求数：

```
rate(payforadoption_requests_total[5m])
```

## 构建自定义控制面板
<a name="Solution-Prometheus-On-ECS-Dashboards"></a>

在收集器开始将 Amazon ECS 指标传输至 CloudWatch 后，您可以构建自定义 CloudWatch 控制面板，以直观显示这些指标。使用自定义控制面板，您可以将 Prometheus 导出程序中的指标合并到小组件中，添加基于 PromQL 的查询，并整理小组件以满足监控需求。有关更多信息，请参阅[使用 CloudWatch 控制面板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。

## 成本
<a name="Solution-Prometheus-On-ECS-Costs"></a>

按小时对 Prometheus 收集器收费，且适用 CloudWatch OpenTelemetry 指标摄取定价。有关 CloudWatch 定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。