本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 為 EC2 啟動類型建立 Amazon ECS 任務 AWS CLI
以下步驟會協助您使用 AWS CLI在 Amazon ECS 中設定叢集、註冊任務定義、執行任務,以及執行其他常見案例。使用最新版本的 AWS CLI。如需如何升級至最新版本的詳細資訊,請參閱安裝或更新至最新版本的 AWS CLI。
注意
您可以使用雙堆疊服務端點,透過 IPv4 和 IPv6 AWS CLI從 、 SDKs 和 Amazon ECS API 與 Amazon ECS 互動。如需詳細資訊,請參閱使用 Amazon ECS 雙堆疊端點。
主題
先決條件
本教學課程假設已完成下列先決條件:
-
AWS CLI 已安裝並設定最新版本的 。如需安裝或升級 的詳細資訊 AWS CLI,請參閱安裝或更新至最新版本的 AWS CLI。
-
已完成「設定以使用 Amazon ECS。」中的步驟。
-
您的 IAM 使用者具有 IAM AmazonECS_FullAccess 政策範例中指定的必要許可。
-
您已建立要使用的容器執行個體 IAM 角色。如需詳細資訊,請參閱 Amazon ECS 容器執行個體 IAM 角色。
-
您已建立要使用的 VPC。如需詳細資訊,請參閱建立 Virtual Private Cloud。
-
(選用) AWS CloudShell 是一種工具,可為客戶提供命令列,而不需要建立自己的 EC2 執行個體。如需詳細資訊,請參閱AWS CloudShell 《 使用者指南》中的什麼是 AWS CloudShell?。
建立叢集
當您啟動第一個容器執行個體時,您的帳戶預設會得到 default
叢集。
注意
使用為您提供之 default
叢集的優點是,您不必在後續的命令中指定 --cluster
選項。如果您建立的是自己的叢集,不是預設叢集,您必須在打算對該叢集使用的每個命令中指定 cluster_name
--cluster
。cluster_name
使用下列命令以唯一的名稱建立您自己的叢集:
aws ecs create-cluster --cluster-name
MyCluster
輸出:
{
"cluster": {
"clusterName": "MyCluster",
"status": "ACTIVE",
"clusterArn": "arn:aws:ecs:region
:aws_account_id
:cluster/MyCluster"
}
}
使用 Amazon ECS AMI 啟動容器執行個體
容器執行個體是執行 Amazon ECS 容器代理程式並已註冊至叢集的 EC2 執行個體。在本節中,您將使用 ECS 最佳化 AMI 啟動 EC2 執行個體。
使用 啟動容器執行個體 AWS CLI
-
AWS 區域 使用下列命令擷取 的最新 ECS 最佳化 Amazon Linux 2 AMI ID。此命令使用 AWS Systems Manager 參數存放區來取得最新的 ECS 最佳化 AMI ID。AMI 包含預先安裝的 Amazon ECS 容器代理程式和 Docker 執行期。
aws ssm get-parameters --names /aws/service/ecs/optimized-ami/amazon-linux-2/recommended --query 'Parameters[0].Value' --output text | jq -r '.image_id'
輸出:
ami-abcd1234
-
建立安全群組,允許 SSH 存取以管理容器執行個體和 Web 伺服器的 HTTP 存取。
aws ec2 create-security-group --group-name
ecs-tutorial-sg
--description "ECS tutorial security group"輸出:
{ "GroupId": "sg-abcd1234" }
-
執行下列命令,將傳入規則新增至安全群組。
aws ec2 authorize-security-group-ingress --group-id
sg-abcd1234
--protocol tcp --port 80 --cidr 0.0.0.0/0輸出:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-efgh5678", "GroupId": "sg-abcd1234", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIpv4": "0.0.0.0/0" } ] }
安全群組現在允許從指定的 IP 範圍進行 SSH 存取,並從任何地方進行 HTTP 存取。在生產環境中,您應該限制對特定 IP 地址的 SSH 存取,並考慮視需要限制 HTTP 存取。
-
為容器執行個體的 SSH 存取建立 EC2 金鑰對。
aws ec2 create-key-pair --key-name
ecs-tutorial-key
--query 'KeyMaterial' --output text > ecs-tutorial-key.pem chmod 400 ecs-tutorial-key.pem私有金鑰會儲存至具有適當 SSH 存取許可的本機機器。
-
使用 ECS 最佳化 AMI 啟動 EC2 執行個體,並將其設定為加入叢集。
aws ec2 run-instances --image-id
ami-abcd1234
--instance-typet3.micro
--key-nameecs-tutorial-key
--security-group-idssg-abcd1234
--iam-instance-profile Name=ecsInstanceRole --user-data '#!/bin/bash echo ECS_CLUSTER=MyCluster >> /etc/ecs/ecs.config' { "Instances": [ { "InstanceId": "i-abcd1234", "ImageId": "ami-abcd1234", "State": { "Code": 0, "Name": "pending" }, "PrivateDnsName": "", "PublicDnsName": "", "StateReason": { "Code": "pending", "Message": "pending" }, "InstanceType": "t3.micro", "KeyName": "ecs-tutorial-key", "LaunchTime": "2025-01-13T10:30:00.000Z" } ] }使用者資料指令碼會將 Amazon ECS 代理程式設定為向 註冊執行個體
MyCluster
。執行個體使用ecsInstanceRole
IAM 角色,為代理程式提供必要的許可。
列出容器執行個體
在您啟動容器執行個體後,Amazon ECS 代理會於幾分鐘內在您的預設叢集註冊執行個體。您可以執行下列命令列出叢集中的容器執行個體:
aws ecs list-container-instances --cluster
default
輸出:
{
"containerInstanceArns": [
"arn:aws:ecs:us-east-1:aws_account_id
:container-instance/container_instance_ID
"
]
}
描述您的容器執行個體
在您取得容器執行個體的 ARN 或 ID 之後,您可以使用 describe-container-instances 命令取得執行個體的實用資訊,例如剩餘的和已註冊的 CPU 與記憶體資源。
aws ecs describe-container-instances --cluster
MyCluster
--container-instancescontainer_instance_ID
輸出:
{
"failures": [],
"containerInstances": [
{
"status": "ACTIVE",
"registeredResources": [
{
"integerValue": 1024,
"longValue": 0,
"type": "INTEGER",
"name": "CPU",
"doubleValue": 0.0
},
{
"integerValue": 995,
"longValue": 0,
"type": "INTEGER",
"name": "MEMORY",
"doubleValue": 0.0
},
{
"name": "PORTS",
"longValue": 0,
"doubleValue": 0.0,
"stringSetValue": [
"22",
"2376",
"2375",
"51678"
],
"type": "STRINGSET",
"integerValue": 0
},
{
"name": "PORTS_UDP",
"longValue": 0,
"doubleValue": 0.0,
"stringSetValue": [],
"type": "STRINGSET",
"integerValue": 0
}
],
"ec2InstanceId": "instance_id
",
"agentConnected": true,
"containerInstanceArn": "arn:aws:ecs:us-west-2:aws_account_id
:container-instance/container_instance_ID
",
"pendingTasksCount": 0,
"remainingResources": [
{
"integerValue": 1024,
"longValue": 0,
"type": "INTEGER",
"name": "CPU",
"doubleValue": 0.0
},
{
"integerValue": 995,
"longValue": 0,
"type": "INTEGER",
"name": "MEMORY",
"doubleValue": 0.0
},
{
"name": "PORTS",
"longValue": 0,
"doubleValue": 0.0,
"stringSetValue": [
"22",
"2376",
"2375",
"51678"
],
"type": "STRINGSET",
"integerValue": 0
},
{
"name": "PORTS_UDP",
"longValue": 0,
"doubleValue": 0.0,
"stringSetValue": [],
"type": "STRINGSET",
"integerValue": 0
}
],
"runningTasksCount": 0,
"attributes": [
{
"name": "com.amazonaws.ecs.capability.privileged-container"
},
{
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.17"
},
{
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
},
{
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
},
{
"name": "com.amazonaws.ecs.capability.logging-driver.json-file"
},
{
"name": "com.amazonaws.ecs.capability.logging-driver.syslog"
}
],
"versionInfo": {
"agentVersion": "1.5.0",
"agentHash": "b197edd",
"dockerVersion": "DockerVersion: 1.7.1"
}
}
]
}
您也可以找到 Amazon EC2 執行個體 ID,用來在 Amazon EC2 主控台中監控執行個體,或搭配 aws ec2 describe-instances --instance-id
instance_id
命令使用。
註冊任務定義
您必須先註冊任務定義,才能在 Amazon ECS 叢集上執行任務。任務定義是分在一組的容器清單。下列範例是使用 nginx
映像的簡單任務定義。如需可用之任務定義參數的詳細資訊,請參閱「Amazon ECS 任務定義」。
{ "family": "nginx-task", "containerDefinitions": [ { "name": "nginx", "image": "public.ecr.aws/ecs-sample-image/amazon-ecs-sample:latest", "cpu": 256, "memory": 512, "essential": true, "portMappings": [ { "containerPort": 80, "hostPort": 80, "protocol": "tcp" } ] } ], "requiresCompatibilities": ["EC2"], "networkMode": "bridge" }
上述範例 JSON 可以透過 AWS CLI 兩種方式傳遞至 :您可以將任務定義 JSON 儲存為 檔案,並使用
選項傳遞。或者,您可以逸出 JSON 中的引號,並在命令列上傳遞 JSON 容器定義。如果您選擇用命令列傳送容器定義,您的命令需要使用額外的 --cli-input-json
file://path_to_file.json
--family
參數,以保留多個彼此相關聯的任務定義版本。
將 JSON 檔案用於容器定義中:
aws ecs register-task-definition --cli-input-json
file://$HOME/tasks/nginx.json
register-task-definition 會在完成註冊後,傳回任務定義的描述。
{
"taskDefinition": {
"taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/nginx-task:1",
"family": "nginx-task",
"revision": 1,
"status": "ACTIVE",
"containerDefinitions": [
{
"name": "nginx",
"image": "public.ecr.aws/docker/library/nginx:latest",
"cpu": 256,
"memory": 512,
"essential": true,
"portMappings": [
{
"containerPort": 80,
"hostPort": 80,
"protocol": "tcp"
}
],
"environment": [],
"mountPoints": [],
"volumesFrom": []
}
],
"volumes": [],
"networkMode": "bridge",
"compatibilities": [
"EC2"
],
"requiresCompatibilities": [
"EC2"
]
}
}
列出任務定義
您可以使用 list-task-definitions 命令隨時列出您帳戶的任務定義。此命令的輸出顯示您可以在呼叫 時一起使用的 family
和 revision
值create-service。
aws ecs list-task-definitions
輸出:
{
"taskDefinitionArns": [
"arn:aws:ec2:us-east-1:aws_account_id
:task-definition/sleep360:1",
"arn:aws:ec2:us-east-1:aws_account_id
:task-definition/sleep360:2",
"arn:aws:ec2:us-east-1:aws_account_id
:task-definition/nginx-task:1",
"arn:aws:ec2:us-east-1:aws_account_id
:task-definition/wordpress:3",
"arn:aws:ec2:us-east-1:aws_account_id
:task-definition/wordpress:4",
"arn:aws:ec2:us-east-1:aws_account_id
:task-definition/wordpress:5",
"arn:aws:ec2:us-east-1:aws_account_id
:task-definition/wordpress:6"
]
}
建立服務
為您的帳戶註冊任務並啟動已註冊至叢集的容器執行個體後,您可以建立 Amazon ECS 服務,使用您註冊的任務定義同時執行和維護所需數量的任務。在此範例中,您會在您的預設叢集中放置 nginx:1
任務定義的單一執行個體。
aws ecs create-service --cluster
default
--service-namenginx-service
--task-definitionnginx-task:1
--desired-count1
輸出:
{
"service": {
"serviceArn": "arn:aws:ecs:us-east-1:aws_account_id
:service/MyCluster/nginx-service",
"serviceName": "nginx-service",
"clusterArn": "arn:aws:ecs:us-east-1:aws_account_id
:cluster/MyCluster",
"taskDefinition": "arn:aws:ecs:us-east-1:aws_account_id
:task-definition/nginx-task:1",
"desiredCount": 1,
"runningCount": 0,
"pendingCount": 0,
"launchType": "EC2",
"status": "ACTIVE",
"createdAt": "2025-01-13T10:45:00.000Z"
}
}
列出服務
列出您叢集的服務。您應該會看到您在先前一節所建立的服務。您可以記下從此命令傳回的服務 ID 或完整 ARN,並在稍後用來描述服務。
aws ecs list-services --cluster
MyCluster
輸出:
{
"taskArns": [
"arn:aws:ecs:us-east-1:aws_account_id
:task/task_ID
"
]
}
描述服務
使用下列命令描述服務,以取得服務的詳細資訊。
aws ecs describe-services --cluster
MyCluster
--servicesnginx-service
輸出:
{
"services": [
{
"serviceArn": "arn:aws:ecs:us-east-1:aws_account_id
:service/MyCluster/nginx-service",
"serviceName": "nginx-service",
"clusterArn": "arn:aws:ecs:us-east-1:aws_account_id
:cluster/MyCluster",
"taskDefinition": "arn:aws:ecs:us-east-1:aws_account_id
:task-definition/nginx-task:1",
"desiredCount": 1,
"runningCount": 1,
"pendingCount": 0,
"launchType": "EC2",
"status": "ACTIVE",
"createdAt": "2025-01-13T10:45:00.000Z",
"events": [
{
"id": "abcd1234-5678-90ab-cdef-1234567890ab",
"createdAt": "2025-01-13T10:45:30.000Z",
"message": "(service nginx-service) has started 1 tasks: (task abcd1234-5678-90ab-cdef-1234567890ab)."
}
]
}
]
}
描述執行中的任務
描述服務之後,請執行下列命令,以取得在服務中執行之任務的詳細資訊。
aws ecs list-tasks --cluster
MyCluster
--service-namenginx-service
輸出:
{
"tasks": [
{
"taskArn": "arn:aws:ecs:us-east-1:aws_account_id
:task/MyCluster/abcd1234-5678-90ab-cdef-1234567890ab",
"clusterArn": "arn:aws:ecs:us-east-1:aws_account_id
:cluster/MyCluster",
"taskDefinitionArn": "arn:aws:ecs:us-east-1:aws_account_id
:task-definition/nginx-task:1",
"containerInstanceArn": "arn:aws:ecs:us-east-1:aws_account_id
:container-instance/MyCluster/abcd1234-5678-90ab-cdef-1234567890ab",
"lastStatus": "RUNNING",
"desiredStatus": "RUNNING",
"containers": [
{
"containerArn": "arn:aws:ecs:us-east-1:aws_account_id
:container/MyCluster/abcd1234-5678-90ab-cdef-1234567890ab/abcd1234-5678-90ab-cdef-1234567890ab",
"taskArn": "arn:aws:ecs:us-east-1:aws_account_id
:task/MyCluster/abcd1234-5678-90ab-cdef-1234567890ab",
"name": "nginx",
"lastStatus": "RUNNING",
"networkBindings": [
{
"bindIP": "0.0.0.0",
"containerPort": 80,
"hostPort": 80,
"protocol": "tcp"
}
]
}
],
"createdAt": "2025-01-13T10:45:00.000Z",
"startedAt": "2025-01-13T10:45:30.000Z"
}
]
}
測試 Web 伺服器
測試 Web 伺服器
-
執行下列命令,擷取容器執行個體的公有 IP 地址。
aws ec2 describe-instances --instance-ids
i-abcd1234
--query 'Reservations[0].Instances[0].PublicIpAddress' --output text輸出:
203.0.113.25
-
擷取 IP 地址之後,請使用 IP 地址執行下列
curl
命令。curl http://203.0.113.25
輸出:
<!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> ... </head> <body> <h1>Welcome to nginx!</h1> <p>If you can see this page, the nginx web server is successfully installed and working.</p> ... </body> </html>
nginx 歡迎頁面確認您的服務已成功執行,並且可從網際網路存取。
清除資源
為了避免產生費用,請清除您在本教學課程中建立的資源。
清理資源
-
將服務更新為具有零個所需任務,然後刪除服務。
aws ecs update-service --cluster
MyCluster
--servicenginx-service
--desired-count 0 { "service": { "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/MyCluster/nginx-service", "serviceName": "nginx-service", "desiredCount": 0, "runningCount": 1, "pendingCount": 0, "status": "ACTIVE" } } -
等待執行中的任務停止,然後刪除服務。
aws ecs delete-service --cluster
MyCluster
--servicenginx-service
{ "service": { "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/MyCluster/nginx-service", "serviceName": "nginx-service", "status": "DRAINING" } } -
終止您建立的容器執行個體。
aws ec2 terminate-instances --instance-ids
i-abcd1234
{ "TerminatingInstances": [ { "InstanceId": "i-abcd1234", "CurrentState": { "Code": 32, "Name": "shutting-down" }, "PreviousState": { "Code": 16, "Name": "running" } } ] } -
清除您建立的安全群組和金鑰對。
aws ec2 delete-security-group --group-id
sg-abcd1234
aws ec2 delete-key-pair --key-nameecs-tutorial-key
rmecs-tutorial-key.pem
-
刪除 Amazon ECS 叢集:
aws ecs delete-cluster --cluster
MyCluster
{ "cluster": { "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/MyCluster", "clusterName": "MyCluster", "status": "INACTIVE" } }