

# 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 워크로드 및 소스를 스크레이프하고 가져오도록 에이전트를 구성할 수도 있습니다.

다음 단계에 따라 Prometheus 지표 수집용 CloudWatch 에이전트를 설치하기 전에 먼저, Amazon EKS에서 클러스터가 실행 중이거나 Amazon EC2 인스턴스에서 Kubernetes 클러스터가 실행 중이어야 합니다.

**VPC 보안 그룹 요구 사항**

Prometheus 워크로드의 보안 그룹 수신 규칙은 프라이빗 IP로 Prometheus 지표를 스크레이프하기 위해 CloudWatch 에이전트에 대한 Prometheus 포트를 열어야 합니다.

CloudWatch 에이전트의 보안 그룹 송신 규칙은 CloudWatch 에이전트가 프라이빗 IP로 Prometheus 워크로드의 포트에 연결할 수 있도록 허용해야 합니다.

**Topics**
+ [Amazon EKS 및 Kubernetes 클러스터에 Prometheus 지표 수집과 함께 CloudWatch 에이전트 설치](#ContainerInsights-Prometheus-Setup-roles)
+ [추가 Prometheus 소스 스크레이핑 및 해당 지표 가져오기](ContainerInsights-Prometheus-Setup-configure.md)
+ [(선택 사항) Prometheus 지표 테스트를 위한 컨테이너화된 Amazon EKS 워크로드 샘플 설정](ContainerInsights-Prometheus-Sample-Workloads.md)

## Amazon EKS 및 Kubernetes 클러스터에 Prometheus 지표 수집과 함께 CloudWatch 에이전트 설치
<a name="ContainerInsights-Prometheus-Setup-roles"></a>

이 단원에서는 Amazon EKS 또는 Kubernetes를 실행 중인 클러스터에서 Prometheus 모니터링이 포함된 CloudWatch 에이전트를 설정하는 방법을 설명합니다. 이렇게 에이전트를 설정하면 에이전트가 해당 클러스터에서 실행 중인 다음 워크로드에 대한 지표를 자동으로 스크레이프하고 가져옵니다.
+ AWS App Mesh
+ NGINX
+ Memcached
+ Java/JMX
+ HAProxy
+ Fluent Bit

추가 Prometheus 워크로드 및 소스를 스크레이프하고 가져오도록 에이전트를 구성할 수도 있습니다.

다음 단계에 따라 Prometheus 지표 수집용 CloudWatch 에이전트를 설치하기 전에 먼저, Amazon EKS에서 클러스터가 실행 중이거나 Amazon EC2 인스턴스에서 Kubernetes 클러스터가 실행 중이어야 합니다.

**VPC 보안 그룹 요구 사항**

Prometheus 워크로드의 보안 그룹 수신 규칙은 프라이빗 IP로 Prometheus 지표를 스크레이프하기 위해 CloudWatch 에이전트에 대한 Prometheus 포트를 열어야 합니다.

CloudWatch 에이전트의 보안 그룹 송신 규칙은 CloudWatch 에이전트가 프라이빗 IP로 Prometheus 워크로드의 포트에 연결할 수 있도록 허용해야 합니다.

**Topics**
+ [IAM 역할 설정](#ContainerInsights-Prometheus-Setup-roles)
+ [Prometheus 지표를 수집하기 위한 CloudWatch 에이전트 설치](#ContainerInsights-Prometheus-Setup-install-agent)

### IAM 역할 설정
<a name="ContainerInsights-Prometheus-Setup-roles"></a>

첫 번째 단계는 클러스터에 필요한 IAM 역할을 설정하는 것입니다. 다음과 같은 두 가지 방법으로 설정할 수 있습니다.
+ **‘서비스 역할’이라고도 하는 서비스 계정의 IAM 역할을 설정합니다. 이 방법은 EC2 시작 유형과 Fargate 시작 유형 모두에 적용됩니다.
+ 클러스터에 사용되는 IAM 역할에 IAM 정책을 추가합니다. 이는 EC2 시작 유형에만 적용됩니다.

**서비스 역할 설정(EC2 시작 유형 및 Fargate 시작 유형)**

서비스 역할을 설정하려면 다음 명령을 입력합니다. *MyCluster*를 클러스터 이름으로 바꿉니다.

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

**노드 그룹의 IAM 역할에 정책 추가(EC2 시작 유형만 해당)**

**Prometheus 지원을 위해 노드 그룹에서 IAM 정책을 설정하려면**

1. [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/)에서 Amazon EC2 콘솔을 엽니다.

1. 탐색 창에서 **인스턴스**를 선택합니다.

1. 클러스터에 대한 IAM 역할 이름의 접두사를 찾아야 합니다. 이렇게 하려면 클러스터에 있는 인스턴스 이름 옆의 확인란을 선택하고 **작업**, **보안**, **IAM 역할 수정**을 선택합니다. 그런 다음, `eksctl-dev303-workshop-nodegroup`과 같은 IAM 역할의 접두사를 복사합니다.

1. IAM 콘솔([https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/))을 엽니다.

1. 탐색 창에서 **역할**을 선택합니다.

1. 검색 상자를 사용하여 이 절차의 앞부분에서 복사한 접두사를 찾은 다음 해당 역할을 선택합니다.

1. **정책 연결**을 선택합니다.

1. 검색 상자를 사용하여 **CloudWatchAgentServerPolicy**를 찾습니다. **CloudWatchAgentServerPolicy** 옆의 확인란을 선택하고 **정책 연결**을 선택합니다.

### Prometheus 지표를 수집하기 위한 CloudWatch 에이전트 설치
<a name="ContainerInsights-Prometheus-Setup-install-agent"></a>

지표를 수집하려면 클러스터에 CloudWatch 에이전트를 설치해야 합니다. Amazon EKS 클러스터와 Kubernetes 클러스터의 에이전트 설치 방법은 다릅니다.

**Prometheus가 지원되는 CloudWatch 에이전트의 이전 버전 삭제**

클러스터에 Prometheus가 지원되는 CloudWatch 에이전트 버전을 이미 설치한 경우 다음 명령을 입력하여 해당 버전을 삭제해야 합니다. 이는 Prometheus가 지원되는 이전 버전의 에이전트에만 필요합니다. Prometheus가 지원되지 않는 Container Insights를 사용하는 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 에이전트 포드가 포함되어 있다면 에이전트가 실행 중이며 Prometheus 지표를 수집하고 있는 것입니다. 기본적으로 CloudWatch 에이전트는 1분마다 App Mesh, NGINX, Memcached, Java/JMX, HAProxy에 대한 지표를 수집합니다. 지표에 대한 자세한 내용은 [CloudWatch 에이전트가 수집하는 Prometheus 지표](ContainerInsights-Prometheus-metrics.md) 단원을 참조하세요. CloudWatch에서 Prometheus 지표를 확인하는 방법에 대한 지침은 [Prometheus 지표 보기](ContainerInsights-Prometheus-viewmetrics.md) 단원을 참조하세요.

또한 다른 Prometheus Exporter에서 지표를 수집하도록 CloudWatch 에이전트를 구성할 수도 있습니다. 자세한 내용은 [추가 Prometheus 소스 스크레이핑 및 해당 지표 가져오기](ContainerInsights-Prometheus-Setup-configure.md) 섹션을 참조하세요.

# 추가 Prometheus 소스 스크레이핑 및 해당 지표 가져오기
<a name="ContainerInsights-Prometheus-Setup-configure"></a>

Prometheus 모니터링이 포함된 CloudWatch 에이전트는 Prometheus 지표를 스크레이프하는 데 두 가지 구성이 필요합니다. 하나는 Prometheus 설명서의 [<scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config)에 설명된 표준 Prometheus 구성을 위한 것입니다. 다른 하나는 CloudWatch 에이전트 구성을 위한 것입니다.

Amazon EKS 클러스터에서 구성은 `prometheus-eks.yaml`(EC2 시작 유형의 경우) 또는 `prometheus-eks-fargate.yaml`(Fargate 시작 유형의 경우)에 다음과 같은 두 config 맵으로 정의됩니다.
+ `name: prometheus-config` 섹션에는 Prometheus 스크레이핑 설정이 포함되어 있습니다.
+ `name: prometheus-cwagentconfig` 섹션에는 CloudWatch 에이전트에 대한 구성이 포함되어 있습니다. 이 섹션을 사용하여 CloudWatch가 Prometheus 지표를 수집하는 방법을 구성할 수 있습니다. 예를 들어 CloudWatch에 가져올 지표를 지정하고 해당 지표의 측정기준을 정의합니다.

Amazon EC2 인스턴스에서 실행되는 Kubernetes 클러스터에서 구성은 `prometheus-k8s.yaml` YAML 파일에 다음과 같은 두 config 맵으로 정의됩니다.
+ `name: prometheus-config` 섹션에는 Prometheus 스크레이핑 설정이 포함되어 있습니다.
+ `name: prometheus-cwagentconfig` 섹션에는 CloudWatch 에이전트에 대한 구성이 포함되어 있습니다.

추가 Prometheus 지표 소스를 스크레이프하고 해당 지표를 CloudWatch에 가져오려면 Prometheus 스크레이프 구성과 CloudWatch 에이전트 구성을 모두 수정한 다음, 업데이트된 구성으로 에이전트를 다시 배포합니다.

**VPC 보안 그룹 요구 사항**

Prometheus 워크로드의 보안 그룹 수신 규칙은 프라이빗 IP로 Prometheus 지표를 스크레이프하기 위해 CloudWatch 에이전트에 대한 Prometheus 포트를 열어야 합니다.

CloudWatch 에이전트의 보안 그룹 송신 규칙은 CloudWatch 에이전트가 프라이빗 IP로 Prometheus 워크로드의 포트에 연결할 수 있도록 허용해야 합니다.

## Prometheus 스크레이프 구성
<a name="ContainerInsights-Prometheus-Setup-config-global"></a>

CloudWatch 에이전트는 Prometheus 설명서의 [ <scrape\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config)에 설명된 대로 표준 Prometheus 스크레이프 구성을 지원합니다. 이 섹션을 편집하여 이 파일에 이미 있는 구성을 업데이트하고 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/**라는 로그 스트림에 전송됩니다.

새 스크레이핑 대상을 추가하려면 YAML 파일의 `scrape_configs` 섹션에 새 `job_name` 섹션을 추가하고 에이전트를 다시 시작합니다. 이 프로세스의 예는 [새로운 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는 Amazon EKS 및 Kubernetes 클러스터의 로그에 **/aws/containerinsights/*cluster\$1name*/prometheus**를 사용합니다.
+ **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 Exporter를 검색하는 빈도입니다. 숫자와 단위 접미사를 지정합니다. 예를 들어 1분마다 한 번의 경우 `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`은 Prometheus 지표에 대한 컨테이너 포트를 지정하는 컨테이너의 Docker 레이블 이름입니다. 기본값은 `ECS_PROMETHEUS_EXPORTER_PORT`입니다. 컨테이너에 이 Docker 레이블이 없다면 CloudWatch 에이전트는 이 필드를 건너뜁니다.
    + `sd_metrics_path_label`은 Prometheus 지표 경로를 지정하는 컨테이너의 Docker 레이블 이름입니다. 기본값은 `ECS_PROMETHEUS_METRICS_PATH`입니다. 컨테이너에 이 도커 레이블이 없다면 에이전트는 기본 경로 `/metrics`를 가정합니다.
    + `sd_job_name_label`은 Prometheus 스크레이프 작업 이름을 지정하는 컨테이너의 Docker 레이블 이름입니다. 기본값은 `job`입니다. 컨테이너에 이 Docker 레이블이 없다면 CloudWatch 에이전트는 Prometheus 스크레이프 구성의 작업 이름을 사용합니다.
  + `task_definition_list`는 태스크 정의 기반 서비스 검색의 구성을 지정하는 데 사용할 수 있는 선택적 섹션입니다. 이 섹션을 생략하면 태스크 정의 기반 검색이 사용되지 않습니다. 이 섹션에는 다음 필드가 포함될 수 있습니다.
    + `sd_task_definition_arn_pattern`은 검색할 Amazon ECS 태스크 정의를 지정하는 데 사용할 패턴입니다. 이는 정규 표현식입니다.
    + `sd_metrics_ports`는 Prometheus 지표에 대한 containerPort를 나열합니다. containerPort를 세미콜론으로 구분합니다.
    + `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`는 여러 `source_labels`가 지정된 경우 ` label_matcher` 줄에 사용할 구분 기호를 지정합니다. 기본값은 `;`입니다. 다음 예에서 `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로 가져오는 방법을 보여 줍니다.
+ CloudWatch 에이전트 YAML 파일에 Kubernetes API 서버의 Prometheus 스크레이핑 구성 추가
+ 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 -
   ```

이 작업을 완료하면 **kubernetes-apiservers**라는 새 로그 스트림이 **/aws/containerinsights/*cluster\$1name*/prometheus** 로그 그룹에 나타납니다. 이 로그 스트림은 다음과 같은 임베디드 지표 형식 정의가 있는 로그 이벤트를 포함해야 합니다.

```
{
   "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"
}
```

CloudWatch 콘솔의 **ContainerInsights/Prometheus** 네임스페이스에서 지표를 볼 수 있습니다. 또한 선택적으로 Prometheus Kubernetes API 서버 지표에 대한 CloudWatch 대시보드를 생성할 수도 있습니다.

### (선택 사항) Kubernetes API 서버 지표에 대한 대시보드 생성
<a name="ContainerInsights-Prometheus-Setup-KPI-dashboard"></a>

대시보드에서 Kubernetes API 서버 지표를 보려면 먼저, 이전 단원의 단계를 완료하여 CloudWatch에서 이러한 지표 수집을 시작해야 합니다.

**Kubernetes API 서버 지표에 대한 대시보드를 생성하려면**

1. [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)에서 CloudWatch 콘솔을 엽니다.

1. 올바른 AWS 리전을 선택했는지 확인합니다.

1. 탐색 창에서 **대시보드**를 선택합니다.

1. **대시보드 생성**을 선택합니다. 새 대시보드의 이름을 입력하고 **대시보드 생성**을 선택합니다.

1. **이 대시보드에 추가**에서 **취소**를 선택합니다.

1. **작업**, **소스 보기/편집**을 선택합니다.

1. [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)라는 JSON 파일을 다운로드합니다.

1. 텍스트 편집기로 다운로드한 JSON 파일을 열고, 다음과 같이 변경합니다.
   + 모든 `{{YOUR_CLUSTER_NAME}}` 문자열을 정확한 클러스터 이름으로 바꿉니다. 텍스트 앞이나 뒤에 공백을 추가하지 않도록 하세요.
   + 모든 `{{YOUR_AWS_REGION}}` 문자열을 지표가 수집되는 리전의 이름으로 바꿉니다. 예: `us-west-2`. 텍스트 앞이나 뒤에 공백을 추가하지 않도록 하세요.

1. JSON blob 전체를 복사하여 CloudWatch 콘솔의 텍스트 상자에 붙여넣어 이미 상자에 있는 내용을 바꿉니다.

1. **업데이트**, **대시보드 저장**을 선택합니다.

# (선택 사항) Prometheus 지표 테스트를 위한 컨테이너화된 Amazon EKS 워크로드 샘플 설정
<a name="ContainerInsights-Prometheus-Sample-Workloads"></a>

CloudWatch Container Insights에서 Prometheus 지표 지원을 테스트하기 위해 다음과 같은 컨테이너화된 워크로드 중 하나 이상을 설정할 수 있습니다. Prometheus가 지원되는 CloudWatch 에이전트는 이러한 각 워크로드에서 지표를 자동으로 수집합니다. 기본적으로 수집되는 지표를 보려면 [CloudWatch 에이전트가 수집하는 Prometheus 지표](ContainerInsights-Prometheus-metrics.md) 단원을 참조하세요.

이러한 워크로드를 설치하려면 다음 명령을 입력하여 Helm 3.x를 설치해야 합니다.

```
brew install helm
```

자세한 내용은 [Helm](https://helm.sh)을 참조하세요.

**Topics**
+ [Amazon EKS 및 Kubernetes의 AWS App Mesh 샘플 워크로드 설정](ContainerInsights-Prometheus-Sample-Workloads-appmesh.md)
+ [Amazon EKS 및 Kubernetes에서 샘플 트래픽이 포함된 NGINX 설정](ContainerInsights-Prometheus-Sample-Workloads-nginx.md)
+ [Amazon EKS 및 Kubernetes에서 지표 익스포터가 포함된 Memcached 설정](ContainerInsights-Prometheus-Sample-Workloads-memcached.md)
+ [Amazon EKS 및 Kubernetes에서 Java/JMX 샘플 워크로드 설정](ContainerInsights-Prometheus-Sample-Workloads-javajmx.md)
+ [Amazon EKS 및 Kubernetes에서 지표 익스포터가 포함된 HAProxy 설정](ContainerInsights-Prometheus-Sample-Workloads-haproxy.md)
+ [새로운 Prometheus 스크레이핑 대상을 추가하는 자습서: Amazon EKS 및 Kubernetes 클러스터의 Redis OSS](ContainerInsights-Prometheus-Setup-redis-eks.md)

# Amazon EKS 및 Kubernetes의 AWS App Mesh 샘플 워크로드 설정
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh"></a>

CloudWatch Container Insights의 Prometheus 지원은 AWS App Mesh를 지원합니다. 다음 단원에서는 App Mesh를 설정하는 방법을 설명합니다.

**Topics**
+ [EC2 시작 유형의 Amazon EKS 클러스터 또는 Kubernetes 클러스터에서 AWS App Mesh 샘플 워크로드 설정](ContainerInsights-Prometheus-Sample-Workloads-appmesh-EKS.md)
+ [Fargate 시작 유형의 Amazon EKS 클러스터에서 AWS App Mesh 샘플 워크로드 설정](ContainerInsights-Prometheus-Sample-Workloads-appmesh-Fargate.md)

# EC2 시작 유형의 Amazon EKS 클러스터 또는 Kubernetes 클러스터에서 AWS App Mesh 샘플 워크로드 설정
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-EKS"></a>

EC2 시작 유형의 Amazon EKS를 실행하는 클러스터 또는 Kubernetes 클러스터에서 App Mesh를 설정할 경우 다음 지침을 따르세요.

## IAM 권한 구성
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-iam"></a>

Amazon EKS 또는 Kubernetes 노드 그룹의 IAM 역할에 **AWSAppMeshFullAccess** 정책을 추가해야 합니다. 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 포드를 시작하여 트래픽을 생성합니다.

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

1. HTTP 헤더를 변경하여 다양한 엔드포인트를 curl합니다. 다음과 같이 curl 명령을 여러 번 실행합니다.

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

1. [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)에서 CloudWatch 콘솔을 엽니다.

1. 클러스터가 실행되고 있는 AWS 리전에서 왼쪽 탐색 창의 [**지표(Metrics)**]를 선택합니다. 지표는 **ContainerInsights/Prometheus** 네임스페이스에 있습니다.

1. CloudWatch Logs 이벤트를 보려면 탐색 창에서 [**로그 그룹(Log groups)**]을 선택합니다. 이벤트는 로그 그룹 ` /aws/containerinsights/your_cluster_name/prometheus `의 로그 스트림 `kubernetes-pod-appmesh-envoy`에 있습니다.

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

Fargate 시작 유형의 Amazon EKS를 실행하는 클러스터에서 App Mesh를 설정할 경우 다음 지침을 따르세요.

## IAM 권한 구성
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh--fargate-iam"></a>

IAM 권한을 설정하려면 다음 명령을 입력합니다. *MyCluster*를 클러스터 이름으로 바꿉니다.

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

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

App Mesh Kubernetes 컨트롤러를 설치하려면 [App Mesh 컨트롤러](https://github.com/aws/eks-charts/tree/master/stable/appmesh-controller#app-mesh-controller)의 지침을 따르세요. Fargate 시작 유형의 Amazon EKS에 대한 지침을 따라야 합니다.

## 샘플 애플리케이션 설치
<a name="ContainerInsights-Prometheus-Sample-Workloads-appmesh-fargate-application"></a>

[aws-app-mesh-examples](https://github.com/aws/aws-app-mesh-examples)에는 여러 Kubernetes App Mesh 시연이 포함되어 있습니다. 이 튜토리얼에서는 Fargate 시작 유형의 Amazon EKS 클러스터에서 작동하는 샘플 컬러 애플리케이션을 설치합니다.

**샘플 App Mesh 애플리케이션을 사용하여 Container Insights를 테스트하려면**

1. 다음 지침에 따라 애플리케이션을 설치합니다. [https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-fargate](https://github.com/aws/aws-app-mesh-examples/tree/main/walkthroughs/howto-k8s-fargate) 

   해당 지침에서는 올바른 Fargate 프로파일을 사용하여 새 클러스터를 생성한다고 가정합니다. 이미 설정한 Amazon EKS 클러스터를 사용하려는 경우 다음 명령을 사용하여 해당 클러스터를 이 데모에 맞게 설정할 수 있습니다. *MyCluster*를 클러스터 이름으로 바꿉니다.

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

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

1. 다음과 같이 프런트 애플리케이션 배포를 포트 포워딩합니다.

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

1. 다음과 같이 프런트 앱을 curl합니다.

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

1. [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)에서 CloudWatch 콘솔을 엽니다.

1. 클러스터가 실행되고 있는 AWS 리전에서 왼쪽 탐색 창의 [**지표(Metrics)**]를 선택합니다. 지표는 **ContainerInsights/Prometheus** 네임스페이스에 있습니다.

1. CloudWatch Logs 이벤트를 보려면 탐색 창에서 [**로그 그룹(Log groups)**]을 선택합니다. 이벤트는 로그 그룹 ` /aws/containerinsights/your_cluster_name/prometheus `의 로그 스트림 `kubernetes-pod-appmesh-envoy`에 있습니다.

## 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는 로드 밸런서 및 역방향 프록시로도 사용할 수 있는 웹 서버입니다. Kubernetes가 진입에 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. 다음 명령을 입력하여 세 개의 포드가 모두 `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
```

**Container Insights Prometheus 지원을 테스트하기 위해 지표 익스포터와 함께 memcached를 설치하려면**

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는 JMX mBeans를 스크레이프하여 노출할 수 있는 공식 Prometheus 익스포터입니다. 자세한 내용은 [prometheus/jmx\$1exporter](https://github.com/prometheus/jmx_exporter)를 참조하세요.

Container Insights는 JMX Exporter를 사용하여 Java Virtual Machine(JVM), Java 및 Tomcat(Catalina)에서 사전 정의된 Prometheus 지표를 수집할 수 있습니다.

## 기본 Prometheus 스크레이프 구성
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-default"></a>

기본적으로 Prometheus가 지원되는 CloudWatch 에이전트는 Amazon EKS 또는 Kubernetes 클러스터에 있는 각 포드의 `http://CLUSTER_IP:9404/metrics`에서 Java/JMX Prometheus 지표를 스크레이프합니다. 이는 Prometheus `kubernetes_sd_config`의 `role: pod` 검색에 의해 수행됩니다. 9404는 Prometheus에서 JMX Exporter에 할당한 기본 포트입니다. `role: pod` 검색에 대한 자세한 내용은 [포드](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#pod)를 참조하세요. 지표를 다른 포트 또는 metrics\$1path에 노출하도록 JMX Exporter를 구성할 수 있습니다. 포트 또는 경로를 변경하는 경우 CloudWatch 에이전트 config 맵의 기본 jmx scrape\$1config를 업데이트하세요. 다음 명령을 실행하여 현재 CloudWatch 에이전트 Prometheus 구성을 가져옵니다.

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

변경할 필드는 다음 예제에서 강조 표시된 대로 `/metrics` 및 `regex: '.*:9404$'` 필드입니다.

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

## 기타 Prometheus 스크레이프 구성
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-other"></a>

Kubernetes Service의 Java/JMX Prometheus Exporter가 있는 포드 세트에서 실행 중인 애플리케이션을 노출하는 경우 Prometheus `kubernetes_sd_config`의 `role: service` 검색 또는 `role: endpoint` 검색을 사용하도록 전환할 수도 있습니다. 이러한 검색 방법에 대한 자세한 내용은 [서비스](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#service), [엔드포인트](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#endpoints), [<kubernetes\$1sd\$1config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#kubernetes_sd_config)를 참조하세요.

이러한 두 가지 서비스 검색 모드는 더 많은 메타 레이블을 제공하므로 CloudWatch 지표 측정기준을 구축하는 데 유용할 수 있습니다. 예를 들어 `__meta_kubernetes_service_name`의 레이블을 `Service`로 다시 지정하고 이를 지표의 측정기준에 포함할 수 있습니다. CloudWatch 지표 및 해당 측정기준의 사용자 지정에 대한 자세한 내용은 [Prometheus에 대한 CloudWatch 에이전트 구성](ContainerInsights-Prometheus-Setup-configure-ECS.md#ContainerInsights-Prometheus-Setup-cw-agent-config) 단원을 참조하세요.

## JMX Exporter가 포함된 Docker 이미지
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-docker"></a>

다음으로, Docker 이미지를 구축합니다. 다음 단원에서는 두 가지 Dockerfile 예를 제공합니다.

이미지를 구축한 경우 Amazon EKS 또는 Kubernetes에 로드한 후 다음 명령을 실행하여 Prometheus 지표가 포트 9404에서 `JMX_EXPORTER`에 의해 노출되는지 확인합니다. *\$1JAR\$1SAMPLE\$1TRAFFIC\$1POD*를 실행 중인 포드 이름으로 바꾸고 *\$1JAR\$1SAMPLE\$1TRAFFIC\$1NAMESPACE*를 애플리케이션 네임스페이스로 바꿉니다.

Fargate 시작 유형의 클러스터에서 JMX Exporter를 실행할 경우 이 절차의 단계를 수행하기 전에 먼저, Fargate 프로파일도 설정해야 합니다. 프로파일을 설정하려면 다음 명령을 입력합니다. *MyCluster*를 클러스터 이름으로 바꿉니다.

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

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

## 예: Prometheus 지표가 있는 Apache Tomcat Docker 이미지
<a name="ContainerInsights-Prometheus-Sample-Workloads-javajmx-tomcat"></a>

Apache Tomcat 서버는 기본적으로 JMX mBeans를 노출합니다. JMX Exporter를 Tomcat과 통합하여 JMX mBeans를 Prometheus 지표로 노출할 수 있습니다. 다음 Dockerfile 예는 테스트 이미지를 구축하는 단계를 보여 줍니다.

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

RUN mkdir -p /opt/jmx_exporter

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

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

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

다음 목록은 이 Dockerfile에 있는 4개의 `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를 시작하고 localhost의 포트 9404에 Prometheus 지표를 노출하는 Tomcat 시작 스크립트입니다. 또한 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 application.war는 Tomcat에 의해 로드될 웹 애플리케이션 `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에 있는 4개의 `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 인큐베이터 리포지토리를 추가합니다.

   ```
   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 License 라이선스)는 지정된 포트(기본값: 0.0.0.0:9121)에서 Redis OSS Prometheus 지표를 노출하는 데 사용됩니다. 자세한 내용은 [redis\$1exporter](https://github.com/oliver006/redis_exporter)를 참조하세요.

이 튜토리얼에서는 다음과 같은 두 Docker Hub 리포지토리의 Docker 이미지를 사용합니다.
+ [ redis](https://hub.docker.com/_/redis?tab=description)
+ [ redis\$1exporter](https://hub.docker.com/r/oliver006/redis_exporter)

**Prometheus 지표를 노출하는 샘플 Redis OSS 워크로드를 설치하는 방법**

1. 샘플 Redis OSS 워크로드의 네임스페이스를 설정합니다.

   ```
   REDIS_NAMESPACE=redis-sample
   ```

1. Fargate 시작 유형의 클러스터에서 Redis OSS를 실행하는 경우 Fargate 프로파일을 설정해야 합니다. 프로파일을 설정하려면 다음 명령을 입력합니다. *MyCluster*를 클러스터 이름으로 바꿉니다.

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

1. 다음 명령을 입력하여 샘플 Redis OSS 워크로드를 설치합니다.

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

1. 설치에는 포트 9121에서 Redis OSS Prometheus 지표를 노출하는 `my-redis-metrics`라는 서비스가 포함되어 있습니다. 다음 명령을 입력하여 서비스 세부 정보를 가져옵니다.

   ```
   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`\$1`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" \
   ```