What is Amazon Elastic Container Service (ECS)?

What is a container?

A container is a collection of code and its dependencies together. It is different from a Virtual Machine (VM), since a container is a lightweight entity. A VM has a guest operating system, whereas a container runs over a container engine like Docker.

What is Amazon ECS?

Amazon Elastic Container Service or ECS is a container orchestration service. It allows us to create new containers quickly and manage them across a cluster of EC2 instances.

In order to run ECS on our service, an ECS agent needs to be installed on the EC2 nodes. This agent communicates to the Amazon ECS service for cluster management.

Once we have the agents installed, and they are communicating to the Amazon ECS service, we can manage our clusters easily. We can create, start, and stop containers. We can also check the state of the clusters and the placement of the containers.

Running an application on Amazon ECS

Amazon ECS expects a task definition file. This task definition file expects container descriptions. We can have one or more container descriptions in the same task definition file. This file should contain the resources needed for the container to run, for example, CPU, Memory, storage, and networking.

A sample task definition is provided below.

{
"family": "anjana-educative",
"containerDefinitions": [ {
"name": "anjana",
"image": "someimage",
"memory": "100",
"cpu": "99"
}],
"requiresCompatibilities": [ "FARGATE" ],
"networkMode": "awsvpc",
"memory": "512",
"cpu": "256"
}

Code explanation

  • Line 2: We define the family. This is the same for multiple versions of task definition, and is auto versioned.

  • Line 3–8: We contain the container definition. These are passed to the Docker daemon on the EC2 instance. Line 9: We define the launch type. The valid values are EC2, FARGATE or EXTERNAL.

  • Line 10: We define the networkMode. This refers to the Docker networking mode to use for the containers in the task. For Amazon ECS tasks on EC2 instances, valid values are none, bridge, awsvpc, and host.

  • Line 11–12: We specify the total memory and CPU that can be used for the task.

Registration

The task definition needs to be registered in AWS.

aws ecs register-task-definition --cli-input-json testFile.json

After registering the task for our account, we can run the registered task in the cluster.

aws ecs run-task --cluster default --task-definition anjana-educative:1 ---count 1