Sub topic 3
ECS building blocks: clusters, tasks, and services
This chapter assumes you can build and run a Docker image, you know the basics of IAM, VPC, subnets and security groups, and you can read JSON and run the AWS CLI. You will learn the four objects that every ECS deployment is built from, how they relate, and the mistakes people commonly make with them.
The working model
Amazon Elastic Container Service (ECS) is a scheduler. You tell it what containers to run and how many copies you want. It finds capacity, starts the containers, and replaces them when they fail. ECS does not build images and does not run containers itself. It delegates that to compute, which with Fargate is capacity that AWS manages.
Four objects describe the whole system:
| Object | What it is | Changes over time? |
|---|---|---|
| Cluster | A logical grouping of tasks and services in one Region | Rarely |
| Task definition | A versioned blueprint: images, CPU, memory, roles, ports, logging | Each change creates a new revision |
| Task | One running instance of a task definition | Short-lived |
| Service | A controller that keeps a desired number of tasks running | Long-lived |
The key idea is that a task definition is only a description. Nothing runs until you create a task from it, either directly or through a service.
Clusters
A cluster is a namespace for your workloads. With Fargate it holds no servers that you manage. It is a name, a place to attach settings, and a scope for permissions and metrics.
aws ecs create-cluster --cluster-name demoThings to know about clusters:
- A cluster belongs to one account and one Region. Tasks in it can span multiple Availability Zones, depending on the subnets you give them.
- You can use one cluster per environment (
dev,prod) or one per team. Clusters cost nothing by themselves, so the choice is about access control and organization. - A cluster can enable Container Insights for CPU, memory, and network metrics per task and service. This adds CloudWatch charges.
- IAM permissions can be scoped to a cluster ARN. That is a common reason to split clusters.
Task definitions
A task definition is a JSON document registered under a family name. Each registration creates a new numbered revision, such as web-app:7. Revisions are immutable. To change anything, you register a new revision.
A task definition has two levels:
- Task level:
family,cpu,memory,networkMode,executionRoleArn,taskRoleArn,requiresCompatibilities, volumes. - Container level:
containerDefinitions, a list of containers that always run together on the same host and share a network namespace.
Put containers in the same task only when they must start, stop, and scale together, for example an application and a log-forwarding sidecar. If two components scale independently, make them separate task definitions.
Each container has an essential flag. If an essential container stops, ECS stops the whole task. A task must have at least one essential container.
The next chapters cover the contents of a task definition in detail. For now, register one and see how revisions behave:
aws ecs register-task-definition --cli-input-json file://taskdef.json
aws ecs list-task-definitions --family-prefix web-app
aws ecs describe-task-definition --task-definition web-appUsing web-app without a revision resolves to the latest active revision. Using web-app:7 pins an exact one.
Tasks
A task is one running instance of a task definition. On Fargate, each task runs in its own isolated environment, with its own kernel boundary, CPU and memory allocation, and network interface. Tasks do not share a host with tasks from other customers or from your other tasks.
You can start a task in two ways:
- Through a service, which keeps tasks running. Use this for web servers and workers.
- With
run-task, which starts a standalone task that runs once and is not replaced when it exits. Use this for migrations, batch jobs, and scheduled work.
A task moves through a lifecycle. Knowing the states helps when you debug.
Two fields tell you what ECS is doing and what it intends to do:
lastStatusis the current state.desiredStatusis where ECS wants the task to go, usuallyRUNNINGorSTOPPED.
A task that fails to start stays visible as STOPPED for a short time, with a stoppedReason and per-container exitCode values. Read these first when a task will not stay up.
aws ecs list-tasks --cluster demo --desired-status STOPPED
aws ecs describe-tasks --cluster demo --tasks <task-id> \
--query "tasks[].{reason:stoppedReason,containers:containers[].{name:name,exit:exitCode,reason:reason}}"Stopped tasks are kept for only about an hour, so check soon after a failure.
Services
A service is a control loop. You give it a task definition, a desired count, and a place to run. It compares the number of healthy running tasks to the desired count and acts to close any gap.
aws ecs create-service \
--cluster demo \
--service-name web \
--task-definition web-app \
--desired-count 2 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[subnet-aaa111,subnet-bbb222],securityGroups=[sg-0123456789abcdef0],assignPublicIp=DISABLED}"A service does several jobs:
- It replaces tasks that stop or fail health checks.
- It spreads tasks across the subnets, and therefore Availability Zones, that you provide.
- It registers and deregisters tasks with a load balancer target group.
- It performs deployments when you point it at a new task definition revision.
- It is the scalable resource that Application Auto Scaling adjusts.
Update a service to roll out a new revision:
aws ecs update-service --cluster demo --service web --task-definition web-app:2Replica and daemon scheduling
ECS services have two scheduling strategies. REPLICA keeps a chosen number of copies running and is the one you use on Fargate. DAEMON runs one task on each container instance and applies only to EC2 capacity. Fargate has no instances you can see, so DAEMON is not available there.
Service or standalone task
| Need | Use |
|---|---|
| Always on, replaced after failure | Service |
| Behind a load balancer | Service |
| Runs to completion once | `run-task` |
| Runs on a schedule | EventBridge Scheduler or rule that calls `run-task` |
Common errors
- Editing instead of registering. You cannot modify a revision. Registering the same JSON again still creates a new revision. Deregister old revisions you no longer need.
- Using
latestimage tags. A new task pulls whatever the tag points to at that moment. Two tasks from the same revision can then run different code. Use immutable version tags or digests. - Expecting
desired-count 0to delete anything. The service still exists and costs nothing in compute. It simply runs no tasks. - Putting unrelated containers in one task. They scale together, so you pay for the largest need on every copy.
- Forgetting that a service needs a task that stays up. A container that exits immediately causes a loop of starts and stops. Look at
stoppedReasonand the service events. - Assuming a cluster is a network boundary. It is not. Isolation comes from VPC subnets and security groups.
You can see what a service has been doing in its event log:
aws ecs describe-services --cluster demo --services web \
--query "services[0].events[:5].[createdAt,message]" --output tableMessages such as "unable to place a task" or "has reached a steady state" show whether the service reached its desired count.
Exercise
A service has desired count 3 and a task definition api:5. You register api:6 and run aws ecs update-service --cluster demo --service api --task-definition api:6. Which object changed, which objects were created, and what does the service do with the existing tasks?
Show answer
The service changed, because its task definition reference now points to api:6. Registering api:6 created a new immutable revision, and the deployment creates new tasks from that revision. The service starts tasks from api:6 and stops the tasks from api:5 according to its deployment settings, until three healthy tasks run the new revision. Revision api:5 is not modified and stays available for rollback.
Exercise
You need to run a database migration once before each release, and a web server that stays up. For each, choose between a service and run-task, and give one reason.
Show answer
Use run-task for the migration, because it runs to completion once and should not be restarted when it exits. Use a service for the web server, because it must stay at a desired count, be replaced after failures, and register with a load balancer.