Running Containers with Amazon ECS, Amazon ECR and AWS Fargate
This lesson explains how Amazon ECS runs containers from task definitions, either on EC2 instances that you manage or on serverless AWS Fargate capacity, using images stored in Amazon ECR.
Learning outcomes
After completing this lesson, you will be able to:
- Describe how task definitions, tasks, services and clusters are related.
- Choose between the EC2 launch type and Fargate.
- Distinguish the task role from the task execution role.
- Describe how images are pushed to Amazon ECR and how ECS services are deployed and scaled.
Core concepts
Amazon Elastic Container Service (ECS) is built on four concepts. A task definition is a versioned JSON document that describes how to run one or more containers together: the image for each, the CPU and memory they need, the ports they listen on, environment variables and secrets, where logs go, and the IAM roles to use. Each change creates a new revision, such as orders-api:7.
A task is a running instance of a task definition. A task can be run on its own, for example for a batch job, and stops when its containers exit. A service runs and maintains a desired number of tasks for a long-running application: it replaces tasks that fail or stop, registers new tasks with a load balancer's target group, rolls out new task definition revisions, and can scale the number of tasks with service auto scaling. A cluster is the logical grouping in which tasks and services run, together with the capacity that runs them, whether EC2 instances or Fargate. The following table summarises the concepts.
| Concept | What it is |
|---|---|
| Task definition | Describes containers: image, CPU and memory, ports, environment variables, secrets, logging and IAM roles |
| Task | A running instance of a task definition |
| Service | Keeps a desired number of tasks running, replaces failed ones and registers them with a load balancer |
| Cluster | The logical group that tasks and services run in |
ECS building blocks
EC2 vs Fargate
ECS tasks run either on EC2 instances that you provide or on AWS Fargate, and the choice decides how much infrastructure the team manages.
With the EC2 launch type, the cluster contains EC2 instances running the ECS agent, and ECS places tasks on them. The team chooses instance types, patches the operating system and scales the number of instances, and pays for the instances whether or not they are full. In return it can use instance types that Fargate does not offer, such as GPU instances, pack many tasks onto each instance, and access the host when needed.
With Fargate, there are no instances to manage. Each task declares its CPU and memory, AWS provides isolated capacity of that size, and billing is for the resources the task requests while it runs. Every Fargate task receives its own elastic network interface and security group. Fargate is the usual answer when a question asks for containers without managing servers. The following table summarises the differences.
Task role vs task execution role
An ECS task can use two IAM roles, which are frequently confused because both appear in the task definition.
The task role belongs to the application. Its temporary credentials are made available to the containers, so the application code, through the AWS SDK, calls AWS services with the task role's permissions, for example to write objects to S3 or read items from DynamoDB. If the application logs AccessDenied for such a call, the task role is missing a permission.
The task execution role belongs to ECS. The ECS agent, or Fargate, uses it before and around the application: to pull the container image from a private ECR repository, to send container logs to CloudWatch Logs, and to retrieve the secrets that the task definition injects as environment variables. If a task fails to start with CannotPullContainerError, or cannot fetch its secrets, the execution role is the one to check. The following table summarises the difference.
Inject secrets from Secrets Manager or Parameter Store through the task definition's secrets field, never by building them into images.
{
"family": "orders-api",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "512", "memory": "1024",
"executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::111122223333:role/OrdersApiTaskRole",
"containerDefinitions": [{
"name": "api",
"image": "111122223333.dkr.ecr.eu-west-1.amazonaws.com/orders-api:1.8.2",
"portMappings": [{"containerPort": 8080}],
"secrets": [{"name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:eu-west-1:111122223333:secret:orders/db"}],
"logConfiguration": {"logDriver": "awslogs",
"options": {"awslogs-group": "/ecs/orders-api", "awslogs-region": "eu-west-1", "awslogs-stream-prefix": "api"}}
}]
}The following diagram shows which role each part of a task uses.

Which ECS role?
Pushing images to ECR
Docker clients authenticate to ECR with aws ecr get-login-password:
aws ecr get-login-password | docker login --username AWS --password-stdin 111122223333.dkr.ecr.eu-west-1.amazonaws.com
docker build -t orders-api:1.8.2 . && docker tag orders-api:1.8.2 111122223333.dkr.ecr.eu-west-1.amazonaws.com/orders-api:1.8.2
docker push 111122223333.dkr.ecr.eu-west-1.amazonaws.com/orders-api:1.8.2Deployments and scaling
Amazon ECS services can be deployed and scaled in several ways. The following list describes the available options.
- Rolling updates, protected by a deployment circuit breaker that rolls back a failing deployment automatically.
- Blue/green through CodeDeploy or native ECS blue/green.
- Service auto scaling with target tracking on CPU, memory or ALB request count.
A task that will not start
A new ECS service on Fargate keeps stopping its tasks. The stopped reason and logs point to two different roles:
| Error | Role at fault | Fix |
|---|---|---|
CannotPullContainerError when pulling from ECR | Task execution role | Attach AmazonECSTaskExecutionRolePolicy (and check the subnet can reach ECR) |
ResourceInitializationError fetching a secret | Task execution role | Allow secretsmanager:GetSecretValue on the secret |
| Application logs show AccessDenied writing to S3 | Task role | Grant s3:PutObject to the task role |
The execution role is for ECS itself (pulling images, writing logs, injecting secrets); the task role is for the application code. Mixing them up is a classic exam trap.
When does the Fargate launch type suit better than the EC2 launch type?
Show answer
When the team does not want to manage, patch or scale servers, because AWS runs each task on capacity it manages. The EC2 launch type suits workloads that need particular instance types or control over the hosts.
Exam Tips
Remember for the exam
- If the container cannot call S3, fix the task role.
- If the task cannot pull its image from ECR or write logs, fix the task execution role.
- To run containers without managing servers, use Fargate.
- To inject a database password into a container, use task definition secrets from Secrets Manager.
- To roll back a failing ECS deployment automatically, enable the deployment circuit breaker.