使用 為 Fargate 建立 Amazon ECS Linux 任務 AWS CLI - Amazon Elastic Container Service

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

使用 為 Fargate 建立 Amazon ECS Linux 任務 AWS CLI

以下步驟會協助您使用 AWS CLI在 Amazon ECS 中設定叢集、註冊任務定義、執行 Linux 任務,以及執行其他常見案例。使用 AWS CLI的最新版本。如需有關如何升級至最新版本的詳細資訊,請參閱 Installing or updating to the latest version of the AWS CLI

注意

您可以使用雙堆疊服務端點,透過 IPv4 和 IPv6 AWS CLI從 、 SDKs 和 Amazon ECS API 與 Amazon ECS 互動。如需詳細資訊,請參閱使用 Amazon ECS 雙堆疊端點

先決條件

本教學課程假設已完成下列先決條件。

  • AWS CLI 已安裝並設定最新版本的 。如需安裝或升級 AWS CLI、安裝或更新至最新版本 AWS CLI的詳細資訊。

  • 已完成「設定以使用 Amazon ECS。」中的步驟。

  • 您的 IAM 使用者擁有 AmazonECS_FullAccess IAM 政策範例中指定的所需許可。

  • 您已建立 VPC 和安全群組。本教學課程使用託管於 Amazon ECR Public 的容器映像,因此任務必須有網際網路連線。若要將網際網路的路由提供給任務,請使用下列其中一個選項。

    • 透過具有彈性 IP 地址的 NAT 閘道使用私有子網路。

    • 使用公有子網路,然後將公有 IP 地址指派給任務。

    如需詳細資訊,請參閱建立 Virtual Private Cloud

    如需有關安全群組和規則的資訊,請參閱《Amazon Virtual Private Cloud 使用者指南》中的 VPC 的預設安全群組規則範例

  • 如果您使用私有子網路遵循本教學課程,則可以使用 Amazon ECS Exec 直接與您的容器互動並測試部署。您必須建立任務 IAM 角色才能使用 ECS Exec。如需有關任務 IAM 角色及其他先決條件的詳細資訊,請參閱使用 Amazon ECS Exec 監控 Amazon ECS 容器

  • (選用) AWS CloudShell 是一種工具,可為客戶提供命令列,而不需要建立自己的 EC2 執行個體。如需詳細資訊,請參閱AWS CloudShell 《 使用者指南》中的什麼是 AWS CloudShell?

步驟 1:建立叢集

您的帳戶預設會得到 default 叢集。

注意

使用為您提供之 default 叢集的優點是,您不必在後續的命令中指定 --cluster cluster_name 選項。如果您建立的是自己的叢集,不是預設叢集,您必須在打算對該叢集使用的每個命令中指定 --cluster cluster_name

使用下列命令以唯一的名稱建立您自己的叢集:

aws ecs create-cluster --cluster-name fargate-cluster

輸出:

{ "cluster": { "status": "ACTIVE", "defaultCapacityProviderStrategy": [], "statistics": [], "capacityProviders": [], "tags": [], "clusterName": "fargate-cluster", "settings": [ { "name": "containerInsights", "value": "disabled" } ], "registeredContainerInstancesCount": 0, "pendingTasksCount": 0, "runningTasksCount": 0, "activeServicesCount": 0, "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/fargate-cluster" } }

步驟 2:註冊 Linux 任務定義

您必須先註冊任務定義,才能在您的 ECS 叢集中執行任務。任務定義是分在一組的容器清單。下列範例是使用託管於 Docker Hub 的 httpd 容器映像來建立 PHP Web 應用程式的簡單任務定義。如需可用之任務定義參數的詳細資訊,請參閱「Amazon ECS 任務定義」。在本教學課程中,僅當您在私有子網路中部署任務並希望測試部署時,才需要 taskRoleArn。如 先決條件 中所述,將 taskRoleArn 取代為您為使用 ECS Exec 建立的 IAM 任務角色。

{ "family": "sample-fargate", "networkMode": "awsvpc", "taskRoleArn": "arn:aws:iam::aws_account_id:role/execCommandRole", "containerDefinitions": [ { "name": "fargate-app", "image": "public.ecr.aws/docker/library/httpd:latest", "portMappings": [ { "containerPort": 80, "hostPort": 80, "protocol": "tcp" } ], "essential": true, "entryPoint": [ "sh", "-c" ], "command": [ "/bin/sh -c \"echo '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div></body></html>' > /usr/local/apache2/htdocs/index.html && httpd-foreground\"" ] } ], "requiresCompatibilities": [ "FARGATE" ], "cpu": "256", "memory": "512" }

將任務定義 JSON 儲存為檔案,並使用 --cli-input-json file://path_to_file.json 選項進行傳遞。

將 JSON 檔案用於容器定義中:

aws ecs register-task-definition --cli-input-json file://$HOME/tasks/fargate-task.json

register-task-definition 命令會在完成註冊後傳回任務定義的描述。

步驟 3:列出任務定義

您可以使用 list-task-definitions 命令隨時列出您帳戶的任務定義。這個命令的輸出會顯示 familyrevision 值,可在呼叫 run-taskstart-task 時一起使用。

aws ecs list-task-definitions

輸出:

{ "taskDefinitionArns": [ "arn:aws:ecs:region:aws_account_id:task-definition/sample-fargate:1" ] }

步驟 4:建立服務

為您的帳戶註冊任務之後,您就可以在您的叢集中建立已註冊任務的服務。在此範例中,您將透過在叢集中執行之 sample-fargate:1 任務定義的一個執行個體建立服務。該任務需要網際網路的路由,因此您可透過兩種方法達成。一種方法是,使用透過 NAT 閘道所設定的私有子網路,而該閘道在公有子網路中具有彈性 IP 地址。另一種方法是,使用公有子網路並將公有 IP 地址指派至任務。以下提供這兩種範例。

使用私有子網路的範例。需要 enable-execute-command 選項才能使用 Amazon ECS Exec。

aws ecs create-service --cluster fargate-cluster --service-name fargate-service --task-definition sample-fargate:1 --desired-count 1 --launch-type "FARGATE" --network-configuration "awsvpcConfiguration={subnets=[subnet-abcd1234],securityGroups=[sg-abcd1234]}" --enable-execute-command

使用公有子網路的範例。

aws ecs create-service --cluster fargate-cluster --service-name fargate-service --task-definition sample-fargate:1 --desired-count 1 --launch-type "FARGATE" --network-configuration "awsvpcConfiguration={subnets=[subnet-abcd1234],securityGroups=[sg-abcd1234],assignPublicIp=ENABLED}"

create-service 命令會在完成註冊後傳回任務定義的描述。

步驟 5:列出服務

列出您叢集的服務。您應該會看到您在先前一節所建立的服務。您可以記下這個命令傳回的服務名稱或完整的 ARN,稍後將用以描述服務。

aws ecs list-services --cluster fargate-cluster

輸出:

{ "serviceArns": [ "arn:aws:ecs:region:aws_account_id:service/fargate-cluster/fargate-service" ] }

步驟 6:描述執行中的服務

使用之前擷取的服務名稱來描述服務,以取得任務的詳細資訊。

aws ecs describe-services --cluster fargate-cluster --services fargate-service

如果成功,這會傳回服務失敗和服務的描述。例如,在 services 區段中,您將可以找到部署的相關資訊,例如執行中或擱置中的任務狀態。您也可以找到任務定義、網路組態和時間戳記事件的相關資訊。在失敗區段中,您將可以找到與呼叫相關聯的失敗 (如果有的話) 的相關資訊。如需故障診斷,請參閱服務事件訊息。如需服務描述的詳細資訊,請參閱描述服務

{ "services": [ { "networkConfiguration": { "awsvpcConfiguration": { "subnets": [ "subnet-abcd1234" ], "securityGroups": [ "sg-abcd1234" ], "assignPublicIp": "ENABLED" } }, "launchType": "FARGATE", "enableECSManagedTags": false, "loadBalancers": [], "deploymentController": { "type": "ECS" }, "desiredCount": 1, "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/fargate-cluster", "serviceArn": "arn:aws:ecs:region:aws_account_id:service/fargate-service", "deploymentConfiguration": { "maximumPercent": 200, "minimumHealthyPercent": 100 }, "createdAt": 1692283199.771, "schedulingStrategy": "REPLICA", "placementConstraints": [], "deployments": [ { "status": "PRIMARY", "networkConfiguration": { "awsvpcConfiguration": { "subnets": [ "subnet-abcd1234" ], "securityGroups": [ "sg-abcd1234" ], "assignPublicIp": "ENABLED" } }, "pendingCount": 0, "launchType": "FARGATE", "createdAt": 1692283199.771, "desiredCount": 1, "taskDefinition": "arn:aws:ecs:region:aws_account_id:task-definition/sample-fargate:1", "updatedAt": 1692283199.771, "platformVersion": "1.4.0", "id": "ecs-svc/9223370526043414679", "runningCount": 0 } ], "serviceName": "fargate-service", "events": [ { "message": "(service fargate-service) has started 2 tasks: (task 53c0de40-ea3b-489f-a352-623bf1235f08) (task d0aec985-901b-488f-9fb4-61b991b332a3).", "id": "92b8443e-67fb-4886-880c-07e73383ea83", "createdAt": 1510811841.408 }, { "message": "(service fargate-service) has started 2 tasks: (task b4911bee-7203-4113-99d4-e89ba457c626) (task cc5853e3-6e2d-4678-8312-74f8a7d76474).", "id": "d85c6ec6-a693-43b3-904a-a997e1fc844d", "createdAt": 1510811601.938 }, { "message": "(service fargate-service) has started 2 tasks: (task cba86182-52bf-42d7-9df8-b744699e6cfc) (task f4c1ad74-a5c6-4620-90cf-2aff118df5fc).", "id": "095703e1-0ca3-4379-a7c8-c0f1b8b95ace", "createdAt": 1510811364.691 } ], "runningCount": 0, "status": "ACTIVE", "serviceRegistries": [], "pendingCount": 0, "createdBy": "arn:aws:iam::aws_account_id:user/user_name", "platformVersion": "LATEST", "placementStrategy": [], "propagateTags": "NONE", "roleArn": "arn:aws:iam::aws_account_id:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS", "taskDefinition": "arn:aws:ecs:region:aws_account_id:task-definition/sample-fargate:1" } ], "failures": [] }

步驟 7:測試

使用公有子網路部署的測試任務

描述服務中的任務,以便取得任務的彈性網路介面 (ENI)。

首先,要取得任務 ARN。

aws ecs list-tasks --cluster fargate-cluster --service fargate-service

輸出包含任務 ARN。

{ "taskArns": [ "arn:aws:ecs:us-east-1:123456789012:task/fargate-service/EXAMPLE ] }

描述任務並找到 ENI ID。將任務 ARN 用於 tasks 參數。

aws ecs describe-tasks --cluster fargate-cluster --tasks arn:aws:ecs:us-east-1:123456789012:task/service/EXAMPLE

連接資訊將在輸出中列出。

{ "tasks": [ { "attachments": [ { "id": "d9e7735a-16aa-4128-bc7a-b2d5115029e9", "type": "ElasticNetworkInterface", "status": "ATTACHED", "details": [ { "name": "subnetId", "value": "subnetabcd1234" }, { "name": "networkInterfaceId", "value": "eni-0fa40520aeEXAMPLE" }, ] } … }

描述 ENI 以獲得公有 IP 地址。

aws ec2 describe-network-interfaces --network-interface-id eni-0fa40520aeEXAMPLE

公有 IP 地址會在輸出中。

{ "NetworkInterfaces": [ { "Association": { "IpOwnerId": "amazon", "PublicDnsName": "ec2-34-229-42-222.compute-1.amazonaws.com", "PublicIp": "198.51.100.2" }, … }

在 Web 瀏覽器中輸入公有 IP 地址,然後您應該會看到顯示 Amazon ECS 範例應用程式的網頁。

使用私有子網路部署的測試任務

描述任務並找出 managedAgents,以驗證 ExecuteCommandAgent 是否正在執行。記下 privateIPv4Address 以供稍後使用。

aws ecs describe-tasks --cluster fargate-cluster --tasks arn:aws:ecs:us-east-1:123456789012:task/fargate-service/EXAMPLE

受管代理程式資訊將在輸出中列出。

{ "tasks": [ { "attachments": [ { "id": "d9e7735a-16aa-4128-bc7a-b2d5115029e9", "type": "ElasticNetworkInterface", "status": "ATTACHED", "details": [ { "name": "subnetId", "value": "subnetabcd1234" }, { "name": "networkInterfaceId", "value": "eni-0fa40520aeEXAMPLE" }, { "name": "privateIPv4Address", "value": "10.0.143.156" } ] } ], ... "containers": [ { ... "managedAgents": [ { "lastStartedAt": "2023-08-01T16:10:13.002000+00:00", "name": "ExecuteCommandAgent", "lastStatus": "RUNNING" } ], ... }

驗證 ExecuteCommandAgent 正在執行之後,您可以執行下列命令,以在任務中的容器上執行互動式 Shell。

aws ecs execute-command --cluster fargate-cluster \ --task arn:aws:ecs:us-east-1:123456789012:task/fargate-service/EXAMPLE \ --container fargate-app \ --interactive \ --command "/bin/sh"

互動式 Shell 執行後,執行以下命令來安裝 cURL。

apt update
apt install curl

安裝 cURL 後,使用您先前獲得的私有 IP 地址執行以下命令。

curl 10.0.143.156

您應該會看到相當於 Amazon ECS 範例應用程式網頁的 HTML。

<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head> <body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div> </body> </html>

步驟 8:清除

完成此教學課程時,建議您清除相關聯的資源,以免未使用的資源產生費用。

刪除服務。

aws ecs delete-service --cluster fargate-cluster --service fargate-service --force

刪除叢集。

aws ecs delete-cluster --cluster fargate-cluster