

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

# 適用於 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\_cluster\_name}}/prometheus** 中。