Subscribe

ECS explained: clusters, task definitions, services, and Fargate vs EC2

The ECS mental model in one post: what a cluster, task definition, task and service really are, how a deploy rolls, the difference between the task role and the execution role, and what Fargate costs against EC2 in Mumbai.

ECS explained: clusters, task definitions, services, and Fargate vs EC2

Open the ECS console and the first question is where your container actually is. There's a cluster, a task definition with a revision number, a service, tasks, and two different IAM roles that look like they do the same job. None of it is hard once you have the picture, but nobody draws the picture for you.

So in this blog we will build the picture. What each ECS piece is, how they fit together, how a deploy actually rolls, the task role vs the execution role, and what Fargate costs compared with running your own EC2 instances. Level is beginner. You should know what a Docker image is (Docker from zero covers that) and have an AWS account, ideally one set up like in Setting up a new AWS account safely. The example is shorty, the URL shortener from Building a REST API in Go with only the standard library. I checked the Terraform here with Terraform 1.17.1 and AWS provider 6.73.0 using terraform validate. Nothing was applied to a real account.

The four nouns

Here's the whole model in one picture.

cluster "shorty"                      a namespace, plus where the capacity comes from
 └── service "shorty"                 "keep 2 copies of shorty:7 running"
      ├── task  (shorty:7)  10.0.1.23  a running copy, one or more containers
      └── task  (shorty:7)  10.0.2.41
task definition "shorty", revision 7  the recipe: image, CPU, memory, env, ports, roles

Task definition. The recipe. Which image, how much CPU and memory, the ports, environment variables, log settings, and which IAM roles to use. Every change makes a new revision, shorty:6, shorty:7, and old revisions stay around. They stay around more than you'd think, which I wrote up in Deregistering an ECS task definition does not delete it.

Task. A running copy of a task definition. If the task definition has two containers (say your app and a log router), one task runs both, side by side, sharing a network. A task is roughly what Kubernetes calls a pod.

Service. The thing that keeps tasks alive. You tell it "I want 2 tasks of shorty:7" and it starts them, replaces any that die, registers them with a load balancer, and rolls them to a new revision when you deploy. You can run a task without a service too. That's what I do for database migrations, see Running goose migrations as a one-off ECS task before updating the service.

Cluster. Mostly a name. On Fargate it's almost nothing, just a grouping with some settings like Container Insights. On EC2 it's also the pool of instances your tasks get placed on.

That's it. Four nouns only. Everything else in the console is a setting on one of them, more or less.

Task definition in Terraform

This is shorty's task definition, trimmed a little.

resource "aws_ecs_task_definition" "shorty" {
  family                   = "shorty"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = "256"
  memory                   = "512"
  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"
  }

  container_definitions = jsonencode([{
    name         = "shorty"
    image        = var.image
    essential    = true
    portMappings = [{ containerPort = 8080, protocol = "tcp" }]
    environment = [
      { name = "PORT", value = "8080" },
      { name = "LOG_LEVEL", value = "info" }
    ]
    healthCheck = {
      command     = ["CMD", "/shorty", "healthcheck"]
      interval    = 15
      timeout     = 3
      retries     = 3
      startPeriod = 10
    }
    logConfiguration = {
      logDriver = "awslogs"
      options = {
        awslogs-group         = aws_cloudwatch_log_group.shorty.name
        awslogs-region        = "ap-south-1"
        awslogs-stream-prefix = "shorty"
      }
    }
  }])
}

A few things trip people up here. cpu = "256" means a quarter of a vCPU, ECS counts in 1024ths. On Fargate only certain CPU and memory pairs exist, and 256 CPU goes with 512 MB, 1 GB or 2 GB. The health check runs /shorty healthcheck because shorty's image is distroless and has no shell or curl. A CMD-SHELL health check with curl would fail on every single task. And awsvpc gives every task its own network interface and private IP, which is required on Fargate.

DATABASE_URL and REDIS_URL aren't in that block on purpose. Secrets don't belong in environment, they get their own post later in this series.

Task role vs execution role

This is the part I see mixed up most often, and it's basically the names' fault.

The execution role is used by ECS itself, before your code runs. ECS uses it to pull the image from ECR, to create the log stream and send logs to CloudWatch, and to fetch any secrets you referenced. Your app never sees it. For most services the AWS managed AmazonECSTaskExecutionRolePolicy is all it needs.

The task role is used by your code while it runs. When shorty's Go code calls S3 or DynamoDB through the AWS SDK, the SDK gets its credentials from the task role. If your app doesn't call AWS at all it doesn't need a task role.

# execution role: used by ECS to START the task
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 while it runs
resource "aws_iam_role_policy" "task" {
  name = "shorty-app"
  role = aws_iam_role.task.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["s3:PutObject"]
      Resource = "arn:aws:s3:::shorty-exports-111122223333/exports/*"
    }]
  })
}

Both roles trust the same principal, ecs-tasks.amazonaws.com, which adds to the confusion. A quick rule: if the error happens before your container starts (CannotPullContainerError, ResourceInitializationError), look at the execution role. If your app logs AccessDenied, look at the task role. More on reading policies in IAM explained by writing policies.

How the app gets task role keys

There are no access keys in your environment. ECS sets one variable, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, and the SDK calls http://169.254.170.2 plus that path to get short lived keys. I wanted to see this with the Go SDK itself rather than take it on trust, so I wrote a test where a local HTTP server plays that endpoint. The SDK also accepts AWS_CONTAINER_CREDENTIALS_FULL_URI pointing at loopback, which makes it testable.

t.Setenv("AWS_CONFIG_FILE", filepath.Join(dir, "none"))
t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "none"))
t.Setenv("AWS_ACCESS_KEY_ID", "")
t.Setenv("AWS_SECRET_ACCESS_KEY", "")
t.Setenv("AWS_PROFILE", "")
t.Setenv("AWS_REGION", "ap-south-1")
t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", srv.URL+"/v2/credentials/abc")

cfg, err := config.LoadDefaultConfig(context.Background())
if err != nil {
    t.Fatal(err)
}
creds, err := cfg.Credentials.Retrieve(context.Background())

The first five lines keep the test away from any real credentials on my machine. I didn't want it to quietly pick up my own profile and pass for the wrong reason. The fake server return fake keys with a six hour expiry.

=== RUN   TestSDKUsesContainerCredentials
    taskcreds_test.go:54: source=CredentialsEndpointProvider key=ASIAEXAMPLEEXAMPLE00 expires=2026-11-19T13:33:33Z
--- PASS: TestSDKUsesContainerCredentials (0.00s)

The test also checks that two Retrieve calls hit the server only once. The SDK caches the keys and refreshes them before they expire, so you don't need to do anything in your code. Just use config.LoadDefaultConfig and don't set keys by hand.

How a deploy rolls

You register a new task definition revision and point the service at it. With the default rolling update, two numbers decide what happens.

resource "aws_ecs_service" "shorty" {
  name            = "shorty"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.shorty.arn
  desired_count   = 2
  launch_type     = "FARGATE"

  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200

  deployment_circuit_breaker {
    enable   = true
    rollback = true
  }

  network_configuration {
    subnets          = var.subnet_ids
    security_groups  = var.security_group_ids
    assign_public_ip = false
  }
}

With 2 tasks, minimum 100% and maximum 200%, ECS may run up to 4 tasks and must keep 2 healthy. So it starts 2 new ones, waits for them to pass health checks (and the load balancer's, if there is one), then stops the 2 old ones. Stopping means SIGTERM, then SIGKILL 30 seconds later by default, so your app should shut down cleanly in that window. I wrote about getting that right in Graceful shutdown of a golang HTTP server on ECS Fargate behind an ALB.

The circuit breaker is the setting I'd turn on everywhere. Without it, a new revision that crashes on start will be retried for a very long time while the old tasks keep serving, and nobody notices. With it, ECS gives up after a number of failed launches and rolls back to the last revision that worked.

Also watch what you put in the container's command. If ECS overrides the command (one-off tasks do), an ENTRYPOINT in your image can make that go wrong in a confusing way, see Why your Docker image should use CMD and not ENTRYPOINT when ECS overrides the command.

Fargate vs EC2

Same task definitions, same services. The difference is who owns the machine.

On Fargate you never see an instance. Each task gets exactly the CPU and memory you asked for and you pay per second for that. No AMIs to patch, no capacity to plan.

On EC2 you run instances in an Auto Scaling group, the ECS agent on them joins the cluster, and ECS packs tasks onto them. You pay for the instances whether they're full or empty. You patch the AMI. In return you get cheaper compute if you keep them full, GPUs, and any instance type you like.

Here are the numbers. Prices are on-demand Linux from the AWS price list for Asia Pacific (Mumbai, ap-south-1), checked on 19 November 2026. Monthly means 730 hours.

What Hourly Monthly
Fargate arm64, per vCPU $0.02383
Fargate arm64, per GB $0.00261
Fargate x86, per vCPU $0.04256
Fargate x86, per GB $0.004655
shorty task, 0.25 vCPU + 0.5 GB, arm64 $0.00726 $5.30
shorty task, 0.25 vCPU + 0.5 GB, x86 $0.01297 $9.47
Fargate arm64, 1 vCPU + 4 GB $0.03427 $25.02
EC2 m7g.medium (1 vCPU, 4 GB) $0.0292 $21.32
EC2 t4g.small (2 vCPU burstable, 2 GB) $0.0112 $8.18

Two things jump out. First, arm64 Fargate is about 44% cheaper than x86 for the same size. If your image builds for arm64 (a Go binary does with one env var), that's the easiest saving in this whole post. Second, for the same shape a fully packed m7g.medium is only about 15% cheaper than Fargate. "Fully packed" is doing a lot of work in that sentence though. In practice instances run half empty during quiet hours, and you need spare room on them for deploys, since a rolling deploy briefly runs double the tasks.

The t4g.small looks like a steal, and for a small steady app it really is. It's burstable, so sustained CPU is limited by credits, and it has 2 GB for the OS, the ECS agent and your tasks. There's another catch with awsvpc on EC2: each task takes a network interface, and a small instance only has a few. A t4g.small supports 3, one of them is the instance's own, so it fits just 2 awsvpc tasks no matter how much memory is free. People hit this and spend an hour wondering why tasks sit in PROVISIONING.

My own blog runs on one t3.small with Docker Compose, not ECS at all, see Running Ghost 6 and MySQL 8 on a 2 GB t3.small. One box, one app, it's the cheapest thing that works. For services at work with a few APIs and deploys every day, I'd pick Fargate without thinking much. The few dollars extra buy back the evenings I'd spend patching AMIs and tuning instance counts.

My rule of thumb, for what it's worth: start on Fargate arm64. Move to EC2 only when the bill is big enough that 15 to 20 percent of it pays for someone's time, or when you need something Fargate doesn't have, like GPUs.

Checking the Terraform

The full file, with the cluster, log group, both roles, the task definition and the service, is about 160 lines. To check it without an account:

terraform init -backend=false
terraform fmt -check
terraform validate

It needs a VPC with private subnets and a security group to really apply, those come in as variables. The next post in this series puts shorty behind an ALB with HTTPS, and that's where the subnets and security groups get built.