Swift Software Group

Launch ECS container using AWS CLI - Step 4 - Create Service

Setup an ECS container repository, create a Docker image, and upload the Docker image to the repository.

This is part of a multi-post thread involving these steps:

  1. Network Setup
  2. Launch EC2 Instance
  3. Create Docker Image
  4. Create Service (this post)
  5. Cleanup

Define Names

# registry (in the form $registryId.dkr.ecr.$region.amazonaws.com)
region=$(aws configure get region)
registryId=$(aws ecr describe-registry | jq -r '.registryId')
registry="$registryId.dkr.ecr.$region.amazonaws.com"

cluster="cluster-ecs"
service="ecs-test-service"
task_def_family="ecs-test"
task="ecs-test"

Create Task Definition

cat << EOT > ./test-ecs-task-def.json
{
    "family": "ecs-test",
    "containerDefinitions": [
        {
            "image": "$registry/ecs-test:latest",
            "name": "test",
            "cpu": 512,
            "memory": 512, 
            "essential": true
        }
    ]
}
EOT

Register Task Definition

Register task definition:

echo "Register task definition ..."
aws ecs register-task-definition --cli-input-json file://test-ecs-task-def.json

To list task definitions:

aws ecs list-task-definitions

Create Service

task_def_arn=$(aws ecs list-task-definitions --sort DESC --family-prefix $task_def_family | jq -r '.taskDefinitionArns[0]')

echo "Launch service $service ..."
aws ecs create-service \
    --cluster $cluster \
    --service-name $service \
    --task-definition $task_def_arn \
    --desired-count 1

Connect to the Container

Find EC2 instance IP address:

task_arn=$(aws ecs list-tasks --cluster=$cluster --service-name=$service | jq -r '.taskArns[0]')
container_instance_arn=$(aws ecs describe-tasks --cluster=$cluster --tasks $task_arn | jq -r '.tasks[0].containerInstanceArn')

ec2_instance=$(aws ecs describe-container-instances --cluster=$cluster --container-instances $container_instance_arn | jq -r '.containerInstances[0].ec2InstanceId')
ec2_ip=$(aws ec2 describe-instances --instance-ids $ec2_instance | jq -r '.Reservations[0].Instances[0].PublicIpAddress')

ec2_key="~/.ssh/aws-ec2-key"

Connect to the EC2 instance:

ssh -i $ec2_key ec2-user@$ec2_ip

Connect to the Docker container:

# On the EC2 instance
task="ecs-test"
container_id=$(docker ps -a -q -f name=ecs-$task | head -n 1)
docker exec -it $container_id bash