使用 Amazon CLI 创建 Fargate 启动类型的 Amazon ECS Linux 任务
以下步骤帮助您在 Amazon ECS 中使用 Amazon CLI 设置集群、注册任务定义、运行 Linux 任务和执行其他常见方案。使用最新版本的 Amazon CLI。有关如何升级到最新版本的更多信息,请参阅安装 Amazon Command Line Interface。
先决条件
本教程假设以下先决条件已完成。
-
安装并配置了最新版本的 Amazon CLI。有关安装或升级 Amazon CLI 的更多信息,请参阅安装 Amazon Command Line Interface。
-
设置以使用 Amazon ECS 中的步骤已完成。
-
您的 Amazon 用户具有 AmazonECS_FullAccess IAM policy 示例中指定的所需权限。
-
您已创建要使用的 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 CloudShell 是一种为客户提供命令行的工具,而无需创建自己的 EC2 实例。有关更多信息,请参阅Amazon CloudShell《用户指南》中的什么是Amazon 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
替换为您创建的 IAM 任务角色,以便使用 ECS Exec,如 先决条件 中所述。
{ "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 命令列出您的账户的任务定义。此命令的输出将显示 family
和 revision
值,您可以在调用 run-task 或 start-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-namefargate-service
--task-definitionsample-fargate:1
--desired-count1
--launch-type "FARGATE" --network-configuration "awsvpcConfiguration={subnets=[subnet-abcd1234
],securityGroups=[sg-abcd1234
]}" --enable-execute-command
使用公有子网的示例。
aws ecs create-service --cluster
fargate-cluster
--service-namefargate-service
--task-definitionsample-fargate:1
--desired-count1
--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
--servicesfargate-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
--servicefargate-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
--tasksarn: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
--tasksarn: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
\ --taskarn:aws:ecs:us-east-1:123456789012:task/fargate-service/EXAMPLE
\ --containerfargate-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
--servicefargate-service
--force
请删除集群。
aws ecs delete-cluster --cluster
fargate-cluster