OnCallReadyStart learning

AWS Lesson 39.15 · AWS VI: Architecting on AWS & the exams · 19 min read

Containers on AWS: ECR, ECS on Fargate, and when to use what

In plain words

ECS is a shipping company for containers. You hand over a packed box (the image) and a delivery note (the task definition) that says what it needs. The company runs it on trucks it owns - that is Fargate - so you never maintain a truck. A loader works for the company before your box is opened, picking it up from the warehouse and setting up the paperwork: that is the execution role. Once open, whatever your goods need to do uses your own pass: the task role.

Containers on AWS: ECR, ECS on Fargate, and when to use what

Docker and Kubernetes taught you containers; AWS II ran Kubernetes on EKS. Many teams on AWS never run a cluster at all: Amazon ECS schedules containers with AWS's own control plane, and Fargate runs each task on capacity AWS manages - no nodes, no AMIs, no patching. You push an image to Amazon ECR, describe the task, and an ECS service keeps N copies running behind a load balancer, replaces the ones that die, and rolls out new versions.

Need to know: a task definition is the blueprint (image, CPU and memory, ports, logging, environment and secrets, the two roles), versioned by revision (web:3). A task is one running copy - on Fargate each gets its own network interface in your subnet (awsvpc). A service keeps desiredCount tasks running, registers them in a target group, and deploys new revisions with a rolling update. The two roles are the classic trap: the task execution role is used by ECS before your code runs (pull from ECR, write to CloudWatch Logs, read secrets), the task role is what your code gets for its own AWS calls.

Push an image to ECR

$ cd ~/oncall-lab/labs/aws/try6/web
$ newgrp docker
$ cat Dockerfile
FROM nginx:1.27-alpine
COPY index.html /usr/share/nginx/html/index.html
$ aws ecr create-repository --repository-name try-web --image-scanning-configuration scanOnPush=true --query 'repository.[repositoryUri,imageTagMutability]' --output text
111122223333.dkr.ecr.eu-central-1.amazonaws.com/try-web	MUTABLE
$ REG=111122223333.dkr.ecr.eu-central-1.amazonaws.com
$ docker build -q -t $REG/try-web:v1 .
sha256:d5dd5a35ea55be8a7db3e3059e208f511977363fb870dd61535933beb7d041d7
$ aws ecr get-login-password | docker login --username AWS --password-stdin $REG

WARNING! Your password will be stored unencrypted in /home/learner/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credential-stores

Login Succeeded
$ docker push $REG/try-web:v1 | tail -1
v1: digest: sha256:d5dd5a35ea55be8a7db3e3059e208f511977363fb870dd61535933beb7d041d7 size: 1440
$ aws ecr describe-images --repository-name try-web --query 'imageDetails[].[imageTags[0],imageSizeInBytes]' --output text
v1	20119687

(newgrp docker starts a shell with your docker group membership, in case you were added to the group after logging in.) get-login-password returns a token valid for 12 hours; CI systems run the login before every push. Production repositories are usually IMMUTABLE (a tag can never be overwritten, so v1 always means the same image) and have a lifecycle policy that expires old untagged images.

A task definition and a service behind an ALB

$ cat taskdef.json
{
  "family": "try-web",
  "requiresCompatibilities": [
    "FARGATE"
  ],
  "networkMode": "awsvpc",
  "cpu": "256",
  "memory": "512",
  "executionRoleArn": "arn:aws:iam::111122223333:role/try-ecs-exec",
  "taskRoleArn": "arn:aws:iam::111122223333:role/try-web-task",
  "containerDefinitions": [
    {
      "name": "web",
      "image": "111122223333.dkr.ecr.eu-central-1.amazonaws.com/try-web:v1",
      "essential": true,
      "portMappings": [
        {
          "containerPort": 80,
          "protocol": "tcp"
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/try-web",
          "awslogs-region": "eu-central-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
    }
  ]
}
$ aws ecs register-task-definition --cli-input-json file://taskdef.json --query 'taskDefinition.[taskDefinitionArn,cpu,memory,networkMode]' --output text
arn:aws:ecs:eu-central-1:111122223333:task-definition/try-web:1	256	512	awsvpc
$ aws ecs create-cluster --cluster-name try-shop --query 'cluster.[clusterName,status]' --output text
try-shop	ACTIVE

Fargate sizes come in fixed pairs (0.25 vCPU with 0.5-2 GB, 1 vCPU with 2-8 GB, up to 16 vCPU and 120 GB); awsvpc is the only network mode. Now the service: two tasks in two public subnets (each with a public IP, so they can reach ECR), registered in the ALB's target group, with the deployment circuit breaker on:

$ TG=$(aws elbv2 describe-target-groups --names try-web-tg --query 'TargetGroups[0].TargetGroupArn' --output text)
$ cat network.txt
awsvpcConfiguration={subnets=[subnet-07d93f499311787f9,subnet-013c96da193a52f19],securityGroups=[sg-0469a55e27b3c238a],assignPublicIp=ENABLED}
$ aws ecs create-service --cluster try-shop --service-name web --task-definition try-web:1 --desired-count 2 --launch-type FARGATE --network-configuration "$(cat network.txt)" --load-balancers targetGroupArn=$TG,containerName=web,containerPort=80 --deployment-configuration 'deploymentCircuitBreaker={enable=true,rollback=true},maximumPercent=200,minimumHealthyPercent=100' --health-check-grace-period-seconds 30 --query 'service.[serviceName,status,desiredCount,deployments[0].rolloutState]' --output text
web	ACTIVE	2	IN_PROGRESS
$ aws ecs wait services-stable --cluster try-shop --services web
$ sleep 30
$ aws ecs describe-services --cluster try-shop --services web --query 'services[0].events[].message' --output text | tr '\t' '\n' | tac
(service web) has started 2 tasks: (task 9203f28d185a6a3b2319f3e7330e969a) (task 476c823c32058746f81978575b5716d5).
(service web) registered 1 targets in (target-group arn:aws:elasticloadbalancing:eu-central-1:111122223333:targetgroup/try-web-tg/33d945d2ab57220c)
(service web) registered 1 targets in (target-group arn:aws:elasticloadbalancing:eu-central-1:111122223333:targetgroup/try-web-tg/33d945d2ab57220c)
(service web) (deployment ecs-svc/1000230255535557600) deployment completed.
(service web) has reached a steady state.
$ DNS=$(aws elbv2 describe-load-balancers --names try-web-alb --query 'LoadBalancers[0].DNSName' --output text)
$ curl -s http://$DNS/
<h1>shop v1</h1>

Read the events oldest first: tasks started, targets registered, steady state. The tasks' output goes to /ecs/try-web through the awslogs driver - with the execution role, which writes it:

$ aws logs tail /ecs/try-web --since 10m --format short | tail -4
2026-09-22T20:00:26 2026/09/22 20:00:26 [notice] 1#1: start worker process 29
2026-09-22T20:00:26 2026/09/22 20:00:26 [notice] 1#1: start worker process 30
2026-09-22T20:00:26 2026/09/22 20:00:26 [notice] 1#1: start worker process 30
2026-09-22T20:01:05 10.61.0.31 - - [22/Sep/2026:20:01:05 +0000] "GET / HTTP/1.1" 200 17 "-" "curl/8.14.1" "198.51.100.24"

A bad release and the circuit breaker

Deploy a revision whose image tag was never pushed - the most common bad release:

$ sed 's/try-web:v1/try-web:v9/' taskdef.json > taskdef-v9.json
$ aws ecs register-task-definition --cli-input-json file://taskdef-v9.json --query 'taskDefinition.revision' --output text
2
$ aws ecs update-service --cluster try-shop --service web --task-definition try-web:2 --query 'service.deployments[].[status,taskDefinition,rolloutState]' --output text
PRIMARY	arn:aws:ecs:eu-central-1:111122223333:task-definition/try-web:2	IN_PROGRESS
ACTIVE	arn:aws:ecs:eu-central-1:111122223333:task-definition/try-web:1	COMPLETED
$ sleep 240
$ aws ecs describe-services --cluster try-shop --services web --query 'services[0].events[].message' --output text | tr '\t' '\n' | grep -E 'deployment failed|rolling back'
(service web) rolling back to deployment ecs-svc/1000230255535557600.
(service web) (deployment ecs-svc/1000210679505819100) deployment failed: tasks failed to start.
$ aws ecs describe-tasks --cluster try-shop --tasks $(aws ecs list-tasks --cluster try-shop --service-name web --desired-status STOPPED --query 'taskArns' --output text) --query "tasks[?stopCode=='TaskFailedToStart'] | [0].stoppedReason" --output text
CannotPullContainerError: pull image manifest has been retried 7 time(s): failed to resolve ref 111122223333.dkr.ecr.eu-central-1.amazonaws.com/try-web:v9: 111122223333.dkr.ecr.eu-central-1.amazonaws.com/try-web:v9: not found
$ aws ecs describe-services --cluster try-shop --services web --query 'services[0].[taskDefinition,runningCount]' --output text
arn:aws:ecs:eu-central-1:111122223333:task-definition/try-web:1	2
$ curl -s http://$DNS/
<h1>shop v1</h1>

The new tasks never started (CannotPullContainerError ... not found in the stopped tasks), the circuit breaker counted the failures, marked the deployment FAILED and rolled back to revision 1 - and because minimumHealthyPercent was 100, the old tasks served traffic the whole time. Without the circuit breaker the service retries the broken deployment forever.

Scaling a service

ECS services scale with Application Auto Scaling: a scalable target (min / max tasks) and a target tracking policy on CPU, memory or ALB requests per target, which creates its own CloudWatch alarms:

$ aws application-autoscaling register-scalable-target --service-namespace ecs --resource-id service/try-shop/web --scalable-dimension ecs:service:DesiredCount --min-capacity 2 --max-capacity 6 --query ScalableTargetARN --output text
arn:aws:application-autoscaling:eu-central-1:111122223333:scalable-target/0e571337303a5d047658fa5511b47ca4
$ aws application-autoscaling put-scaling-policy --service-namespace ecs --resource-id service/try-shop/web --scalable-dimension ecs:service:DesiredCount --policy-name cpu60 --policy-type TargetTrackingScaling --target-tracking-scaling-policy-configuration '{"TargetValue":60,"PredefinedMetricSpecification":{"PredefinedMetricType":"ECSServiceAverageCPUUtilization"},"ScaleOutCooldown":60,"ScaleInCooldown":300}' --query 'Alarms[].AlarmName' --output text
TargetTracking-service/try-shop/web-AlarmHigh-615fb9a1-385a-469d-9480-b3a3a5114529	TargetTracking-service/try-shop/web-AlarmLow-117045c5-e825-4439-9f44-5a6382163737

ECS, EKS, Lambda or something else?

LambdaECS on FargateEKSEC2 (+ ASG)
unita function, up to 15 mina container task, any durationKubernetes podsan instance
you managecode + configimages + task definitionsthe cluster's add-ons, upgrades, nodes (or Fargate / Auto Mode)everything above the hypervisor
scalesper request, to zeroper task, by policy (not to zero by default)HPA / KarpenterASG policies
best forevents, spiky or low traffic, gluelong-running services and workers without Kubernetesteams with Kubernetes skills, portability, its ecosystemspecial hardware, licensing, full control

ECS on EC2 (your own container instances, capacity providers with an ASG) is cheaper at steady high utilization and needed for GPUs or daemons, at the cost of managing the instances. AWS Batch queues batch jobs on ECS or EKS capacity; App Runner and Elastic Beanstalk hide even the service and load balancer for simple web apps (both are concepts here, not simulated). Fargate Spot runs interruptible tasks at a large discount with a two-minute warning - the cost lesson uses it.

On the exam (SAA-C03 3.3, 2.1, 1.2; SOA-C03 3.1, 1.3): task role vs task execution role, ECR pulls through NAT or VPC endpoints, Fargate vs EC2 launch type, services behind an ALB with target type ip, the deployment circuit breaker, service auto scaling, and "containers without managing servers" = Fargate; "Kubernetes" = EKS.

In an interview: "Your ECS tasks get AccessDenied when the app reads S3, but they start fine. Which role do you fix?" - "The task role. The execution role is only used by ECS itself to pull the image, create the log stream and fetch secrets; once the container runs, the SDK in my code gets the task role's credentials from the container credentials endpoint."

You can now: create an ECR repository, log Docker in and push, register a Fargate task definition with an execution role and a task role, run a service behind an ALB, read service events and task stop reasons, recover from a bad release with the circuit breaker, scale a service with target tracking, and choose between Lambda, ECS, EKS and EC2.

Why it helps

Containers on ECS with Fargate are the default way to run long-lived services on AWS without managing servers or Kubernetes, and they have a small set of failures that recur everywhere: the missing execution role, no network path to ECR, the missing log group, a bad image tag. Knowing task definitions, services behind load balancers, the circuit breaker and auto scaling - and when to choose ECS, EKS or Lambda instead - covers both real operations and a large part of the exams.

Commands in this lesson

cd newgrp cat aws docker sleep curl sed

FAQ

What is the difference between a task and a service?

A task is one running copy of a task definition - one or more containers sharing a network interface. A service keeps a desired number of tasks running, replaces failed ones, registers them with a load balancer target group, and rolls out new task definition revisions with rolling deployments and the circuit breaker.

Why does Fargate need awsvpc networking?

Each Fargate task gets its own elastic network interface with a private IP in your subnet and its own security groups, so there is no host networking to share. That is also why a load balancer target group for Fargate tasks must use target type ip rather than instance.

What does the deployment circuit breaker do?

It watches a rolling deployment; when tasks keep failing to start or to pass health checks, it marks the deployment failed and, with rollback enabled, returns the service to the last deployment that completed. Combined with a minimum healthy percent of 100, users keep being served by the old tasks.

Why use IMMUTABLE image tags in ECR?

With immutable tags a tag such as v2 can never be pushed again with different content, so a task definition that names it always runs the same image, and rolling back to an older revision really restores the older code. Mutable tags like latest make it unclear what is running.

When should I choose EKS instead of ECS?

When the organization already runs Kubernetes, needs its ecosystem of controllers and tools, or wants portability to other Kubernetes clusters. ECS is simpler to operate and integrates directly with AWS services; for teams without Kubernetes skills it is usually the better default.

In an interview Mid

Your ECS tasks get AccessDenied when the application reads S3, but they start fine. Which role do you fix, and why?

The task role. The task execution role is only used by ECS itself before and around the container: pulling the image from ECR, creating the CloudWatch Logs stream and fetching secrets - if that one were wrong, the task would not start. Once the container runs, the SDK in the application gets the task role's credentials, so the S3 permission belongs there, scoped to the bucket and prefix it needs.

Also asked: Why would a Fargate task fail with ResourceInitializationError? · How do you roll back a bad ECS deployment automatically? · When would you use Lambda instead of ECS?

Practise this lesson in the terminal Free, in your browser - a real Ubuntu terminal to try it in, with missions that check your work.