

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Container Insights Prometheus 指標監控
<a name="ContainerInsights-Prometheus"></a>

適用於 Prometheus 的 CloudWatch Container Insights 監控可自動從容器化系統和工作負載探索 Prometheus 指標。Prometheus 是一種開放原始碼系統監控和警示工具組。如需詳細資訊，請參閱 Prometheus 文件中的[什麼是 Prometheus？](https://prometheus.io/docs/introduction/overview/)。

探索 Prometheus 指標可支援在 Amazon EC2 執行個體上執行的 [Amazon Elastic Container Service](https://aws.amazon.com/ecs/)、[Amazon Elastic Kubernetes Service](https://aws.amazon.com/eks/) 和 [Kubernetes](https://aws.amazon.com/kubernetes/) 叢集。將會收集 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 解決方案包含適用於本節所列熱門工作負載的預先建置儀表板。如需這些工作負載的範例組態，請參閱 [(選用) 設定範例容器化 Amazon ECS 工作負載，以進行 Prometheus 指標測試](ContainerInsights-Prometheus-Sample-Workloads-ECS.md) 和 [(選用) 設定範例容器化 Amazon EKS 工作負載範例進行 Prometheus 指標測試](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

# 在 Amazon ECS 執行個體上安裝和設定 Prometheus 指標集合
<a name="ContainerInsights-Prometheus-Setup-ECS"></a>

若要從 Amazon ECS 叢集收集 Prometheus 指標，您可以使用 CloudWatch 代理程式做為收集器，或使用 AWS Distro for OpenTelemetry 收集器。如需使用 AWS Distro for OpenTelemetry 收集器的詳細資訊，請參閱 https：//[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)
+ [(選用) 設定範例容器化 Amazon ECS 工作負載，以進行 Prometheus 指標測試](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)。

## 使用 安裝具有 Prometheus 監控的 CloudWatch 代理程式 CloudFormation
<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 任務角色使用的現有角色。
+ **TaskRoleName**— 如果您將 **CreateIAMRoles** 指定為 **True**，則會指定要用於新 Amazon ECS 任務角色的名稱。如果您將 **CreateIAMRoles** 指定為 **False**，則會指定要作為 Amazon ECS 任務執行角色使用的現有角色。
+ **ECSNetworkMode**— 如果您使用 EC2 啟動類型，請在此處指定網路模式。其必須為 **bridge** 或 **host**。
+ **ECSLaunchType**— 指定 **fargate** 或 **EC2**。
+ **SecurityGroupID**— 如果 **ECSNetworkMode** 是 **awsvpc**，請在此指定安全群組 ID。
+ **SubneId**— 如果 **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}
```

### AWS CloudFormation 堆疊建立的資源
<a name="ContainerInsights-Prometheus-Setup-ECS-resources"></a>

下表列出當您 CloudFormation 使用 在 Amazon ECS 叢集上設定 Container Insights with Prometheus 監控時所建立 AWS 的資源。


| Resource Type (資源類型) | 資源名稱 | 說明 | 
| --- | --- | --- | 
|  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 的參數存放區進行整合：
+ 秘密 `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 Exporters 的頻率。指定數字和單位尾碼。例如：每分鐘一次 `1m` 或每 30 秒`30s`一次。有效的單位尾碼為`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`

**注意**  
不符合規則表達式的 Docker 標籤 `[a-zA-Z_][a-zA-Z0-9_]*` 會被篩選掉。這與 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，以下列格式建構 Prometheus 匯出工具目標：`private_ip:host_port`。

`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` 檔案中。將掃描帶有 Docker 標籤的容器 `ECS_PROMETHEUS_EXPORTER_PORT_SUBSET_A`。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 代理程式將會每 5 分鐘查詢一次 ECS 任務的中繼資料，然後將已搜索到的目標寫入 CloudWatch 代理程式容器內的 `/tmp/cwagent_ecs_auto_sd.yaml` 檔案中。

定義了兩個任務定義 ARN 規則表達式部分：
+  對於第一個區段，會篩選出其 ECS 任務定義 ARN 中具有 `javajmx` 的 ECS 任務，以進行容器連接埠掃描。如果這些 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` 且 `:23` 的 `version` 的 ECS 任務，以進行容器連接埠掃描。對於名稱為 `envoy` 且在 `9901` 上公開容器連接埠的容器，則會使用映射的主機連接埠以及容器的私有 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 代理程式將會每 5 分鐘查詢一次 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.*`，以進行容器連接埠掃描。對於名稱為 `haproxy` 且在 8404 上公開容器連接埠的容器，則會使用映射的主機連接埠以及容器的私有 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 標籤的 ECS 任務 `MY_PROMETHEUS_EXPORTER_PORT_LABEL` 將被篩選為 Prometheus 連接埠掃描。目標 Prometheus 容器連接埠由標籤 `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 任務，以進行容器連接埠掃描。目標 Prometheus 容器連接埠由 `sd_metrics_ports` 定義為 9150。使用預設指標路徑 `/metrics`。使用 Prometheus 組態中定義的任務名稱。

# (選用) 設定範例容器化 Amazon ECS 工作負載，以進行 Prometheus 指標測試
<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 行。將根據 Prometheus 湊集的指定容器連接埠自動探索具有 `ECS_PROMETHEUS_EXPORTER_PORT` 標籤的容器。

CloudWatch 代理程式的預設設定在同一個檔案的第 112 行也具有針對 Java/JMX 的 `metric_declaration` 設定。目標容器的所有 Docker 標籤將會新增為 Prometheus 指標中的其他標籤，並傳送至 CloudWatch Logs。對於帶有 Docker 標籤的 Java/JMX 容器 `Java_EMF_Metrics=“true”`，會產生內嵌指標格式。

# 適用於 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
     ```
   + 一個修改自 [ https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/](https://github.com/awslabs/ecs-nginx-reverse-proxy/tree/master/reverse-proxy/) 的 `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;
     
       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;
         }
       }
     }
     ```
**注意**  
必須在 `nginx-prometheus-exporter` 設定為從中湊集指標的相同連接埠啟用 `stub_status`。在我們的範例任務定義中，將 `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，在 Amazon ECS 叢集中部署了 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-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. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 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，在 Amazon ECS 叢集中部署了 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-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. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 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>

本教學課程提供實作介紹，讓您在具有 EC2 啟動類型的 Amazon ECS 叢集上湊集範例 Memcached 應用程式的 Prometheus 指標。CloudWatch 代理程式會透過 ECS 任務定義型服務探索自動探索 Memcached Prometheus 匯出工具目標。

Memcached 是一個通用的分佈式記憶體快取系統。它通常用於透過在 RAM 中快取資料和物件，來加速動態資料庫驅動的網站，進而減少必須讀取外部資料來源 (例如資料庫或 API) 的次數。如需詳細資訊，請參閱[什麼是 Memcached？](https://www.memcached.org/)

[memchached\$1exporter](https://github.com/prometheus/memcached_exporter) (Apache License 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. 如果您已在 Amazon ECS 叢集中部署 CloudWatch 代理程式 CloudFormation，您可以輸入下列命令來建立變更集。

   ```
   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. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 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 主控台查看該命名空間中的指標。


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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`、TaskDefinitionFamily、命令 `ClusterName`、TaskDefinitionFamily、狀態、命令  | 

**注意**  
**command** (命令) 維度的數值可以是：`delete`、`get`、`cas`、`set`、`decr`、`touch`、`incr` 或 `flush`。  
**status** (狀態) 維度的數值可以是 `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 指標。CloudWatch 代理程式會根據容器的 Docker 標籤，自動探索 Redis OSS Prometheus 匯出工具目標，並支援 Prometheus 指標。

Redis OSS (https://redis.io/) 是一個開放原始碼 (BSD 授權)、記憶體內資料結構存儲，可用作資料庫、快取和訊息代理程式。如需詳細資訊，請參閱 [redis](https://redis.io/)。

redis\$1exporter (授權的 MIT 授權) 可用於在指定的連接埠上公開 Redis OSS Prometheus 指標 (預設：0.0.0.0:9121)。如需詳細資訊，請參閱 [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. 如果您已在 Amazon ECS 叢集中部署 CloudWatch 代理程式 CloudFormation，您可以輸入下列命令來建立變更集。

   ```
   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. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 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 主控台查看該命名空間中的指標。


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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：//[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)
+ [(選用) 設定範例容器化 Amazon EKS 工作負載範例進行 Prometheus 指標測試](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 啟動類型)**

**若要在節點群組中設定 IAM 政策以獲得 Prometheus 支援**

1. 前往 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/) 開啟 Amazon EC2 主控台。

1. 在導覽窗格中，選擇**執行個體**。

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** 旁的核取方塊，然後選擇 **Attach policy (連接政策)**。

### 安裝 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*。此名稱會用於存放代理程式所收集之日誌事件的日誌群組名稱中，也用作為代理程式所收集之指標的維度。

將*區域*取代為 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 啟動類型) 中定義為兩種組態映射：
+ `name: prometheus-config` 區段包含 Prometheus 湊集的設定。
+ `name: prometheus-cwagentconfig` 區段包含 CloudWatch 代理程式的組態。您可以使用此區段來設定 CloudWatch 收集 Prometheus 指標的方式。例如，您可以將要匯入 CloudWatch 的指標列入白名單，並定義其維度。

對於在 Amazon EC2 執行個體上執行的 Kubernetes 叢集，組態在 `prometheus-k8s.yaml` YAML 檔案中定義為兩種組態映射：
+ `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** 日誌群組。

每個湊集任務都包含在此日誌群組的不同日誌串流中。例如，Prometheus 湊集任務 `kubernetes-pod-appmesh-envoy` 是針對 App Mesh 所定義。來自 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 Exporters 的頻率。指定數字和單位尾碼。例如：每分鐘一次 `1m` 或每 30 秒`30s`一次。有效的單位尾碼為`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. 在導覽窗格中，選擇 **Dashboards** (儀表板)。

1. 選擇 **Create Dashboard (建立儀表板)**。輸入新儀表板的名稱，然後選擇 **Create dashboard (建立儀表板)**。

1. 在 **Add to this dashboard (新增至此儀表板)** 中，選擇 **Cancel (取消)**。

1. 選擇 **Actions (動作)**、**View/edit sources (檢視/編輯來源)**。

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. 選擇 **Update (更新)**、**Save dashboard (儲存儀表板)**。

# (選用) 設定範例容器化 Amazon EKS 工作負載範例進行 Prometheus 指標測試
<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 中的 Prometheus 支援可支援 AWS App Mesh。以下各節說明如何設定 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 區域中，選擇導覽窗格中**的指標**。指標位於 **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 區域中，選擇導覽窗格中**的指標**。指標位於 **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 伺服器，可同時用作為負載平衡器和反向代理。如需如何使用 NGINX 進行擷取的詳細資訊，請參閱 [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 egress。

   ```
   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
```

**使用指標匯出工具安裝 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 代理程式組態映射中的預設 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 上執行的應用程式，則還可以切換到使用 `role: service` 探索或 Prometheus `kubernetes_sd_config` 的 `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)。

## Docker 影像與 JMX Exporter
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-docker"></a>

下一步：建置 Docker 影像 下列各節提供兩個範例 Dockerfile。

當您建置映像後，請將它載入 Amazon EKS 或 Kubernetes，然後執行下列命令，以確認 `JMX_EXPORTER` 是在連接埠 9404 上公開 Prometheus 指標。將 *\$1JAR\$1SAMPLE\$1TRAFFIC\$1POD* 取代為執行中的 pod 名稱，並將 *\$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，並在 localhost 的連接埠 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
```

**使用指標匯出工具安裝 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 授權) 可用於在指定的連接埠上公開 Redis OSS Prometheus 指標 (預設：0.0.0.0:9121)。如需詳細資訊，請參閱 [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 主控台查看該命名空間中的指標。


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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` |  ClusterName、`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 指標**


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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 指標**


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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` 是 mesh 的 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 自動收集下列指標。


| 指標名稱 | 維度 | 
| --- | --- | 
|  `nginx_ingress_controller_nginx_process_cpu_seconds_total` |  ClusterName、`Namespace`、服務  | 
|  `nginx_ingress_controller_success` |  ClusterName、`Namespace`、服務  | 
|  `nginx_ingress_controller_requests` |  ClusterName、`Namespace`、服務  | 
|  `nginx_ingress_controller_nginx_process_connections` |  ClusterName、`Namespace`、服務  | 
|  `nginx_ingress_controller_nginx_process_connections_total` |  ClusterName、`Namespace`、服務  | 
|  `nginx_ingress_controller_nginx_process_resident_memory_bytes` |  ClusterName、`Namespace`、服務  | 
|  `nginx_ingress_controller_config_last_reload_successful` |  ClusterName、`Namespace`、服務  | 
|  `nginx_ingress_controller_requests` |  ClusterName、`Namespace`、服務、狀態  | 

## memcached 的 Prometheus 指標
<a name="ContainerInsights-Prometheus-metrics-memcached"></a>

系統會 Amazon EKS 和 Kubernetes 叢集上的 Memcached 自動收集下列指標。


| 指標名稱 | 維度 | 
| --- | --- | 
|  `memcached_current_items` |  ClusterName、`Namespace`、服務  | 
|  `memcached_current_connections` |  ClusterName、`Namespace`、服務  | 
|  `memcached_limit_bytes` |  ClusterName、`Namespace`、服務  | 
|  `memcached_current_bytes` |  ClusterName、`Namespace`、服務  | 
|  `memcached_written_bytes_total` |  ClusterName、`Namespace`、服務  | 
|  `memcached_read_bytes_total` |  ClusterName、`Namespace`、服務  | 
|  `memcached_items_evicted_total` |  ClusterName、`Namespace`、服務  | 
|  `memcached_items_reclaimed_total` |  ClusterName、`Namespace`、服務  | 
|  `memcached_commands_total` |  ClusterName、`Namespace`、服務 ClusterName、`Namespace`、服務、命令 ClusterName、`Namespace`、服務、狀態、命令  | 

## 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**


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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`、區域  | 
|  `jvm_memory_pool_bytes_used` |  `ClusterName`、`Namespace`、集區  | 

**注意**  
`area` 維度的數值可以是 `heap` 或 `nonheap`。  
`pool` 維度的數值可以是 `Tenured Gen`、`Compress Class Space`、`Survivor Space`、`Eden Space`、`Code Cache` 或 `Metaspace`。

**Amazon EKS 和 Kubernetes 叢集上的 Tomcat/JMX**

除了上表中的 Java/JMX 指標之外，也會收集 Tomcat 工作負載的下列指標。


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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**


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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、區域  | 
|  `jvm_memory_pool_bytes_used` |  `ClusterName`、TaskDefinitionFamily、集區  | 

**注意**  
`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 工作負載的下列指標。


| 指標名稱 | 維度 | 
| --- | --- | 
|  `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)。


| 指標名稱 | 維度 | 可用性 | 
| --- | --- | --- | 
|  `haproxy_backend_bytes_in_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_backend_bytes_out_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_backend_connection_errors_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_backend_connections_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_backend_current_sessions` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_backend_http_responses_total` |  `ClusterName`、`Namespace`、服務、程式碼、後端  | HAProxy Ingress 的所有版本 | 
|  `haproxy_backend_status` |  `ClusterName`、`Namespace`、服務  |  只有 HAProxy Ingress 的 0.10 版或更新版本  | 
|  `haproxy_backend_up` |  `ClusterName`、`Namespace`、服務  |  只有 HAProxy Ingress 的 0.10 版  | 
|  `haproxy_frontend_bytes_in_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_frontend_bytes_out_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_frontend_connections_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_frontend_current_sessions` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_frontend_http_requests_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_frontend_http_responses_total` |  `ClusterName`、`Namespace`、服務、程式碼、前端  | HAProxy Ingress 的所有版本 | 
|  `haproxy_frontend_request_errors_total` |  `ClusterName`、`Namespace`、服務  | HAProxy Ingress 的所有版本 | 
|  `haproxy_frontend_requests_denied_total` |  `ClusterName`、`Namespace`、服務  | 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、JavaA/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. 在導覽窗格中，選擇 **Performance Monitoring (效能監控)**。

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. 選擇 **Create Dashboard (建立儀表板)**。輸入新儀表板的名稱，然後選擇 **Create dashboard (建立儀表板)**。

1. 在 **Add to this dashboard (新增至此儀表板)** 中，選擇 **Cancel (取消)**。

1. 選擇 **Actions (動作)**、**View/edit sources (檢視/編輯來源)**。

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. 選擇 **Update (更新)**、**Save dashboard (儲存儀表板)**。

# 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`或 ，將 CloudWatch 代理程式變更為偵錯模式`cwagent-ecs-prometheus-metric-for-awsvpc.yaml`。接著儲存檔案。

```
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 任務定義數目。
+ **Latency** (延遲) – 服務探索週期所需的時間。

檢查 `ExporterDiscoveredTargetCount` 的數值，查看已搜索到 Prometheus 目標是否符合您的期望。如果沒有，可能的原因如下：
+ ECS 服務探索的組態可能不符合應用程式的設定。對於 Docker 型標籤服務探索，您的目標容器可能沒有在 CloudWatch 代理程式中設定必要的 Docker 標籤來自動發現它們。對於 ECS 任務定義 ARN 規則表達式型服務探索，CloudWatch 代理程式中的 regex 設定可能與應用程式的任務定義不相符。
+ CloudWatch 代理程式的 ECS 任務角色可能沒有擷取 ECS 任務中繼資料的許可。檢查 CloudWatch 代理程式是否已授與下列唯讀許可：
  + `ec2:DescribeInstances`
  + `ecs:ListTasks`
  + `ecs:DescribeContainerInstances`
  + `ecs:DescribeTasks`
  + `ecs:DescribeTaskDefinition`

**步驟 3：檢查網路連線和 ECS 任務角色政策**

如果仍然沒有任何日誌事件傳送至目標 CloudWatch Logs 日誌群組，即使 `Exporter_DiscoveredTargetCount` 的數值表示有已搜索到 Prometheus 目標，而這可能由以下其中一項造成的：
+ 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* 取代為 pod 的完整名稱，即以 `cw-agent-prometheus` 為開頭的名稱。

```
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. 以下列查詢取代搜尋查詢表達式，然後選擇 **Run query (執行查詢)**

   ```
   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. 以下列查詢取代搜尋查詢表達式，然後選擇 **Run query (執行查詢)**

   ```
   fields @timestamp, @message | sort @timestamp desc | limit 20
   ```

## 記錄日誌已捨棄 Prometheus 指標
<a name="ContainerInsights-Prometheus-troubleshooting-droppedmetrics"></a>

此版本不會收集長條圖類型的 Prometheus 指標。您可以使用 CloudWatch 代理程式來檢查是否有任何 Prometheus 指標是因為屬於長條圖指標而遭到捨棄。您也可以記錄前 500 個因為是長條圖指標而遭到捨棄且未傳送到 CloudWatch 的 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 指標都會在名為 **/aws/containerinsights/cluster-name/Prometheus** 的日誌群組下的日誌串流 **kubernetes-pod-appmesh-envoy** 中擷取為 CloudWatch Logs 事件。

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