適用於 Amazon ECS 叢集的範例 NGINX Plus 工作負載 - Amazon CloudWatch

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

適用於 Amazon ECS 叢集的範例 NGINX Plus 工作負載

NGINX Plus 是 NGINX 的商用版本。您必須擁有授權才能使用。如需詳細資訊,請參閱 NGINX Plus

NGINX Prometheus 匯出工具可以湊集和公開 NGINX 資料作為 Prometheus 指標。此範例會聯合使用匯出工具與 Amazon ECS 的 NGINX Plus 反向代理服務。

有關 NGINX Prometheus 出口商的更多信息,請參閱 Github 上的。 nginx-prometheus-exporter有關 NGINX 反向代理的更多信息,請參閱 Github ecs-nginx-reverse-proxy上的。

支援 Prometheus 的 CloudWatch 代理程式會根據 Amazon ECS 叢集中的服務探索組態抓取 NGINX Plus Prometheus 指標。您可以設定 NGINX Prometheus Exporter 在不同的連接埠或路徑上公開指標。如果您變更通訊埠或路徑,請更新 CloudWatch 代理程式組態檔中的ecs_service_discovery區段。

安裝適用於 Amazon ECS 叢集的 NGINX Plus 反向代理範例工作負載

請遵循這些步驟,安裝 NGINX 反向代理範例工作負載。

建立 Docker 影像

若要為 NGINX Plus 反向代理範例工作負載建立 Docker 影像
  1. 從 NGINX 反向代理軟件庫下載以下文件夾:https://github.com/awslabs/ ecs-nginx-reverse-proxy /樹/主/反向代理/。

  2. 尋找 app 目錄並從該目錄建置一個映像:

    docker build -t web-server-app ./path-to-app-directory
  3. 為 NGINX Plus 建置一個自訂映像。在為 NGINX Plus 建置映像之前,您需要為您授權的 NGINX Plus 獲取名為 nginx-repo.key 的金鑰和 SSL 憑證 nginx-repo.crt。建立目錄,並將您的 nginx-repo.keynginx-repo.crt 檔案存放於其中。

    在您剛才建立的目錄中,建立下列兩個檔案:

    • 含有下列內容的範例 Dockerfile。此 docker 檔案是從 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;"]
    • 一個nginx.conf文件,從修改 https://github.com/awslabs/ ecs-nginx-reverse-proxy /樹/主/反向代理/ nginx

      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; } } }
  4. 從新目錄中的檔案建置映像:

    docker build -t nginx-plus-reverse-proxy ./path-to-your-directory
  5. 將您的新映像上傳至映像儲存庫以供日後使用。

建立任務定義,以在 Amazon ECS 中執行 NGINX Plus 和 Web 伺服器應用程式

接著,設定任務定義。

此任務定義可以啟用 NGINX Plus Prometheus 指標的收集與匯出。NGINX 容器會追蹤應用程式的輸入,並將該資料公開到連接埠 8080,如 nginx.conf 中所設定。NGINX 普羅米修斯出口商集裝箱抓取這些指標,並將其發佈到端口 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" }
  2. 註冊任務定義:

    aws ecs register-task-definition --cli-input-json file://path-to-your-task-definition-json
  3. 透過輸入以下命令,建立服務以執行任務:

    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 加 Prometheus 指標

最後一步是配置 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
  2. 使用文本編輯器打開文件,然後在部分的value密鑰中找到完整的 CloudWatch 代理程序合併。resource:CWAgentConfigSSMParameter然後,在 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.*" } ],
  3. 在相同的檔案中,在 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$" ] },
  4. 如果您尚未在此叢集中部署 CloudWatch 代理程式,請跳至步驟 8。

    如果您已使用將 CloudWatch 代理程式部署在 Amazon ECS 叢集中 AWS CloudFormation,則可以輸入下列命令來建立變更集:

    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
  5. 請在以下位置開啟 AWS CloudFormation 主控台。 https://console.aws.amazon.com/cloudformation

  6. 啟示新創建的變更集。nginx-plus-scraping-support您應該會看到一個套用至 CW AgentConfig SSM 參數資源的變更。輸入下列命令,執行變更集並重新執行 CloudWatch 代理程式工作:

    aws ecs update-service --cluster $ECS_CLUSTER_NAME \ --desired-count 0 \ --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \ --region $AWS_REGION
  7. 請等候約 10 秒鐘,然後輸入下列命令。

    aws ecs update-service --cluster $ECS_CLUSTER_NAME \ --desired-count 1 \ --service cwagent-prometheus-replica-service-EC2-$ECS_NETWORK_MODE \ --region $AWS_REGION
  8. 如果您是第一次在叢集上使用 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 指標和日誌

您現在可以檢視收集的 NGINX Plus 指標。

若要檢視範例 NGINX 工作負載的指標
  1. 請在以下位置開啟 CloudWatch 主控台。 https://console.aws.amazon.com/cloudwatch/

  2. 在執行叢集的區域中,在左側的導覽窗格中選擇 Metrics (指標)。找到 ContainerInsights/Prometheus 命名空間以查看指標。

  3. 若要查看記 CloudWatch 錄事件,請在導覽窗格中選擇 [記錄群組]。這些事件位於記錄檔資料流中的記錄檔群組 /aws/容器洞量/的 _cluster_name/prometheus 中。nginx-plus-prometheus-exporter