0Pricing
AWS Solutions Architect · Lesson

ECS Clusters, Task Definitions, and Services

Define ECS task definitions with container images and resource limits, register them in a cluster, and create a service to maintain desired count.

ECS Clusters, Task Definitions, and Services is a free AWS Solutions Architect lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AWS Solutions Architect learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Containers on AWS?

Containers package an application and all its dependencies into a portable, isolated unit that runs consistently across environments. Amazon ECS (Elastic Container Service) is AWS's fully managed container orchestration service that runs Docker containers without you managing a control plane. ECS integrates deeply with AWS services (IAM, ALB, CloudWatch, Secrets Manager) and is the recommended way to run containers on AWS without Kubernetes complexity.

ECS Clusters: The Grouping Unit

An ECS Cluster is a logical grouping of compute resources where your containers run. A cluster can contain EC2 instances (EC2 launch type), Fargate capacity (Fargate launch type), or both. You can have multiple services and standalone tasks in one cluster. Clusters are regional but span Availability Zones. A common pattern is one cluster per environment (dev/staging/prod) with multiple services within each cluster for different microservices.

aws ecs create-cluster \
  --cluster-name 'MyAppCluster' \
  --capacity-providers FARGATE FARGATE_SPOT \
  --default-capacity-provider-strategy \
    capacityProvider=FARGATE,weight=1,base=1

Task Definitions: The Blueprint

A Task Definition is the blueprint for running containers in ECS—analogous to a Docker Compose file. It specifies: container images (ECR URIs or Docker Hub), CPU and memory allocations, port mappings, environment variables, logging configuration, volumes, and the IAM task role. A task definition is versioned—each revision is immutable. You can define multiple containers per task for sidecar patterns (main app + log shipper + monitoring agent).

{
  'family': 'myapp-task',
  'networkMode': 'awsvpc',
  'requiresCompatibilities': ['FARGATE'],
  'cpu': '512',
  'memory': '1024',
  'executionRoleArn': 'arn:aws:iam::123456789012:role/ecsTaskExecutionRole',
  'taskRoleArn': 'arn:aws:iam::123456789012:role/myAppTaskRole',
  'containerDefinitions': [{
    'name': 'myapp',
    'image': '123456789012.dkr.ecr.us-east-1.amazonaws.com/myapp:latest',
    'portMappings': [{'containerPort': 8080}]
  }]
}

Task Role vs Execution Role

ECS tasks use two separate IAM roles with distinct purposes. The Task Execution Role is used by the ECS agent to pull container images from ECR, send logs to CloudWatch, and retrieve secrets from Secrets Manager or Parameter Store during task startup. The Task Role is used by the application code running inside the container to call AWS services (S3, DynamoDB, SQS). Always assign least-privilege permissions to each role separately—never give the execution role permissions the application doesn't need.

ECS Services for Long-Running Workloads

An ECS Service maintains a specified number of simultaneously running task instances (the desired count). If a task fails or stops, the service scheduler launches a replacement automatically. Services also integrate with Elastic Load Balancing for traffic distribution and support rolling deployments and blue/green deployments. Use a service for any long-running process (web server, API server, background worker). For one-off jobs, run a standalone task instead.

aws ecs create-service \
  --cluster 'MyAppCluster' \
  --service-name 'MyAppService' \
  --task-definition 'myapp-task:5' \
  --desired-count 3 \
  --launch-type FARGATE \
  --network-configuration '{
    "awsvpcConfiguration": {
      "subnets": ["subnet-aaa111", "subnet-bbb222"],
      "securityGroups": ["sg-xyz"],
      "assignPublicIp": "DISABLED"
    }
  }'

Network Modes: awsvpc vs bridge

The awsvpc network mode gives each ECS task its own Elastic Network Interface (ENI) and private IP address within your VPC—just like an EC2 instance. This enables fine-grained security group control per task and is required for Fargate tasks. The bridge network mode uses Docker's built-in virtual network on the host, with port mapping from host to container—it shares the host EC2 instance's ENI. For the SAA-C03 exam, Fargate always uses awsvpc; EC2 launch type can use either.

Attaching a Load Balancer to an ECS Service

Register your ECS service with an ALB target group to distribute traffic across task instances. When a new task starts, ECS automatically registers it with the target group; when it stops, ECS deregisters it. Configure a health check grace period (e.g., 60-120 seconds) to give containers time to start before health checks run. Without a grace period, the ALB may mark a slow-starting container as unhealthy before it's ready, causing replacement loops.

aws ecs create-service \
  --cluster 'MyAppCluster' \
  --service-name 'MyAppService' \
  --load-balancers \
    'targetGroupArn=arn:aws:elasticloadbalancing:...,containerName=myapp,containerPort=8080' \
  --health-check-grace-period-seconds 120 \
  --task-definition 'myapp-task:5' \
  --desired-count 3

Rolling Deployment vs Blue/Green Deployment

ECS services support two deployment strategies: Rolling Update gradually replaces old tasks with new ones—configurable with minimumHealthyPercent (floor) and maximumPercent (ceiling). Setting 100/200 means old tasks run while new ones launch (100% healthy required, up to 200% capacity). Blue/Green deployment (via AWS CodeDeploy) creates a new task set alongside the old one, shifts traffic gradually using ALB weighted routing, and terminates old tasks after validation. Blue/green has zero-downtime rollback capability.

CloudWatch Logging from ECS

Configure the awslogs log driver in your task definition to send container stdout/stderr directly to CloudWatch Logs. Specify a log group, region, and stream prefix. The task execution role needs logs:CreateLogStream and logs:PutLogEvents permissions. For centralised log aggregation across multiple services, consider using FireLens (a sidecar container with Fluent Bit or Fluentd) to route logs to S3, OpenSearch, or third-party logging systems.

'logConfiguration': {
    'logDriver': 'awslogs',
    'options': {
        'awslogs-group': '/ecs/myapp',
        'awslogs-region': 'us-east-1',
        'awslogs-stream-prefix': 'myapp'
    }
}

ECS Service Discovery with Cloud Map

When microservices in ECS need to communicate with each other, hard-coded IP addresses won't work because tasks are ephemeral and get new IPs on each launch. Use AWS Cloud Map (ECS Service Discovery) to register each task's IP and port in a DNS namespace. Other services resolve myservice.namespace.local to the current healthy task IPs. ECS automatically registers new tasks and deregisters failed ones, keeping DNS records accurate without manual management.

Secrets in ECS Task Definitions

Never hardcode credentials in task definitions. Instead, reference Secrets Manager or Parameter Store secrets in your task definition—ECS injects them as environment variables at task startup. The task execution role must have permissions to retrieve the secrets. For Secrets Manager, use secretsmanager:GetSecretValue; for Parameter Store, use ssm:GetParameters. Secrets are retrieved once at container startup; rotating secrets requires task replacement to pick up new values.

'secrets': [
    {
        'name': 'DB_PASSWORD',
        'valueFrom': 'arn:aws:secretsmanager:us-east-1:123456789012:secret:myapp/db-password-AbCdEf'
    },
    {
        'name': 'API_KEY',
        'valueFrom': 'arn:aws:ssm:us-east-1:123456789012:parameter/myapp/api-key'
    }
]

Quick Check

Test your understanding of AWS Solutions Architect (SAA-C03) concepts from this lesson.

Lesson Recap

In this lesson you learned: ECS Clusters group compute resources where tasks run, Task Definitions define container images, CPU/memory, roles, and logging as versioned blueprints, and ECS Services maintain desired task count, integrate with ALB for traffic distribution, and support rolling or blue/green deployments. Next up we compare the EC2 launch type with the serverless Fargate launch type.

Frequently asked questions

Is the “ECS Clusters, Task Definitions, and Services” lesson free?

Yes — the full text of “ECS Clusters, Task Definitions, and Services” is free to read here on the web, and the AWS Solutions Architect course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AWS Solutions Architect course, upgrade to CoddyKit PRO.

What will I learn in “ECS Clusters, Task Definitions, and Services”?

Define ECS task definitions with container images and resource limits, register them in a cluster, and create a service to maintain desired count. You practise AWS Solutions Architect with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AWS Solutions Architect?

No prior experience is required. AWS Solutions Architect on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “ECS Clusters, Task Definitions, and Services” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AWS Solutions Architect lesson?

Yes. Every AWS Solutions Architect lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. ECS Clusters, Task Definitions, and Services
  2. EC2 Launch Type vs Fargate
  3. ECR: Storing and Pulling Container Images
  4. ECS Service Auto Scaling and Load Balancing
← Back to AWS Solutions Architect