

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

此解决方案可帮助您从 Amazon EC2 实例收集与 Prometheus 兼容的指标，而无需运行或扩展您自己的收集基础设施。您在实例上运行一个或多个 Prometheus 导出程序，Amazon CloudWatch 托管式 Prometheus 收集器可发现 VPC 中的目标，抓取其 `/metrics` 端点，并将指标传输至 CloudWatch。有关所有 CloudWatch 可观测性解决方案的一般信息，请参阅 [CloudWatch 可观测性解决方案](Monitoring-Solutions.md)。有关托管式收集器的更多信息，请参阅 [Amazon CloudWatch 托管式 Prometheus 收集器](managed-prometheus-collectors.md)。

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

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

此解决方案适用于以下情况：
+ 计算：运行一个或多个 Prometheus 导出程序的 Amazon EC2 实例。
+ 已启用 DNS 的 Amazon VPC，以及至少两个位于不同可用区的子网，可供收集器使用。
+ 允许收集器访问实例上导出程序端口的安全组。

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

Prometheus 导出程序是指在 HTTP `/metrics` 端点上以 Prometheus 展览格式公开指标的进程。运行与要监控的工作负载相匹配的导出程序。以下导出程序通常在 Amazon EC2 上使用：
+ **Node Exporter**：主机级基础设施指标，例如 CPU、内存、磁盘和网络（默认端口 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/)。

启动导出程序后，通过从实例查询其端点以确认是否公开指标：

```
curl http://localhost:{{port-number}}/metrics
```

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

以下示例结合使用 `static_configs` 和实例私有 DNS 名称，在 Amazon EC2 实例上抓取示例应用程序（端口 8080）和 Node Exporter（端口 9100）。`relabel_configs` 部分会为指标添加一致的标签，以便您可以跨服务进行查询和筛选。有关受支持的全部配置选项，请参阅 [抓取程序配置](managed-prometheus-collectors-scraper-configuration.md)。

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

scrape_configs:
  - job_name: 'ec2-metrics'
    static_configs:
      - targets:
          - ip-{{ip-address}}.us-west-2.compute.internal:8080
    metrics_path: '/metrics'
    relabel_configs:
      - source_labels: [__address__]
        target_label: instance
        replacement: 'ec2-metrics-instance'
      - target_label: service
        replacement: 'ec2-metrics'
      - target_label: environment
        replacement: 'dev'
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: '.*'
        action: keep

  - job_name: ec2-node-exporter
    static_configs:
      - targets:
          - ip-{{ip-address}}.us-west-2.compute.internal:9100
```

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

创建连接 VPC 的托管式收集器，用于抓取实例并将指标传输至 CloudWatch 数据集。提供允许收集器访问导出程序端口的子网和安全组：

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

------
#### [ Amazon API ]

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

```
POST /scrapers HTTP/1.1

{
  "alias": "ec2-payment-service-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}}"
  }
}
```

------
#### [ Amazon CLI ]

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

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

------

创建托管式收集器时，Amazon Managed Service for Prometheus 会自动创建服务相关角色，该角色授予收集器访问 VPC 资源和写入 CloudWatch 数据集的权限。

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

几分钟内，指标即可开始流入 CloudWatch 数据集。要确认指标是否已到达，使用 [Query Studio](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/CloudWatch-PromQL-QueryStudio.html) 在 CloudWatch 中运行临时查询即可。例如，以下查询将返回 `ec2-metrics` 任务的指标：

```
{job="ec2-metrics"}
```

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

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

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

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