Thuta Learning
AWS Advanced
ContainersDevOpsAdvanced

ECS on Fargate — Running Container Services Without Managing Servers

AWS AdvancedLesson 1350 min

What you'll walk away with

  • Explain the job of a cluster, task definition, task and service
  • Choose between Fargate, Fargate Spot and EC2 capacity for a workload
  • Use the task role and the task execution role correctly
  • Deploy a Fargate service behind an ALB with the circuit breaker and auto scaling
  • Debug a running task with ECS Exec and CloudWatch Logs

Explain it simply

Explain it simply

In AWS Fundamentals you installed and ran an app directly on an EC2 instance. ECS (Elastic Container Service) is an orchestrator: once your app is packaged as a container image, you tell ECS 'always keep two copies of this image running, replace any copy that dies, and register them behind my load balancer', and it does exactly that.

Fargate is the mode where AWS also runs the servers those containers need. There is no instance type to pick, no OS to patch and no disk to watch fill up. You only say how much CPU and memory each copy needs. If EC2 is buying a car and driving it yourself, Fargate is taking a taxi — you pay for the trip, and repairs and fuel are no longer your job.

Problem → Why → Solution

The problem — a task definition that 'works' and is a security hole

When a team first tries ECS, it often writes a task definition like the one below. The app needs to call DynamoDB, nobody knows where container permissions come from, so a developer's access key goes into an environment variable. The database password is in plain text too. The image uses the :latest tag and there is no log configuration.

The deploy works. But anyone with ecs:DescribeTaskDefinition can read the password and the key in the console, in clear text. And when the container crashes there are no logs to tell you why.

taskdef-bad.json
{
  "family": "orders-api",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "name": "web",
      "image": "111122223333.dkr.ecr.us-east-1.amazonaws.com/orders-api:latest",
      "portMappings": [{ "containerPort": 8080 }],
      "environment": [
        { "name": "DB_PASSWORD", "value": "SuperSecret123" },
        { "name": "AWS_ACCESS_KEY_ID", "value": "AKIAIOSFODNN7EXAMPLE" }
      ]
    }
  ]
}

Why this happens

People don't know ECS has two roles. The execution role is used by the ECS agent itself to pull the image, ship logs and read secrets; the task role is what your application code uses when it calls AWS APIs. Set taskRoleArn and the SDK picks up temporary credentials automatically — there is never a reason to put an access key in a container.

Core concept — the four ECS building blocks

Task definition
A versioned JSON blueprint for running one or more containers: image, CPU/memory, ports, environment, secrets, log settings and the two roles. Every change creates a new immutable revision (orders-api:7, :8 ...).

ECS has only four things you must understand. A cluster is just a logical namespace that tasks live in; with Fargate it contains no servers of your own. A task definition is the blueprint. A task is one running instance of that blueprint — a single container, or a group of containers that must live together (for example an app plus a log sidecar).

The service is the most important piece. It is a controller that holds a desired state such as 'always keep two orders-api:7 tasks running'. When a task dies or fails its health check, the service starts a replacement and registers or deregisters it in the ALB target group. One-off work such as a batch job skips the service and runs as a standalone task with run-task.

text
ECS SERVICE ON FARGATE BEHIND AN ALB
------------------------------------
                +---------------- cluster: demo-cluster ----------------+
 Internet       |  service: orders-api  (desired=2, taskdef orders-api:7) |
    |           |                                                       |
    v           |   +------------------+          +------------------+  |
 +-----+  TG    |   | task (AZ a)      |          | task (AZ b)      |  |
 | ALB |--(ip)--+-->| ENI 10.0.11.23   |          | ENI 10.0.12.41   |  |
 +-----+        |   | [web container]  |          | [web container]  |  |
    |           |   +------------------+          +------------------+  |
    +-----------+---------------------------------------^               |
                |   capacity: FARGATE / FARGATE_SPOT (AWS runs hosts)   |
                +-------------------------------------------------------+

On Fargate every task uses the awsvpc network mode and gets its own ENI (elastic network interface) and private IP. That means a security group attaches directly to the task, instead of every container on an EC2 host sharing the host's security group. Because the ALB sends traffic straight to that IP, the target group must be created with target type 'ip'.

Capacity is where tasks run. A capacity provider strategy can mix FARGATE (on-demand) and FARGATE_SPOT. Spot is much cheaper, but when AWS needs the capacity back it gives a two-minute warning and stops the task. 'base' is the minimum number of tasks that always land on the first provider, and 'weight' sets the ratio for every task after that.

FargateEC2 capacity
Server managementAWS does itYou own AMI, patching, scaling
BillingPer task vCPU/GB per secondWhole instances, idle space included
GPU / privileged / host accessNot availableAvailable
Best fitWeb/API, workers, small teamsGPU, large steady fleets

When should you pick EC2 capacity instead? For GPU inference, tools that need privileged containers, or large fleets with flat 24-hour load where you can pack instances tightly and cover them with a Savings Plan. For most other workloads, Fargate's somewhat higher unit price is a fair trade for the operations work it removes.

Mental model
  1. Task definition = blueprint
  2. Service = keeps desired count
  3. Task = containers with own ENI
  4. Capacity provider = where it runs
  5. ALB target group = traffic entry

Think of the service as a control loop: you declare what you want, and ECS keeps working out how to make it true.

A production-ready task definition

taskdef.json
{
  "family": "orders-api",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "runtimePlatform": { "cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX" },
  "executionRoleArn": "arn:aws:iam::111122223333:role/orders-api-execution",
  "taskRoleArn": "arn:aws:iam::111122223333:role/orders-api-task",
  "containerDefinitions": [
    {
      "name": "web",
      "image": "111122223333.dkr.ecr.us-east-1.amazonaws.com/orders-api:1.4.2",
      "essential": true,
      "portMappings": [{ "containerPort": 8080, "protocol": "tcp" }],
      "secrets": [
        {
          "name": "DB_PASSWORD",
          "valueFrom": "arn:aws:secretsmanager:us-east-1:111122223333:secret:db-AbCdEf"
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/orders-api",
          "awslogs-region": "us-east-1",
          "awslogs-stream-prefix": "web"
        }
      },
      "healthCheck": {
        "command": ["CMD-SHELL", "curl -f http://localhost:8080/healthz || exit 1"],
        "interval": 15,
        "timeout": 5,
        "retries": 3,
        "startPeriod": 30
      }
    }
  ]
}

The two roles are separate, and the password is referenced through 'secrets' by its Secrets Manager ARN — ECS reads it with the execution role when the task starts and injects it as an env var, so the value never appears in the task definition. The image tag is an exact version, and the awslogs driver ships stdout to CloudWatch Logs. Choosing ARM64 means the image must be built for arm64, and the health check command needs curl inside the image.

Deploying a Fargate service end to end

This script assumes a VPC, two private subnets, an ALB and a listener already exist (as in the AWS Fundamentals lab). The private subnets need a NAT Gateway or VPC endpoints to reach ECR and CloudWatch Logs. It creates the cluster, log group, task definition, target group and service in order, then waits until the service is stable.

deploy-orders-api.sh
#!/usr/bin/env bash
set -euo pipefail
CLUSTER=demo-cluster
VPC_ID=vpc-0a1b2c3d4e5f67890
SUBNETS=subnet-0a1b2c3d4e5f60001,subnet-0a1b2c3d4e5f60002
TASK_SG=sg-0a1b2c3d4e5f60003

aws ecs create-cluster --cluster-name $CLUSTER \
  --capacity-providers FARGATE FARGATE_SPOT \
  --settings name=containerInsights,value=enabled

aws logs create-log-group --log-group-name /ecs/orders-api
aws logs put-retention-policy --log-group-name /ecs/orders-api --retention-in-days 30

TASKDEF_ARN=$(aws ecs register-task-definition --cli-input-json file://taskdef.json \
  --query 'taskDefinition.taskDefinitionArn' --output text)

TG_ARN=$(aws elbv2 create-target-group --name orders-api-tg \
  --protocol HTTP --port 8080 --vpc-id $VPC_ID --target-type ip \
  --health-check-path /healthz \
  --query 'TargetGroups[0].TargetGroupArn' --output text)
# then forward an ALB listener rule to $TG_ARN (aws elbv2 create-rule)

NETCFG="awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$TASK_SG],"
NETCFG+="assignPublicIp=DISABLED}"
DEPLOY="deploymentCircuitBreaker={enable=true,rollback=true},"
DEPLOY+="maximumPercent=200,minimumHealthyPercent=100"

aws ecs create-service --cluster $CLUSTER --service-name orders-api \
  --task-definition "$TASKDEF_ARN" --desired-count 2 \
  --capacity-provider-strategy capacityProvider=FARGATE,base=2,weight=1 \
      capacityProvider=FARGATE_SPOT,weight=3 \
  --network-configuration "$NETCFG" \
  --load-balancers targetGroupArn=$TG_ARN,containerName=web,containerPort=8080 \
  --health-check-grace-period-seconds 60 \
  --deployment-configuration "$DEPLOY" \
  --enable-execute-command

aws ecs wait services-stable --cluster $CLUSTER --services orders-api
aws ecs describe-services --cluster $CLUSTER --services orders-api \
  --query 'services[0].{status:status,running:runningCount,desired:desiredCount}'

Code breakdown

  1. create-cluster--capacity-providers FARGATE FARGATE_SPOT

    Lets the cluster use both the Fargate and Fargate Spot capacity providers, and turns on Container Insights for per-task CPU and memory metrics.

  2. log groupput-retention-policy ... --retention-in-days 30

    Creates the log group up front and sets retention. The default is 'never expire', so without this the log storage bill only ever grows.

  3. target group--target-type ip

    awsvpc tasks have their own IP, so the target type must be 'ip'. A target group created with 'instance' makes create-service fail.

  4. capacity strategycapacityProvider=FARGATE,base=2,weight=1 capacityProvider=FARGATE_SPOT,weight=3

    The first two tasks always run on on-demand Fargate; any tasks beyond that are split 1:3 (25% on-demand, 75% Spot). Scaling out is cheap, and a Spot interruption still leaves at least two tasks running.

  5. circuit breakerdeploymentCircuitBreaker={enable=true,rollback=true}

    If the new deployment's tasks keep failing to start, ECS marks the deployment FAILED and rolls back to the last revision that worked. minimumHealthyPercent=100 keeps the old tasks until new ones are healthy.

  6. ECS Exec + wait--enable-execute-command / wait services-stable

    ECS Exec must be enabled before tasks start (existing tasks don't pick it up). The wait blocks until the running count equals the desired count.

You should see
Sample output of the last command:
{
    "status": "ACTIVE",
    "running": 2,
    "desired": 2
}
Rolling deployment with the circuit breaker
  1. update-service: revision :8
  2. Start new tasks (max 200%)
  3. Wait for ALB health checks
  4. Drain and stop old tasks

New tasks healthy

COMPLETED

New tasks keep failing

FAILED -> rollback to :7

Task role vs task execution role — who uses which

Task execution roleTask role
Used byThe ECS agent / Fargate platformYour app inside the container
WhenTask start, plus log deliveryThe whole time the app runs
Typical permissionsECR pull, logs, read secretsDynamoDB, S3, SQS, ECS Exec

The error message tells you which role is wrong. If a task goes from PENDING to STOPPED with 'CannotPullContainerError' or 'ResourceInitializationError: unable to pull secrets', it is the execution role (or the network). If the task is running and the app logs show 'AccessDeniedException', it is the task role.

Both roles trust the same principal, ecs-tasks.amazonaws.com. The task role permissions below allow only the app's one DynamoDB table plus the ssmmessages actions that ECS Exec needs.

orders-api-task-role.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AppTable",
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query"],
      "Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/orders"
    },
    {
      "Sid": "EcsExec",
      "Effect": "Allow",
      "Action": [
        "ssmmessages:CreateControlChannel",
        "ssmmessages:CreateDataChannel",
        "ssmmessages:OpenControlChannel",
        "ssmmessages:OpenDataChannel"
      ],
      "Resource": "*"
    }
  ]
}

Service auto scaling

ECS services scale through Application Auto Scaling. The idea matches the EC2 Auto Scaling groups from AWS Fundamentals, but it changes the service's desired count instead of an instance count. Target tracking is the simplest option: say 'keep average CPU around 60%' and it creates the CloudWatch alarms for you.

For a web API, ALBRequestCountPerTarget is often a better signal than CPU because it sees rising load before CPU climbs. A scale-in cooldown longer than the scale-out cooldown stops task counts from flapping up and down.

autoscale.sh
RESOURCE_ID=service/demo-cluster/orders-api

aws application-autoscaling register-scalable-target \
  --service-namespace ecs --resource-id $RESOURCE_ID \
  --scalable-dimension ecs:service:DesiredCount \
  --min-capacity 2 --max-capacity 10

cat > cpu60.json <<'EOF'
{
  "TargetValue": 60.0,
  "PredefinedMetricSpecification": {
    "PredefinedMetricType": "ECSServiceAverageCPUUtilization"
  },
  "ScaleOutCooldown": 60,
  "ScaleInCooldown": 300
}
EOF

aws application-autoscaling put-scaling-policy --policy-name cpu60 \
  --service-namespace ecs --resource-id $RESOURCE_ID \
  --scalable-dimension ecs:service:DesiredCount \
  --policy-type TargetTrackingScaling \
  --target-tracking-scaling-policy-configuration file://cpu60.json

Debugging with ECS Exec and logs

Fargate has no host to SSH into. ECS Exec uses Systems Manager Session Manager behind the scenes to open a shell inside a running container. It needs three things: the service has --enable-execute-command, the task role has the ssmmessages permissions, and your machine has the Session Manager plugin installed. Every session is recorded in CloudTrail, and the cluster can be configured to log session output to CloudWatch Logs or S3.

For logs, 'aws logs tail /ecs/orders-api --follow' in CLI v2 is the most convenient. To hunt for errors, use filter-log-events with a pattern.

debug.sh
TASK_ARN=$(aws ecs list-tasks --cluster demo-cluster --service-name orders-api \
  --query 'taskArns[0]' --output text)

# why did a task stop? (stoppedReason is the first thing to read)
aws ecs describe-tasks --cluster demo-cluster --tasks $TASK_ARN \
  --query 'tasks[0].{last:lastStatus,reason:stoppedReason}'

# open a shell in the running "web" container
aws ecs execute-command --cluster demo-cluster --task $TASK_ARN \
  --container web --interactive --command "/bin/sh"

# recent ERROR lines from the container logs
aws logs filter-log-events --log-group-name /ecs/orders-api \
  --filter-pattern ERROR --max-items 20

In production

How teams run this in production

Most teams never create ECS resources in the console. The cluster, service, roles and ALB live in CDK or Terraform, and the CI pipeline tags the image with the git commit SHA, pushes it to ECR, registers a new task definition revision and calls update-service. Every revision then maps to exactly one commit, and rolling back means pointing the service at the previous revision.

VPC endpoints are another key production piece. Tasks in private subnets that pull images through a NAT Gateway pay a per-GB processing fee. Adding ECR (api and dkr) interface endpoints, the S3 gateway endpoint and a CloudWatch Logs endpoint saves that cost and lets you remove the path to the internet entirely.

  • Fargate Spot is used mainly for stateless workers, queue consumers and dev/test environments; customer-facing APIs mix it with an on-demand base.
  • The app must catch SIGTERM and finish in-flight requests — both Spot interruptions and deployments stop tasks with SIGTERM.
  • Teams lower the ALB target group's deregistration delay from the default 300 seconds to match their longest request, which makes deployments much faster.
  • For blue/green, teams pair ECS with CodeDeploy; ECS now also offers a built-in blue/green deployment option — check what your tooling supports.

Common mistakes

Common mistakes

Mistake 1 — image pulls fail from private subnets

Put tasks in a private subnet with assignPublicIp=DISABLED and no NAT Gateway or VPC endpoints, and they stop with 'CannotPullContainerError'. People often forget that ECR stores image layers in S3, so besides the ecr.api and ecr.dkr interface endpoints you also need the S3 gateway endpoint. Shipping logs needs a logs endpoint, and reading secrets needs a secretsmanager endpoint.

Mistake 2 — no health check grace period, every deploy rolls back

For an app that takes 40-60 seconds to boot (Java or Spring, for example), without a health check grace period the ALB marks the new task unhealthy shortly after it starts and ECS kills it. The circuit breaker sees this as a failed deployment and rolls back, so deploys fail even though the code is fine. Set the grace period a little longer than the app's startup time.

Mistake 3 — adding permissions to the wrong role

When the app gets AccessDenied reading S3, people add s3:GetObject to the execution role and then spend hours wondering why nothing changed. Application code only ever uses the task role. The reverse mistake is common too: put the secret-reading permission in the task role and the 'secrets' field still fails, because ECS reads it with the execution role.

Best practices

Best practices

  • Give each service its own least-privilege task role.
  • Reference images by version tag or digest — never :latest.
  • Always enable the circuit breaker with rollback=true.
  • Set retention on every log group.
  • Run at least two tasks in production, across subnets in different AZs.

💰 Cost & Cleanup

Fargate has no free tier: you pay for the task's vCPU and memory per second (1-minute minimum) from when the image pull starts until the task stops. Fargate Spot is substantially cheaper. The ALB costs per hour plus per LCU, a NAT Gateway per hour plus per GB processed, and CloudWatch Logs per GB ingested. Delete the lab with the commands below as soon as you finish — two tasks and an ALB left running around the clock add up. Check the AWS pricing pages for exact rates.

Clean up when you are done

cleanup.sh
aws application-autoscaling deregister-scalable-target --service-namespace ecs \
  --resource-id service/demo-cluster/orders-api \
  --scalable-dimension ecs:service:DesiredCount
aws ecs delete-service --cluster demo-cluster --service orders-api --force
aws ecs wait services-inactive --cluster demo-cluster --services orders-api
aws ecs deregister-task-definition --task-definition orders-api:1
aws ecs delete-cluster --cluster demo-cluster
aws elbv2 delete-target-group --target-group-arn $TG_ARN
aws logs delete-log-group --log-group-name /ecs/orders-api

Mini challenge

Mini challenge — a Fargate service in CDK

Rewrite this lesson's CLI deployment as an AWS CDK app: a Fargate service behind an ALB with the production settings from the lesson.

  • Keep 2 tasks as an on-demand Fargate base and split the rest 1:3 with Fargate Spot
  • Enable the circuit breaker with rollback, and enable ECS Exec
  • Scale from 2 to 10 tasks with CPU 60% target tracking

Expected: cdk synth produces a template with an ECS cluster, a service with two capacity provider strategies and a DeploymentCircuitBreaker, an ALB, a target group and a ScalableTarget plus ScalingPolicy.

Show hint

Use ApplicationLoadBalancedFargateService from aws-ecs-patterns, and remember enableFargateCapacityProviders: true on the cluster.

Show solution
bin/orders-api.ts
import { App, Stack } from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as ecsPatterns from "aws-cdk-lib/aws-ecs-patterns";

const app = new App();
const stack = new Stack(app, "OrdersApiStack");

const vpc = new ec2.Vpc(stack, "Vpc", { maxAzs: 2, natGateways: 1 });
const cluster = new ecs.Cluster(stack, "Cluster", {
  vpc,
  enableFargateCapacityProviders: true,
});

const svc = new ecsPatterns.ApplicationLoadBalancedFargateService(stack, "Api", {
  cluster,
  cpu: 512,
  memoryLimitMiB: 1024,
  desiredCount: 2,
  taskImageOptions: {
    // pin a version tag or digest in production
    image: ecs.ContainerImage.fromRegistry("public.ecr.aws/nginx/nginx:stable"),
    containerPort: 80,
  },
  circuitBreaker: { rollback: true },
  enableExecuteCommand: true,
  capacityProviderStrategies: [
    { capacityProvider: "FARGATE", base: 2, weight: 1 },
    { capacityProvider: "FARGATE_SPOT", weight: 3 },
  ],
});
svc.targetGroup.configureHealthCheck({ path: "/" });

const scaling = svc.service.autoScaleTaskCount({ minCapacity: 2, maxCapacity: 10 });
scaling.scaleOnCpuUtilization("Cpu60", { targetUtilizationPercent: 60 });

app.synth();

Quick quiz 1 / 3

A task fails to start with 'ResourceInitializationError: unable to pull secrets'. Which permission should you check, and where?

Quick quiz 2 / 3

The strategy is FARGATE base=2 weight=1 and FARGATE_SPOT weight=3. With a desired count of 10, how many tasks run on Spot?

Quick quiz 3 / 3

Which target type must the target group use to put Fargate tasks behind an ALB?

What to remember

  • The service keeps the desired count; task definition revisions are immutable blueprints.
  • Execution role = ECS agent for images, logs and secrets; task role = your app code.
  • Every Fargate task gets its own ENI, so security groups apply per task and target groups use type 'ip'.
  • A base + weight capacity strategy mixes in Fargate Spot safely.
  • Circuit breaker rollback, a grace period and ECS Exec make deploying and debugging safe.

Amazon ECS Developer Guide — AWS Documentation

AWS Fargate for Amazon ECS — AWS Documentation

Monitor Amazon ECS containers with ECS Exec — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.