

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

# 使用 為 EC2 建立 Amazon ECS 任務 AWS CLI
<a name="ECS_AWSCLI_EC2"></a>

以下步驟會協助您使用 AWS CLI在 Amazon ECS 中設定叢集、註冊任務定義、執行任務，以及執行其他常見案例。使用 AWS CLI的最新版本。如需有關如何升級至最新版本的詳細資訊，請參閱 [Installing or updating to the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

**注意**  
您可以使用雙堆疊服務端點，透過 IPv4 和 IPv6 AWS CLI從 、 SDKs 和 Amazon ECS API 與 Amazon ECS 互動。如需詳細資訊，請參閱[使用 Amazon ECS 雙堆疊端點](dual-stack-endpoint.md)。

**Topics**
+ [先決條件](#AWSCLI_EC2_prereq)
+ [建立 叢集](#AWSCLI_EC2_create_cluster)
+ [使用 Amazon ECS AMI 啟動容器執行個體](#AWSCLI_EC2_launch_container_instance)
+ [列出容器執行個體](#AWSCLI_EC2_list_container_instances)
+ [描述容器執行個體](#AWSCLI_EC2_describe_container_instance)
+ [註冊任務定義](#AWSCLI_EC2_register_task_definition)
+ [列出任務定義](#AWSCLI_EC2_list_task_definitions)
+ [建立服務](#AWSCLI_EC2_run_task)
+ [列出服務](#AWSCLI_EC2_list_tasks)
+ [描述服務](#AWSCLI_EC2_describe_service)
+ [描述執行中的任務](#AWSCLI_EC2_describe_task)
+ [測試 Web 伺服器](#AWSCLI_EC2_test_web_server)
+ [清除資源](#AWSCLI_EC2_clean_up_resources)

## 先決條件
<a name="AWSCLI_EC2_prereq"></a>

本教學課程假設已完成下列先決條件：
+  AWS CLI 已安裝並設定最新版本的 。如需安裝或升級 的詳細資訊 AWS CLI，請參閱[安裝或更新至最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。
+ 已完成「[設定以使用 Amazon ECS。](get-set-up-for-amazon-ecs.md)」中的步驟。
+ 您的 IAM 使用者擁有 [AmazonECS\$1FullAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonECS_FullAccess) IAM 政策範例中指定的所需許可。
+ 您已建立可供使用的容器執行個體 IAM 角色。如需詳細資訊，請參閱 [Amazon ECS 容器執行個體 IAM 角色](instance_IAM_role.md)。
+ 您已建立可供使用的 VPC。如需詳細資訊，請參閱[建立 Virtual Private Cloud](get-set-up-for-amazon-ecs.md#create-a-vpc)。
+ （選用） AWS CloudShell 是一種工具，可為客戶提供命令列，而不需要建立自己的 EC2 執行個體。如需詳細資訊，請參閱*AWS CloudShell 《 使用者指南*》中的[什麼是 AWS CloudShell？](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html)。

## 建立 叢集
<a name="AWSCLI_EC2_create_cluster"></a>

當您啟動第一個容器執行個體時，您的帳戶預設會得到 `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 啟動容器執行個體
<a name="AWSCLI_EC2_launch_container_instance"></a>

容器執行個體是執行 Amazon ECS 容器代理程式並已在叢集中註冊的 EC2 執行個體。在本節中，您將使用 ECS 最佳化 AMI 來啟動 EC2 執行個體。

**使用 啟動容器執行個體 AWS CLI**

1.  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
   ```

1. 建立一個安全群組，該群組允許透過 SSH 存取來管理容器執行個體，也允許 Web 伺服器的 HTTP 存取。

   ```
   aws ec2 create-security-group --group-name ecs-tutorial-sg --description "ECS tutorial security group"
   ```

   輸出：

   ```
   {
       "GroupId": "sg-abcd1234"
   }
   ```

1. 執行下列命令，將傳入規則新增至安全群組。

   ```
   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 存取。在生產環境中，您應將 SSH 存取限制為特定 IP 位址，並視需要考量限制 HTTP 存取。

1. 建立一個用於對容器執行個體進行 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 存取的適當許可。

1. 使用 ECS 最佳化 AMI 啟動 EC2 執行個體，並將執行個體設定為加入叢集。

   ```
   aws ec2 run-instances --image-id ami-abcd1234 --instance-type t3.micro --key-name ecs-tutorial-key --security-group-ids sg-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 角色，該角色為代理程式提供必要許可。

## 列出容器執行個體
<a name="AWSCLI_EC2_list_container_instances"></a>

在您啟動容器執行個體後的幾分鐘內，Amazon ECS 代理程式會將該執行個體註冊至您的 MyCluster 叢集。您可以執行下列命令列出叢集中的容器執行個體：

```
aws ecs list-container-instances --cluster MyCluster
```

輸出：

```
{
    "containerInstanceArns": [
        "arn:aws:ecs:us-east-1:aws_account_id:container-instance/container_instance_ID"
    ]
}
```

## 描述容器執行個體
<a name="AWSCLI_EC2_describe_container_instance"></a>

在您取得容器執行個體的 ARN 或 ID 之後，您可以使用 **describe-container-instances** 命令取得執行個體的實用資訊，例如剩餘的和已註冊的 CPU 與記憶體資源。

```
aws ecs describe-container-instances --cluster MyCluster --container-instances container_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\$1id*** 命令使用。

## 註冊任務定義
<a name="AWSCLI_EC2_register_task_definition"></a>

您必須先註冊任務定義，才能在 Amazon ECS 叢集中執行任務。任務定義是分在一組的容器清單。以下範例是使用 `nginx` 映像的簡單任務定義。如需可用之任務定義參數的詳細資訊，請參閱「[Amazon ECS 任務定義](task_definitions.md)」。

```
{
    "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 儲存為 檔案，並使用 `--cli-input-json file://path_to_file.json`選項將其傳遞。或者，您可以逸出 JSON 中的引號，在命令列上傳遞 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"
        ]
    }
}
```

## 列出任務定義
<a name="AWSCLI_EC2_list_task_definitions"></a>

您可以使用 **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"
    ]
}
```

## 建立服務
<a name="AWSCLI_EC2_run_task"></a>

在為帳戶註冊任務並啟動已註冊至叢集的容器執行個體後，即可建立 Amazon ECS 服務。該服務會使用您註冊的任務定義，同時執行並維持所需數量的任務。在此範例中，您會在 MyCluster 叢集中置放 `nginx:1` 任務定義的單一執行個體。

```
aws ecs create-service --cluster MyCluster --service-name nginx-service --task-definition nginx-task:1 --desired-count 1
```

輸出：

```
{
    "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"
    }
}
```

## 列出服務
<a name="AWSCLI_EC2_list_tasks"></a>

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

```
aws ecs list-services --cluster MyCluster
```

輸出：

```
{
    "taskArns": [
        "arn:aws:ecs:us-east-1:aws_account_id:task/task_ID"
    ]
}
```

## 描述服務
<a name="AWSCLI_EC2_describe_service"></a>

使用下列命令描述服務，取得有關服務的詳細資訊。

```
aws ecs describe-services --cluster MyCluster --services nginx-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)."
                }
            ]
        }
    ]
}
```

## 描述執行中的任務
<a name="AWSCLI_EC2_describe_task"></a>

描述服務之後，請執行下列命令，取得作為服務一部分的執行中任務的詳細資訊。

```
aws ecs list-tasks --cluster MyCluster --service-name nginx-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 伺服器
<a name="AWSCLI_EC2_test_web_server"></a>

**測試 Web 伺服器**

1. 透過執行下列命令，擷取容器執行個體的公有 IP 位址。

   ```
   aws ec2 describe-instances --instance-ids i-abcd1234 --query 'Reservations[0].Instances[0].PublicIpAddress' --output text
   ```

   輸出：

   ```
   203.0.113.25
   ```

1. 擷取 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 歡迎頁面即確認服務已成功執行，可從網際網路存取。

## 清除資源
<a name="AWSCLI_EC2_clean_up_resources"></a>

若要避免產生費用，需清理在此教學課程中建立的資源。

**清理資源**

1. 將服務的所需任務數量更新為零，然後刪除服務。

   ```
   aws ecs update-service --cluster MyCluster --service nginx-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"
       }
   }
   ```

1. 等待執行中任務停止，然後刪除服務。

   ```
   aws ecs delete-service --cluster MyCluster --service nginx-service
   {
       "service": {
           "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/MyCluster/nginx-service",
           "serviceName": "nginx-service",
           "status": "DRAINING"
       }
   }
   ```

1. 終止已建立的容器執行個體。

   ```
   aws ec2 terminate-instances --instance-ids i-abcd1234
   {
       "TerminatingInstances": [
           {
               "InstanceId": "i-abcd1234",
               "CurrentState": {
                   "Code": 32,
                   "Name": "shutting-down"
               },
               "PreviousState": {
                   "Code": 16,
                   "Name": "running"
               }
           }
       ]
   }
   ```

1. 清理已建立的安全群組與金鑰對。

   ```
   aws ec2 delete-security-group --group-id sg-abcd1234
   aws ec2 delete-key-pair --key-name ecs-tutorial-key
   rm ecs-tutorial-key.pem
   ```

1. 刪除 Amazon ECS 叢集。

   ```
   aws ecs delete-cluster --cluster MyCluster
   {
       "cluster": {
           "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/MyCluster",
           "clusterName": "MyCluster",
           "status": "INACTIVE"
       }
   }
   ```