Containers on AWS: ECR and ECS
Overview
Containers package an application with its dependencies so it runs the same everywhere. Amazon ECR is a private registry for container images, while Amazon ECS runs and scales containers on EC2 or the serverless Fargate engine. Amazon EKS offers managed Kubernetes if you need that ecosystem.
Imagine shipping containers at a port. ECR is the warehouse where sealed, labelled containers are stored. A task definition is the shipping manifest, and ECS is the crane operator that places containers on ships (EC2) or on a ship that magically appears and vanishes as needed (Fargate).
You should know how to build and push images, write task definitions, assign roles, wire up load balancers and troubleshoot tasks that will not start.
Key Concepts
- ECR stores images in repositories with lifecycle policies, image scanning (basic and enhanced via Inspector), tag immutability, cross-Region/account replication and encryption.
- An ECS task definition defines containers (image, CPU/memory, ports, environment, secrets, logging), network mode (awsvpc for Fargate) and roles.
- A task is one running instance of a task definition; a service keeps a desired count running and integrates with ALB/NLB and Auto Scaling; cluster groups capacity.
- Launch types: Fargate (serverless, per vCPU/memory-second) or EC2 (you manage instances, more control, GPUs). Capacity providers combine them with Spot.
- Two roles: task execution role (pull from ECR, write logs, fetch secrets) and task role (permissions for application code).
- Secrets from Secrets Manager or Parameter Store are injected via the task definition
secretsfield, not plain environment variables. - Deployments: rolling update (min/max healthy percent), blue/green with CodeDeploy; circuit breaker can roll back failed deployments.
- Logs go to CloudWatch Logs via the
awslogsdriver; use ECS Exec for interactive debugging and Service Connect / Cloud Map for service discovery.
Detailed Notes
Build, tag and push to ECR
aws ecr create-repository --repository-name shop/api \
--image-scanning-configuration scanOnPush=true --image-tag-mutability IMMUTABLE
aws ecr get-login-password --region eu-west-1 | \
docker login --username AWS --password-stdin 111122223333.dkr.ecr.eu-west-1.amazonaws.com
docker build -t shop/api:1.4.2 .
docker tag shop/api:1.4.2 111122223333.dkr.ecr.eu-west-1.amazonaws.com/shop/api:1.4.2
docker push 111122223333.dkr.ecr.eu-west-1.amazonaws.com/shop/api:1.4.2
Use immutable, versioned tags (commit SHA) rather than latest so deployments are reproducible. A lifecycle policy can expire untagged or old images to save storage.
Task definition
{
"family": "shop-api",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "512",
"memory": "1024",
"executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::111122223333:role/shopApiTaskRole",
"containerDefinitions": [{
"name": "api",
"image": "111122223333.dkr.ecr.eu-west-1.amazonaws.com/shop/api:1.4.2",
"portMappings": [{ "containerPort": 8080 }],
"environment": [{ "name": "STAGE", "value": "prod" }],
"secrets": [{ "name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:eu-west-1:111122223333:secret:shop/db-AbCdEf" }],
"logConfiguration": {
"logDriver": "awslogs",
"options": { "awslogs-group": "/ecs/shop-api", "awslogs-region": "eu-west-1", "awslogs-stream-prefix": "api" }
},
"healthCheck": { "command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"] }
}]
}
Service and scaling
aws ecs create-service --cluster prod --service-name shop-api \
--task-definition shop-api:7 --desired-count 3 --launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[subnet-a,subnet-b],securityGroups=[sg-123],assignPublicIp=DISABLED}" \
--load-balancers targetGroupArn=arn:aws:elasticloadbalancing:...,containerName=api,containerPort=8080 \
--deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},minimumHealthyPercent=100,maximumPercent=200"
Service Auto Scaling uses target tracking (for example average CPU 60% or ALB requests per target) through Application Auto Scaling.
Fargate vs EC2 launch type
| Fargate | EC2 | |
|---|---|---|
| Server management | None | You manage instances/AMIs |
| Pricing | vCPU + memory per second | Instance price |
| Control (GPU, daemon, privileged) | Limited | Full |
| Startup | Task-level provisioning | Faster if capacity exists |
Networking modes
awsvpc gives every task its own ENI, IP and security group, which is required for Fargate and recommended for EC2. Tasks in private subnets need a NAT gateway or VPC endpoints (ECR api, ECR dkr, S3 gateway, CloudWatch Logs) to pull images and send logs.
Troubleshooting tasks that do not start
| Symptom | Likely cause |
|---|---|
CannotPullContainerError | No route to ECR (NAT/endpoints) or execution role lacks ECR permission |
| Task stops with exit code 137 | Out of memory; raise memory |
| Task fails health checks and cycles | Wrong container port, health check path or security group |
ResourceInitializationError fetching secrets | Execution role missing secretsmanager:GetSecretValue or no network path |
Use aws ecs describe-tasks to read stoppedReason, and ECS Exec to open a shell.
ECS vs EKS vs Lambda containers
Use ECS for simple AWS-native orchestration, EKS when you need Kubernetes portability and ecosystem, and Lambda container images for event-driven code up to 10 GB.
ECS building blocks in code
| Concept | Meaning |
|---|---|
| Task definition | Blueprint: image, CPU, memory, ports, environment, secrets, roles, logging |
| Task | One running instance of a task definition |
| Service | Keeps N tasks running, registers them with a load balancer, performs rolling or blue/green updates |
| Cluster | Logical group of capacity (Fargate or EC2 instances) |
| Task role vs execution role | Task role = app permissions; execution role = pull image and write logs |
{
"family": "orders-api",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "512", "memory": "1024",
"taskRoleArn": "arn:aws:iam::111122223333:role/orders-task",
"executionRoleArn": "arn:aws:iam::111122223333:role/orders-exec",
"containerDefinitions": [{
"name": "api",
"image": "111122223333.dkr.ecr.eu-west-1.amazonaws.com/orders:1.4.2",
"portMappings": [{ "containerPort": 8080 }],
"secrets": [{ "name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:eu-west-1:111122223333:secret:prod/db" }],
"logConfiguration": { "logDriver": "awslogs", "options": {
"awslogs-group": "/ecs/orders", "awslogs-region": "eu-west-1", "awslogs-stream-prefix": "api" } }
}]
}
Working with ECR
aws ecr get-login-password --region eu-west-1 | \
docker login --username AWS --password-stdin 111122223333.dkr.ecr.eu-west-1.amazonaws.com
docker build -t orders:1.4.2 .
docker tag orders:1.4.2 111122223333.dkr.ecr.eu-west-1.amazonaws.com/orders:1.4.2
docker push 111122223333.dkr.ecr.eu-west-1.amazonaws.com/orders:1.4.2
aws ecr put-lifecycle-policy --repository-name orders --lifecycle-policy-text file://policy.json
Enable scan on push (basic or enhanced with Inspector), tag immutability and lifecycle policies to expire old images, and use replication for cross-Region or cross-account copies. Fargate removes server management; ECS on EC2 gives control of instance types, GPUs and cost optimisation with Spot. Service Connect or Cloud Map provides service discovery between tasks. Deployments use a rolling update by default with a deployment circuit breaker, or CodeDeploy blue/green for traffic shifting. Troubleshoot tasks that stop immediately with the stopped reason, container exit code and CloudWatch logs.
Real World Example
A retail platform moved its monolith into three containerised services. Images are built in CodeBuild, scanned on push in ECR, tagged by commit SHA and deployed to ECS Fargate services behind an ALB. Tasks use a task role limited to their own DynamoDB tables, and database passwords are injected from Secrets Manager. A deployment circuit breaker automatically rolled back a release whose container failed health checks, with no manual action and no customer impact.
Architecture Diagram
Images are stored in ECR; ECS runs them behind a load balancer using task and execution roles.
- 1The pipeline builds an image and pushes it to ECR with an immutable tag.
- 2A new task definition revision references that tag.
- 3The ECS service starts tasks, pulling the image with the execution role.
- 4The ALB routes traffic to healthy tasks; the circuit breaker rolls back failures.
Best Practices
- ✓Use immutable, unique image tags and enable scan on push.
- ✓Separate the task role (app) from the execution role (agent).
- ✓Inject secrets via
secretsin the task definition. - ✓Enable the deployment circuit breaker and container health checks.
- ✓Provide private-subnet VPC endpoints or NAT for ECR and logs.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Task role = app permissions; execution role = pull images, logs, secrets.
- Fargate requires awsvpc networking.
- Private tasks pulling images need NAT or VPC endpoints.
- Container logs -> awslogs driver to CloudWatch Logs.
Chapter quiz
CI/CD and Deployment · 10 questions
1.A CodeBuild project must run unit tests and then package a SAM application. Where should these commands be defined?
2.A team deploys a Lambda function using CodeDeploy and wants 10% of traffic shifted first, with automatic rollback if the error alarm triggers. Which configuration meets this?
3.A CloudFormation update would change a DynamoDB table property that requires replacement. How can a developer see this risk before applying the update?
4.A team needs zero-downtime Elastic Beanstalk deployments with full capacity throughout and quick rollback by terminating new instances. Which policy fits BEST?
5.A Fargate task in a private subnet fails with CannotPullContainerError. The execution role allows ECR access. What is the most likely missing piece?
6.A CodeBuild project must reuse npm dependencies between builds to cut build time. What should be configured?
7.A CloudFormation update fails midway. What happens by default?
8.Internal teams need to share private npm and Maven packages with versioning and upstream proxying to public registries. Which service fits?
9.A team needs zero-downtime releases on EC2 with the ability to instantly route back to the old fleet. Which deployment type is best?
10.Different API stages need different backend Lambda aliases without redeploying code. What feature supports this?
0 of 10 answered
Finished this lesson?
0 of 46 lessons done · 0% of the course

