Overview and What You Will Learn
Amazon ECS is AWS's container orchestrator, and AWS Fargate is the serverless compute engine that runs ECS tasks without any servers for you to manage. You describe what a container needs in a task definition, and an ECS service keeps the desired number of tasks running, replaces failed ones, and registers them with a load balancer.
In this guide you will learn:
- How Docker concepts map onto ECS terms, so there is little new to learn
- How the EC2 launch type, Fargate, and ECS Managed Instances differ
- What goes into a task definition
- How the task execution role, task role, and EC2 instance role differ, which is the most commonly confused topic in ECS
- How to scale tasks with target tracking, and how capacity providers scale the cluster
- How to give containers persistent storage with EFS and EBS
- How to build event-driven container workloads with EventBridge and SQS
- How ECR stores images, and how lifecycle policies stop storage costs from growing
- Why ECS Express Mode replaces App Runner for new projects
- How to deploy a Fargate service behind an Application Load Balancer with Terraform
Why This Matters in Production
A streaming platform like Hotstar runs many microservices, such as metadata, profiles, and recommendations, and each must scale on its own, recover from failures, and deploy without downtime. A payments team like PhonePe's cannot afford to patch cluster hosts or watch capacity during a traffic spike. ECS with Fargate removes the host layer, but only if the task definition, roles, networking, and scaling are configured correctly. Most ECS incidents trace back to a wrong role, a missing network path to ECR, or a cluster that was full when tasks needed to start.
Core Principles
How Docker Concepts Map to ECS
If you know Docker, ECS adds three new ideas: ECR for images, the task definition for run configuration, and the service for keeping containers alive.
| Docker concept | ECS equivalent |
|---|---|
docker run with all its flags |
Task definition, saved and versioned in AWS |
| One running container (or set) | Task |
| The machines that run containers | Cluster |
| Compose keeping containers alive | Service, which keeps N tasks running |
docker push to Docker Hub |
docker push to ECR with a different URL |
CPU, memory, roles] TD --> SVC[ECS service
keeps N tasks] SVC --> T1[Task 1] SVC --> T2[Task 2] ALB[Application Load Balancer] -->|Health checked| T1 ALB -->|Health checked| T2 classDef person fill:#475569,color:#ffffff classDef store fill:#F97316,color:#ffffff classDef config fill:#8B5CF6,color:#ffffff classDef run fill:#10B981,color:#ffffff classDef edge fill:#326CE5,color:#ffffff class DEV person class ECR store class TD,SVC config class T1,T2 run class ALB edge
EC2 Launch Type vs Fargate
With Fargate you set CPU and memory per task and AWS finds, patches, and scales the underlying capacity. With the EC2 launch type you run and patch the instances yourself, and ECS places tasks on them.
| Aspect | EC2 launch type | Fargate |
|---|---|---|
| Infrastructure | You manage EC2 instances | AWS manages it |
| Capacity planning | Size the cluster, or use capacity providers | None, each task gets its own capacity |
| Billing | EC2 instances, used or not | vCPU and memory per task, billed per second |
| GPU and special hardware | Yes | No |
Fargate tasks range from 0.25 to 16 vCPU, include 20 GiB of ephemeral storage that you can raise to 200 GiB, and can run on Arm (Graviton) for lower cost. Fargate Spot runs interruptible tasks at a discount of up to 70 percent for fault-tolerant work. ECS Managed Instances is a newer option where AWS manages EC2 instances for you while you still choose instance types, which helps when you need GPUs or specific hardware without operating hosts.
Choose EC2 when you need GPUs, already hold Reserved Instances or Savings Plans, or must control the host. Choose Fargate for most other workloads.
What a Task Definition Contains
A task definition is the saved recipe for how a task runs. Each change creates a new numbered revision, so you can roll back to any earlier revision.
- Image URI, such as an ECR image and tag
- CPU and memory for the task
- Port mappings, environment variables, and secrets references
- The task role and task execution role
- Log configuration, usually the
awslogsdriver to CloudWatch - Volumes, such as EFS mounts
- Network mode (
awsvpcgives each task its own network interface and security group)
The Three IAM Roles in ECS
ECS uses separate roles for separate jobs, and mixing them up either breaks startup or over-grants access.
| Role | Used by | Typical permissions |
|---|---|---|
| Task execution role | ECS agent or Fargate, on behalf of the task | Pull from ECR, write to CloudWatch Logs, read referenced secrets |
| Task role | Your application code inside the container | S3, DynamoDB, SQS, and other services your code calls |
| EC2 instance role | ECS agent on EC2 hosts (EC2 launch type only) | Register the instance, talk to ECS |
The task execution role is about starting the task. The task role is about what your code can do once it runs. Each task can have its own task role, so two tasks on the same host can have entirely different permissions.
RememberPut application permissions on the task role, not on the EC2 instance role. Anything on the instance role is inherited by every container on that host.
How ECS Service Auto Scaling Works
ECS Service Auto Scaling changes a service's desired task count using Application Auto Scaling. The three policy types are:
- Target tracking: hold a metric at a target, such as average CPU at 60 percent or 500 requests per target from the ALB. This is the best default.
- Step scaling: add or remove tasks in tiers when a CloudWatch alarm crosses thresholds.
- Scheduled scaling: set minimum and maximum capacity at known times, such as raising capacity before business hours.
For queue workers, publish a backlog-per-task metric (queue depth divided by running tasks) and track that. With Fargate, scaling tasks is all you need to do.
With the EC2 launch type there are two independent levels: service scaling changes the number of tasks, and an Auto Scaling group changes the number of instances. If the cluster is full, new tasks sit in PENDING. A capacity provider with managed scaling connects the two, so ECS asks the Auto Scaling group for more instances when tasks cannot be placed. Use capacity providers for the EC2 launch type from the start.
How to Give Containers Persistent Storage
Containers lose local data when they stop, so choose storage by access pattern:
- Ephemeral storage: scratch space for the life of one task
- Amazon EFS: a shared file system mounted by many tasks across Availability Zones, for uploads, shared config, and model files. It works on both launch types.
- Amazon EBS volumes: attached to a single task at launch, for stateful single-task workloads. This is supported on Fargate, so older advice that EBS cannot be used with Fargate is out of date.
- S3: object storage called from application code through the task role
How ECS Handles Deployments
By default a service does a rolling update, starting new tasks before stopping old ones within your minimum healthy and maximum percent settings. Turn on the deployment circuit breaker with rollback so a bad image or failing health check reverts automatically instead of leaving a half-broken service. ECS also offers built-in blue/green deployments for services that need traffic shifted between two task sets.
How to Run Containers on Events and Queues
Tasks do not have to be always on.
- EventBridge to ECS: a rule starts a Fargate task when an event arrives, such as a new video landing in S3. Enable EventBridge notifications on the bucket first. The task processes the file and stops, so you pay only for run time.
- SQS workers: a service polls a queue, a backlog metric rises when work piles up, and target tracking adds tasks until the queue drains.
- Task state change events: ECS emits an event whenever a task stops. An EventBridge rule can match
stoppedReasonand notify an SNS topic, so out-of-memory kills reach the on-call engineer immediately.
How ECR Stores Images
Amazon ECR is AWS's managed image registry, integrated with IAM. Authenticate Docker with a token that lasts 12 hours, create a repository, then tag and push.
aws ecr get-login-password --region ap-south-1 | \ docker login --username AWS --password-stdin \ 123456789012.dkr.ecr.ap-south-1.amazonaws.com # Build, tag, and pushdocker build -t devops-orders-api:v1 .docker tag devops-orders-api:v1 \ 123456789012.dkr.ecr.ap-south-1.amazonaws.com/devops-orders-api:v1docker push 123456789012.dkr.ecr.ap-south-1.amazonaws.com/devops-orders-api:v1Enable scan on push to catch vulnerable packages, use immutable tags so a tag always means the same image, and add a lifecycle policy that expires old images. Without one, every CI push is stored forever.
ECS Express Mode and App Runner
ECS Express Mode is the simplest way to run a container on ECS. You supply a container image plus two IAM roles, and it creates the Fargate service, load balancer, networking, HTTPS, and autoscaling for you, while leaving the real ECS resources visible and editable. Express Mode adds no charge beyond the resources it creates, can share one load balancer across several services, and deploys prebuilt images only, so you need a build pipeline.
AWS App Runner closed to new customers on April 30, 2026. Existing customers can keep using it, but no new features are planned, and AWS recommends ECS Express Mode for new projects. Fargate services do not scale to zero, so a small always-on service has a monthly cost floor.
Detailed Step-by-Step Practical Lab
You will deploy an nginx service on Fargate behind an Application Load Balancer, with an ECR repository, separate task and execution roles, a Fargate and Fargate Spot capacity strategy, a deployment circuit breaker, and autoscaling. You need Terraform 1.6 or later and the AWS CLI. The lab uses the default VPC with public IPs on tasks to stay short. In production, run tasks in private subnets with a NAT Gateway or VPC endpoints for ECR, S3, and CloudWatch Logs.
Step 1: Network, Load Balancer, and Security Groups
# main.tfterraform { required_version = ">= 1.6.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } }} provider "aws" { region = "ap-south-1"} variable "image" { description = "Container image to deploy" type = string default = "public.ecr.aws/docker/library/nginx:stable"} data "aws_vpc" "default" { default = true} data "aws_subnets" "default" { filter { name = "vpc-id" values = [data.aws_vpc.default.id] }} # The load balancer accepts web traffic from the internetresource "aws_security_group" "alb" { name = "devops-orders-alb-sg" vpc_id = data.aws_vpc.default.id ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] }} # Tasks accept traffic only from the load balancerresource "aws_security_group" "tasks" { name = "devops-orders-tasks-sg" vpc_id = data.aws_vpc.default.id ingress { from_port = 80 to_port = 80 protocol = "tcp" security_groups = [aws_security_group.alb.id] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] }} resource "aws_lb" "orders" { name = "devops-orders-alb" load_balancer_type = "application" subnets = data.aws_subnets.default.ids security_groups = [aws_security_group.alb.id]} resource "aws_lb_target_group" "orders" { name = "devops-orders-tg" port = 80 protocol = "HTTP" vpc_id = data.aws_vpc.default.id target_type = "ip" # required for awsvpc tasks deregistration_delay = 30 # drain faster than the 300 second default health_check { path = "/" matcher = "200" }} resource "aws_lb_listener" "http" { load_balancer_arn = aws_lb.orders.arn port = 80 protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.orders.arn }} output "alb_dns_name" { value = aws_lb.orders.dns_name}Step 2: ECR Repository, Log Group, and the Two Roles
# iam_ecr.tfresource "aws_ecr_repository" "orders" { name = "devops-orders-api" image_tag_mutability = "IMMUTABLE" # a tag always points at the same image force_delete = true # lab only, lets destroy remove images image_scanning_configuration { scan_on_push = true }} # Keep only the 10 most recent imagesresource "aws_ecr_lifecycle_policy" "orders" { repository = aws_ecr_repository.orders.name policy = jsonencode({ rules = [ { rulePriority = 1 description = "Keep the last 10 images" selection = { tagStatus = "any" countType = "imageCountMoreThan" countNumber = 10 } action = { type = "expire" } } ] })} resource "aws_cloudwatch_log_group" "orders" { name = "/ecs/orders-api" retention_in_days = 14} data "aws_iam_policy_document" "ecs_tasks_assume" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = ["ecs-tasks.amazonaws.com"] } }} # Task EXECUTION role: used by ECS to start the task (pull image, write logs)resource "aws_iam_role" "execution" { name = "devops-orders-execution-role" assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json} resource "aws_iam_role_policy_attachment" "execution" { role = aws_iam_role.execution.name policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"} # Task role: used by YOUR CODE. Grant only what the application needs.resource "aws_iam_role" "task" { name = "devops-orders-task-role" assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json} data "aws_iam_policy_document" "task" { # Example application permission: read one config bucket statement { actions = ["s3:GetObject"] resources = ["arn:aws:s3:::devops-orders-config/*"] } # Lets you open a shell in the running task with ECS Exec statement { actions = [ "ssmmessages:CreateControlChannel", "ssmmessages:CreateDataChannel", "ssmmessages:OpenControlChannel", "ssmmessages:OpenDataChannel", ] resources = ["*"] }} resource "aws_iam_role_policy" "task" { name = "orders-app-permissions" role = aws_iam_role.task.id policy = data.aws_iam_policy_document.task.json}Step 3: Cluster, Task Definition, Service, and Autoscaling
# ecs.tfdata "aws_region" "current" { # no arguments required} resource "aws_ecs_cluster" "main" { name = "devops-prod-cluster"} # Fargate for the baseline, Fargate Spot for extra capacityresource "aws_ecs_cluster_capacity_providers" "main" { cluster_name = aws_ecs_cluster.main.name capacity_providers = ["FARGATE", "FARGATE_SPOT"]} resource "aws_ecs_task_definition" "orders" { family = "devops-orders-api" requires_compatibilities = ["FARGATE"] network_mode = "awsvpc" cpu = 256 # 0.25 vCPU memory = 512 # 512 MiB execution_role_arn = aws_iam_role.execution.arn task_role_arn = aws_iam_role.task.arn runtime_platform { operating_system_family = "LINUX" cpu_architecture = "ARM64" # Graviton is cheaper per vCPU } container_definitions = jsonencode([ { name = "orders-api" image = var.image essential = true portMappings = [ { containerPort = 80 protocol = "tcp" } ] logConfiguration = { logDriver = "awslogs" options = { "awslogs-group" = aws_cloudwatch_log_group.orders.name "awslogs-region" = data.aws_region.current.name "awslogs-stream-prefix" = "orders-api" } } } ])} resource "aws_ecs_service" "orders" { name = "orders-api-service" cluster = aws_ecs_cluster.main.id task_definition = aws_ecs_task_definition.orders.arn desired_count = 2 enable_execute_command = true health_check_grace_period_seconds = 30 # One task is always on regular Fargate, extra tasks prefer Spot capacity_provider_strategy { capacity_provider = "FARGATE" base = 1 weight = 1 } capacity_provider_strategy { capacity_provider = "FARGATE_SPOT" weight = 3 } network_configuration { subnets = data.aws_subnets.default.ids security_groups = [aws_security_group.tasks.id] assign_public_ip = true # lab only, use private subnets in production } load_balancer { target_group_arn = aws_lb_target_group.orders.arn container_name = "orders-api" container_port = 80 } # A failing deployment rolls back instead of staying broken deployment_circuit_breaker { enable = true rollback = true } # Autoscaling owns the desired count after creation lifecycle { ignore_changes = [desired_count] } depends_on = [ aws_lb_listener.http, aws_ecs_cluster_capacity_providers.main, ]} resource "aws_appautoscaling_target" "orders" { service_namespace = "ecs" resource_id = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.orders.name}" scalable_dimension = "ecs:service:DesiredCount" min_capacity = 2 max_capacity = 10} resource "aws_appautoscaling_policy" "cpu" { name = "cpu-target-60" policy_type = "TargetTrackingScaling" service_namespace = aws_appautoscaling_target.orders.service_namespace resource_id = aws_appautoscaling_target.orders.resource_id scalable_dimension = aws_appautoscaling_target.orders.scalable_dimension target_tracking_scaling_policy_configuration { target_value = 60 predefined_metric_specification { predefined_metric_type = "ECSServiceAverageCPUUtilization" } }}terraform initterraform applyStep 4: Verify the Service and Reach It Through the ALB
aws ecs describe-services \ --cluster devops-prod-cluster --services orders-api-service \ --query 'services[0].[status,desiredCount,runningCount]' --output text# ACTIVE 2 2 ALB=$(terraform output -raw alb_dns_name)until curl -s -o /dev/null -w "%{http_code}\n" "http://$ALB/" | grep -q 200; do echo "waiting for healthy targets..."; sleep 10donecurl -sI "http://$ALB/" | head -n 1# HTTP/1.1 200 OKStep 5: Open a Shell in a Running Task with ECS Exec
This needs the Session Manager plugin for the AWS CLI. It confirms the task role credentials work from inside the container.
TASK=$(aws ecs list-tasks --cluster devops-prod-cluster \ --service-name orders-api-service --query 'taskArns[0]' --output text) aws ecs execute-command \ --cluster devops-prod-cluster --task "$TASK" \ --container orders-api --interactive --command "/bin/sh"Step 6: Push Your Own Image to ECR and Redeploy
Because the repository uses immutable tags, use a new tag for every build.
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)REPO="$ACCOUNT.dkr.ecr.ap-south-1.amazonaws.com/devops-orders-api" aws ecr get-login-password --region ap-south-1 | \ docker login --username AWS --password-stdin "$ACCOUNT.dkr.ecr.ap-south-1.amazonaws.com" # Build for the same CPU architecture as the task definition (ARM64)docker buildx build --platform linux/arm64 -t "$REPO:v1" --push . terraform apply -var "image=$REPO:v1"Step 7: Watch the Circuit Breaker Roll Back a Bad Deployment
Deploy a tag that does not exist. The new tasks cannot pull the image, and ECS rolls back to the working revision.
terraform apply -var "image=public.ecr.aws/docker/library/nginx:does-not-exist" aws ecs describe-services \ --cluster devops-prod-cluster --services orders-api-service \ --query 'services[0].deployments[].[status,rolloutState,rolloutStateReason]' \ --output table# The failed deployment ends in rolloutState FAILED and the service keeps serving traffic # Restore your Terraform state to the good imageterraform applyStep 8: Generate Load and Watch Autoscaling
# hey is a simple HTTP load generator (https://github.com/rakyll/hey)hey -z 5m -c 200 "http://$ALB/" # In another terminal, watch the desired count rise above 2watch -n 20 "aws ecs describe-services --cluster devops-prod-cluster \ --services orders-api-service \ --query 'services[0].[desiredCount,runningCount]' --output text"Target tracking scales out within a few minutes and scales in more slowly, so allow about 15 minutes after the load stops to see the count fall.
Step 9: Clean Up
terraform destroyProduction Best Practices & Common Pitfalls
Common MistakeForgetting the task execution role, or giving application permissions to the wrong role. Without the execution role a Fargate task cannot pull from ECR or write logs. Without the right task role your code gets
AccessDeniedwhen it calls AWS. Keep the two roles separate and minimal.
Common MistakeGiving containers AWS access through the EC2 instance role. Every task on that host inherits it, including tasks that should not have it. Use a task role per service so each gets only what it needs.
Common MistakeRunning the EC2 launch type without a capacity provider, then finding tasks stuck in
PENDINGduring a spike. The service and the Auto Scaling group scale independently, so the group does not know tasks are waiting. Use capacity providers with managed scaling.
Common MistakeSkipping ECR lifecycle policies. Every CI push stores another image, and months later the registry holds thousands of old images. Create the policy when you create the repository.
TipWhen a task stops right after starting, check the stop reason and logs first.
aws ecs describe-tasksshowsstoppedReasonand the container exit code, and CloudWatch Logs shows the application error. Exit code 137 usually means out of memory.
SecurityDo not put secrets in plain environment variables. Reference Secrets Manager or Parameter Store in the task definition's
secretsfield, and grant the execution role read access to just those secrets. Run tasks in private subnets with no public IP, and expose them only through the load balancer.
- Reach ECR without a public path. Tasks in private subnets need a NAT Gateway or VPC endpoints for ECR (API and Docker), S3, and CloudWatch Logs. A missing path shows up as
CannotPullContainerError. - Right-size from measurements. Start with a small CPU and memory size, then adjust from observed utilisation, because Fargate bills for what you allocate.
- Handle SIGTERM. ECS sends SIGTERM before stopping a task and waits for the stop timeout, so finish in-flight requests and exit cleanly. Pair this with a short deregistration delay on the target group.
- Use Fargate Spot only for tolerant work. Keep a regular Fargate base for availability, and let Spot absorb extra capacity.
- Pin and scan images. Use immutable tags or digests and scan on push, so what you tested is what you run.
- Set log retention. Create log groups yourself and set a retention period so logs do not accumulate forever.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
aws ecs list-clusters |
List clusters |
aws ecs describe-services --cluster C --services S |
Show service status and deployments |
aws ecs list-tasks --cluster C --service-name S |
List a service's tasks |
aws ecs describe-tasks --cluster C --tasks T |
Show task status and stop reason |
aws ecs update-service --cluster C --service S --force-new-deployment |
Restart tasks with a new deployment |
aws ecs execute-command --cluster C --task T --container N --interactive --command "/bin/sh" |
Open a shell in a task |
aws ecr describe-images --repository-name R |
List images in a repository |
aws logs tail /ecs/orders-api --follow |
Stream container logs |
| Problem | Likely fix |
|---|---|
CannotPullContainerError |
Add a public IP, NAT, or VPC endpoints, and check the execution role |
ResourceInitializationError |
Check network access to ECR, S3, and Secrets Manager |
| Targets are unhealthy | Check the security group, container port, and health check path |
Tasks stay PENDING on EC2 |
Add capacity or use a capacity provider with managed scaling |
| Container exits with code 137 | Increase task memory or fix a memory leak |
| Service keeps rolling back | Read rolloutStateReason and the container logs for the failing revision |
AccessDenied from your code |
Add the permission to the task role, not the execution role |