AWS CLI를 사용하여 EC2 시작 유형에 대한 Amazon ECS 작업 생성 - Amazon Elastic Container Service

AWS CLI를 사용하여 EC2 시작 유형에 대한 Amazon ECS 작업 생성

다음 단계는 AWS CLI를 사용하여 Amazon ECS에서 클러스터를 설정하고, 태스크 정의를 등록하고, 태스크를 실행하고, 기타 일반적인 시나리오를 수행하는 데 도움이 됩니다. AWS CLI의 최신 버전을 사용합니다. 최신 버전으로 업그레이드하는 방법에 대한 자세한 내용은 AWS CLI 최신 버전의 설치 또는 업데이트를 참조하세요.

참고

듀얼 스택 서비스 엔드포인트를 사용하면 AWS CLI, SDK 및 Amazon ECS API에서 IPv4 및 IPv6 모두를 통해 Amazon ECS와 상호 작용할 수 있습니다. 자세한 내용은 Amazon ECS 듀얼 스택 엔드포인트 사용 섹션을 참조하세요.

사전 조건

이 자습서에서는 다음 사전 조건이 충족되었다고 가정합니다.

클러스터 생성

기본적으로 첫 번째 컨테이너 인스턴스를 시작할 때 계정에 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로 컨테이너 인스턴스 시작하려면
  1. 다음 명령을 사용하여 AWS 리전에 대한 최신 ECS 최적화 Amazon Linux 2 AMI ID를 검색합니다. 이 명령은 AWS Systems Manager Parameter Store를 사용하여 최신 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
  2. 컨테이너 인스턴스를 관리할 SSH 액세스와 웹 서버에 대한 HTTP 액세스를 허용하는 보안 그룹을 생성합니다.

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

    출력:

    { "GroupId": "sg-abcd1234" }
  3. 다음 명령을 실행하여 보안 그룹에 인바운드 규칙을 추가합니다.

    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 액세스를 제한하는 것을 고려해야 합니다.

  4. 컨테이너 인스턴스에 대한 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 액세스에 대한 적절한 권한이 있는 로컬 시스템에 저장됩니다.

  5. 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" } ] }

    사용자 데이터 스크립트는 인스턴스를 MyCluster에 등록하도록 Amazon ECS 에이전트를 구성합니다. 인스턴스는 에이전트에 필요한 권한을 제공하는 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-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 콘솔이나 aws ec2 describe-instances --instance-id instance_id 명령을 사용하여 인스턴스를 모니터링하는 데 사용할 수 있는 Amazon EC2 인스턴스 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을 파일로 저장하고 --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" ] } }

태스크 정의 나열

언제라도 list-task-definitions 명령을 사용하여 계정의 작업 정의를 나열할 수 있습니다. 이 명령은 create-service를 호출할 때 함께 사용할 수 있는 familyrevision 값을 출력합니다.

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

서비스 나열

클러스터의 서비스를 나열합니다. 이전 섹션에서 생성한 서비스가 보일 것입니다. 이 명령에서 반환된 서비스 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 --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)." } ] } ] }

실행 중인 태스크 설명

서비스를 설명한 후 다음 명령을 실행하여 서비스의 일부로 실행 중인 태스크에 대한 자세한 정보를 가져옵니다.

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" } ] }

웹 서버 테스트

웹 서버를 테스트하려면
  1. 다음 명령을 실행하여 컨테이너 인스턴스의 퍼블릭 IP 주소를 검색합니다.

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

    출력:

    203.0.113.25
  2. 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 시작 페이지에서 서비스가 성공적으로 실행되고 인터넷에서 액세스할 수 있는지 확인합니다.

리소스 정리

비용이 발생하지 않도록 하려면 이 자습서에서 생성한 리소스를 정리합니다.

리소스를 정리하려면
  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" } }
  2. 실행 중인 태스크가 중지될 때까지 기다린 다음, 서비스를 삭제합니다.

    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" } }
  3. 생성된 컨테이너 인스턴스를 종료합니다.

    aws ec2 terminate-instances --instance-ids i-abcd1234 { "TerminatingInstances": [ { "InstanceId": "i-abcd1234", "CurrentState": { "Code": 32, "Name": "shutting-down" }, "PreviousState": { "Code": 16, "Name": "running" } } ] }
  4. 생성한 보안 그룹 및 키 페어를 정리합니다.

    aws ec2 delete-security-group --group-id sg-abcd1234 aws ec2 delete-key-pair --key-name ecs-tutorial-key rm ecs-tutorial-key.pem
  5. Amazon ECS 클러스터를 삭제합니다.

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