irfan@backend:~/portfolio
Email me
← cd ../blog

AWS / ECS / Deployment / Beginner

ECS Fargate from Zero: one API, from first deploy to CI/CD

A beginner guide to ECS Fargate: how the pieces fit, a first deploy behind a load balancer, then CI/CD from GitHub Actions with OIDC and no AWS keys.

On this page
  1. ECS and Fargate
  2. When to pick Fargate
  3. The four ECS objects
  4. The load balancer
  5. Health check settings
  6. Why a separate /health route
  7. The two IAM roles
  8. Push to ECR
  9. Before you start
  10. Create the repository
  11. Why immutable tags
  12. The task definition
  13. Create the log group first
  14. Check the execution role
  15. Register it with JSON
  16. Service, ALB and security groups
  17. Step by step in the Console
  18. Follow one request
  19. The same setup with the CLI
  20. Test, debug and clean up
  21. Test it
  22. When it does not work
  23. Clean up
  24. OIDC
  25. The deploy role
  26. 1. The identity provider
  27. 2. The trust policy
  28. 3. The permissions policy
  29. The deploy workflow
  30. Rolling deploys and rollback
  31. A good deploy
  32. A bad deploy and the circuit breaker
  33. Rolling back by hand
  34. Recap

You have a Docker image of a small API called hello-api. This post takes it to AWS. First you learn how ECS fits together, then you deploy it behind a load balancer. Then GitHub Actions deploys every push, with no stored AWS keys.

After this post you can:

  • name every ECS object, and pick the right IAM role for a job
  • deploy hello-api as 2 tasks behind a load balancer, debug it, and clean it up
  • deploy on every push to main with OIDC, and explain how a bad deploy rolls back

You need the hello-api app from Docker from Zero. Build that image first if you haven't.

ECS and Fargate#

Here is how you might run an API on one server by hand:

docker run -d --restart=always -p 3000:3000 hello-api

It works. Then the server dies at night. Or traffic grows and you need a second copy. Or a new version ships and users see errors while the old container stops.

Now you are writing scripts for restarts, copies and deploys. A container service does those jobs for you.

Words you need:

  • ECS (Elastic Container Service): AWS's service that starts your containers, watches them, and replaces them when they fail or when you deploy.
  • Fargate: a way to run ECS containers where AWS owns and patches the servers. You only pick CPU and memory for each copy.
  • EC2 launch type: the other way. ECS runs your containers on EC2 virtual machines that you create, patch and scale.

With Fargate you pay for the CPU and memory you asked for, while it runs. The Fargate pricing page says Linux tasks are billed per second with a 1-minute minimum. Billing starts when the image download starts and stops when the task ends.

When to pick Fargate#

Here is Fargate next to ECS on EC2 and Google Cloud Run (from my Cloud Run guide):

ECS on FargateECS on EC2Cloud Run
You managetask definitions, services, a load balancerall of that, plus the EC2 machinesyour container and its settings
No traffictasks keep running and billingmachines keep running and billingscales to zero by default
Good forteams on AWS who don't want serversGPUs, special host settingsapps on Google Cloud

My rule: on AWS, start with Fargate. Move to EC2 only when you hit something Fargate can't do, like a GPU.

quick-check

Your API needs a GPU. Which ECS option fits?

quick-check

How does Fargate bill a Linux task?

The four ECS objects#

Words you need:

  • ECR (Elastic Container Registry): AWS's private image registry, like Docker Hub inside your account. Tasks pull their image from it when they start.
  • vCPU: one virtual CPU core. 256 CPU units is a quarter of one core.

Now look at a cut-down task definition for hello-api:

{
  "family": "hello-api",
  "cpu": "256",
  "memory": "512",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "containerDefinitions": [
    {
      "name": "hello-api",
      "image": "123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/hello-api:3f9c2a1",
      "portMappings": [{ "containerPort": 3000 }]
    }
  ]
}

This file runs nothing. It is a recipe: which image, how much CPU and memory, and which port.

  • Size: 256 is the CPU (a quarter core), and 512 is the memory in MiB.
  • Fargate rules: "networkMode": "awsvpc" gives each task its own network card and private IP, and Fargate needs it. "requiresCompatibilities": ["FARGATE"] asks ECS to check the file is valid for Fargate.

You register the file with ECS, and it becomes hello-api:1. Change the image tag and register again, and you get hello-api:2. A revision never changes after you register it. Every change makes a new one.

The four objects:

  • Task definition: the JSON recipe. It holds the image, CPU, memory, ports, environment variables, roles and log settings. Each change makes a new revision.
  • Task: one running copy of a task definition. hello-api has one container, so one task is one container.
  • Service: keeps a set number of tasks running (the desired count). It replaces tasks that die, connects them to the load balancer, and rolls out new revisions.
  • Cluster: a named group for your services and tasks. With Fargate there are no servers inside it to look after.

In Docker from Zero, an image was like a class and a container like an object. Here, a task definition is the class, a task is the object, and a service is a manager that keeps exactly N objects alive.

When do you touch each one?

  • New image, new environment variable, more memory: register a new task definition revision.
  • More copies, or switch to a new revision: update the service.
  • The cluster: you create it once and rarely change it.
quick-check

You need to change an environment variable of hello-api. What do you do?

Quick check: the service has a desired count of 2. One task crashes at 3 a.m. What happens?

Show answer

The service sees 1 running task and wants 2. It starts a new task from the same revision, without you doing anything. That is the main job of a service.

The load balancer#

On Fargate, each task gets its own private IP address. So why not give that IP to your users?

Two reasons. A task's IP changes every time the task is replaced: after a crash, a deploy or a scale change. And with 2 tasks, which IP would you give out? You need one fixed address in front of all tasks.

Words you need:

  • ALB (Application Load Balancer): AWS's HTTP load balancer. It has one fixed DNS name and sends each request to a healthy task.
  • Listener: the port and protocol where the ALB takes requests, for example HTTP on port 80.
  • Target group: the list of places the listener sends requests to. Here, the IP and port of each task. The ECS service adds and removes tasks for you.
  • Health check: the ALB calls a path on each target again and again, to see if it still answers.

For Fargate, the target group must use the ip target type, not instance (ECS docs). The ALB sends traffic to the task's own IP, because there is no EC2 machine to send it to.

Health check settings#

These are the target group defaults from the ALB health check docs, and what hello-api uses:

SettingDefaultFor hello-api
Path//health
Intervalevery 30 secondskeep
Timeout5 secondskeep
Unhealthy after2 failed checks in a rowkeep
Healthy again after5 passed checks in a rowkeep
Success code200keep

A brand new target is different. The docs say it must pass one check to be healthy. So a new task gets traffic after its first good check. The 5-in-a-row rule is only for a target that was unhealthy before.

Watch what happens when one task stops answering:

health-check-fails
  1. The ALB calls GET /health on task 1 and task 2 every 30 seconds.
  2. Task 2 hangs, and its check gets no answer within 5 seconds.
  3. A second failed check in a row: the ALB marks task 2 unhealthy.
  4. The ALB sends new requests only to task 1.
  5. The ECS service sees the failed health check and stops task 2.
  6. The service starts a new task in place of task 2. It passes its first check, and it gets traffic.
step 1 / 6
Users only ever reach task 1 while task 2 is broken.

One surprise from the same docs: if every target is unhealthy, the ALB sends traffic to all of them anyway. The docs call this "fail open". So a health check that fails everywhere does not protect your users.

Why a separate /health route#

hello-api has a tiny /health route that only returns {"status":"ok"}. Why not point the check at a real page, like /orders?

A real page may call the database. If the database is slow for a minute, every task fails its check. The service then replaces all of them, even though the containers were fine.

A light /health route answers one question only: is this process alive and able to take requests?

quick-check

The target group checks /healthz, but hello-api only has /health. What happens?

The two IAM roles#

Think about two jobs:

  1. Before your code starts, something must download the image from ECR and set up the log stream in CloudWatch (AWS's log service).
  2. While your code runs, your app calls s3.getObject() to read a file.

Both jobs need AWS permissions. But different things do them, so they use different roles.

Words you need:

  • IAM (Identity and Access Management): the AWS system that decides who can do what.
  • IAM role: an identity with permissions that a service can take on for a while. It gets short-lived keys, never a stored password.
  • Policy: a JSON list of allowed actions, like ecr:BatchGetImage.
  • Agent: AWS's own program that runs next to your container. It pulls the image, starts the container and ships the logs. On Fargate you never see it.
  • S3: AWS's file storage. Secrets Manager and SSM Parameter Store are AWS places to keep passwords and settings.
Task execution roleTask role
Used byECS and the Fargate agentyour app code
Whenaround your container: pull the image, send logs, read secretswhile your app runs and calls AWS
Usual permissionsthe AWS managed policy AmazonECSTaskExecutionRolePolicyonly what your app needs, like reading one S3 bucket
Does hello-api need it?yesno, leave it empty

The managed policy has six actions. Four are for pulling from ECR, and two are for logs: logs:CreateLogStream and logs:PutLogEvents (policy reference).

It does not have logs:CreateLogGroup. Remember that. In the task definition chapter you create the log group yourself because of it.

Two more facts from the execution role docs:

  • Your containers can't see the execution role's keys. The docs say they "aren't directly accessible by the containers in the task". Only the agent uses them.
  • Reading secrets from Secrets Manager or SSM Parameter Store at start needs extra permissions on the execution role.

Every role also has a trust policy: a rule that says who may take on the role. For both of these roles, it names ecs-tasks.amazonaws.com, the AWS service that runs ECS tasks. Without that rule, ECS could not use the role.

quick-check

Which role pulls the image from ECR?

quick-check

Your app uploads files to S3 and gets AccessDenied. Which role needs s3:PutObject?

Push to ECR#

Now hello-api goes live. By the end of this chapter and the next three, it runs as 2 tasks behind a load balancer. Only the load balancer can reach them.

Before you start#

Plan a couple of hours for your first run, and do it in one sitting.

This costs money while it runs. Fargate bills each task per second, and the ALB bills for every hour it exists.

Every public IPv4 address also costs $0.005 per hour (VPC pricing). That includes the ALB's own addresses. Do the cleanup (Test, debug and clean up chapter) when you finish.

You need:

  • The hello-api folder and Dockerfile from Docker from Zero, in a git repo with at least one commit.
  • AWS CLI v2 and Docker on your laptop.
  • One region for everything. I use ap-southeast-1 (Singapore).

Words you need:

  • IAM Identity Center: AWS's single sign-on. It gives the CLI short-lived keys after a browser login.
  • Start URL: the web address of your sign-in page, like https://my-sso-portal.awsapps.com/start.
  • Permission set: Identity Center's name for a group of permissions.

Sign in to the CLI with Identity Center. Older guides tell you to make an IAM user and paste a long-lived access key into aws configure. Skip that.

A key stored on your laptop never expires on its own. It also works for anyone who copies it.

Set up a user for yourself with the Identity Center getting started guide. It gives you your start URL.

The CLI docs suggest the AWS managed PowerUserAccess for development. It covers ECR, ECS, EC2 and CloudWatch, but blocks IAM. This post creates IAM roles.

  • On your own learning account, also add IAMFullAccess. Know that it is admin access in practice: a user with it can attach AdministratorAccess to itself.
  • At work, ask your admin to create the roles. Also ask for iam:PassRole on those roles. PowerUserAccess blocks it too, so registering a task definition that names executionRoleArn would fail.

Then:

aws configure sso          # asks for your start URL and region, opens the browser
export AWS_PROFILE=learn   # the profile name you picked in the wizard
aws sso login              # run this again when the session expires
aws sts get-caller-identity

The last command prints your account ID. I use 123456789012 as a fake one below. Replace it with yours.

Create the repository#

Words you need:

  • Immutable tags: ECR refuses a second push with a tag that already exists.
  • Scan on push: ECR checks each new image for known security bugs (CVEs).

In the Console:

  1. Open ECR, choose Create repository.
  2. Name: hello-api. Image tag mutability: Immutable. Create.
  3. Go to Private registry, then Scanning. Keep Basic scanning and add a scan on push filter for hello-api.

Step 3 is on its own page. Scan on push lives in the registry's scanning settings (ECR image scanning docs, how to turn it on).

Now build and push from the hello-api folder:

REGISTRY=123456789012.dkr.ecr.ap-southeast-1.amazonaws.com
TAG=$(git rev-parse --short HEAD)    # for example 3f9c2a1

aws ecr get-login-password --region ap-southeast-1 \
  | docker login --username AWS --password-stdin "$REGISTRY"

docker build --platform linux/amd64 -t "$REGISTRY/hello-api:$TAG" .
docker push "$REGISTRY/hello-api:$TAG"

Line by line:

  • get-login-password | docker login: Docker can't use your AWS login directly. This swaps it for a registry password that is valid for 12 hours (ECR auth docs).
  • --platform linux/amd64: a Mac with Apple Silicon builds arm64 images by default. The task definition (next chapter) asks for X86_64. A mismatch makes the container fail on start with exec format error.
  • The tag is the commit SHA. Each tag points to exactly one commit. You always know what code runs, and a rollback means "deploy the old tag".

Why immutable tags#

When do you hit this? The day someone pushes hello-api:latest again, and the tag now means different code.

With immutable tags, ECR refuses a second push with the same tag and returns ImageTagAlreadyExistsException. Together with SHA tags, a tag can never change under you.

Open the image in the ECR console after the push. The scan result shows any known CVEs in the image. For a gate that fails the build before the push, use Trivy from Docker from Zero.

quick-check

The repository has immutable tags. You change a file and push again with the same tag 3f9c2a1. What happens?

The task definition#

Words you need:

  • Log group: a named bucket in CloudWatch Logs. Each task writes its own log stream inside it.
  • Retention: how long CloudWatch keeps the logs.
  • ARN (Amazon Resource Name): the full, unique ID of an AWS resource.

Create the log group first#

What do you think happens if the log group in your task definition does not exist?

The task can't start. The execution role's managed policy has no logs:CreateLogGroup (two IAM roles chapter). So create the group yourself:

  1. Open CloudWatch, then Log groups, Create log group.
  2. Name: /ecs/hello-api. Retention: 1 month.

Retention matters because CloudWatch keeps logs forever by default (CloudWatch Logs docs).

Check the execution role#

Open IAM, then Roles, and search for ecsTaskExecutionRole. Many accounts already have it.

If not: Create role, AWS service, Elastic Container Service, use case Elastic Container Service Task. Attach AmazonECSTaskExecutionRolePolicy, and name it ecsTaskExecutionRole.

Register it with JSON#

Open ECS, then Task definitions, Create new task definition with JSON. Paste the JSON below, with your account ID and tag.

Also save it as task-definition.json in the hello-api folder. The CLI box in the next chapter uses that file.

// task-definition.json (key lines)
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": "X86_64" },
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  // ...
      "image": "123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/hello-api:3f9c2a1",
      "essential": true,
      // ...
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/hello-api",
          "awslogs-region": "ap-southeast-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
Show full code: task-definition.json
{
  "family": "hello-api",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": "X86_64" },
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "name": "hello-api",
      "image": "123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/hello-api:3f9c2a1",
      "essential": true,
      "portMappings": [{ "containerPort": 3000, "protocol": "tcp" }],
      "environment": [{ "name": "PORT", "value": "3000" }],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/hello-api",
          "awslogs-region": "ap-southeast-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
    }
  ]
}
FieldValueWhy
familyhello-apithe name; this first one becomes hello-api:1
networkModeawsvpcrequired on Fargate; each task gets its own network interface and private IP
cpu, memory256, 5120.25 vCPU and 512 MiB, the smallest Fargate size
runtimePlatformLinux, X86_64must match the --platform you built with
executionRoleArnecsTaskExecutionRolelets the agent pull the image and write logs
image...:3f9c2a1the exact tag you pushed
portMappings3000the port hello-api listens on
essentialtrueif this container stops, the whole task stops, so the service replaces it
logConfigurationawslogssends what the app prints to /ecs/hello-api; the stream prefix is required on Fargate

There is no taskRoleArn. hello-api never calls AWS, so it gets no AWS permissions at all.

Two notes:

  • Watch for "awslogs-create-group": "true". JSON copied from other guides often has it. It needs logs:CreateLogGroup (API reference), which the execution role lacks. Remove it, since your group exists already.

  • Never put a password in environment. Anyone who can read the task definition can read it. Store it in SSM Parameter Store or Secrets Manager instead. Then point to it in the container's secrets field:

    "secrets": [
      {
        "name": "DATABASE_URL",
        "valueFrom": "arn:aws:ssm:ap-southeast-1:123456789012:parameter/hello-api/database-url"
      }
    ]
    

    ECS reads the value when the task starts and gives it to your app as the DATABASE_URL environment variable. The execution role then needs ssm:GetParameters on that one parameter (execution role docs). hello-api has no secrets, so it skips this.

quick-check

Your task stops before the app prints anything. The stopped reason says access was denied while creating the log group. What is the smallest fix?

Service, ALB and security groups#

Words you need:

  • VPC: your private network in AWS. Every account has a default VPC in each region.
  • Subnet: one slice of the VPC, in one Availability Zone (one data center group). The default VPC's subnets are public: they have a route to the internet.
  • Security group (SG): a firewall around one resource. Inbound rules say who may connect, and on which port.

Here is the plan. Two security groups, and the task group trusts only the ALB group:

Step by step in the Console#

  1. EC2, Security groups, Create. Name hello-api-alb-sg, default VPC. Inbound: HTTP, port 80, source 0.0.0.0/0.
  2. Create a second one. Name hello-api-task-sg. Inbound: Custom TCP, port 3000, source: the security group hello-api-alb-sg, not an IP range.
  3. EC2, Target groups, Create. Target type IP addresses. Name hello-api-tg, HTTP, port 3000, default VPC. Health check path /health. Register no targets; ECS does that.
  4. EC2, Load balancers, Create, Application Load Balancer. Name hello-api-alb, internet-facing, default VPC, at least 2 subnets in different zones. Security group: only hello-api-alb-sg. Listener: HTTP 80, forward to hello-api-tg.
  5. ECS, Clusters, Create cluster. Name hello-api-cluster. Fargate is the default.
  6. Open the cluster, Services, Create:
    • Compute options: Launch type, FARGATE.
    • Task definition hello-api, latest revision. Service name hello-api-service. Desired tasks: 2.
    • Health check grace period: 30 seconds, so a task gets time to boot before checks count.
    • Deployment failure detection: leave circuit breaker and rollback on failures on. They are on by default, and the rolling deploys chapter explains them.
    • Networking: default VPC, the same subnets as the ALB, security group only hello-api-task-sg, Public IP on.
    • Load balancing: Application Load Balancer, use an existing load balancer, hello-api-alb.
    • Container to load balance: hello-api 3000. Pick the existing listener on 80 and the existing target group hello-api-tg.

Set the load balancer now. The ECS docs say you can't change it later from the Console, only with the CLI or an SDK.

Why Public IP on? A task in a public subnet needs a public IP to reach ECR and pull its image (Fargate networking docs). It is still safe here, because hello-api-task-sg blocks everyone except the ALB.

In production, tasks usually sit in private subnets with no public IP. They reach ECR through a NAT gateway or VPC endpoints.

  • NAT gateway: a paid AWS box that lets private resources call out to the internet.
  • VPC endpoint: a private link from your VPC straight to one AWS service.

Production also needs HTTPS. Add a listener on port 443 with a free certificate from AWS Certificate Manager, and redirect port 80 to it.

The certificate needs a domain you own, pointed at the ALB. You can't get one for the elb.amazonaws.com name. So this post stays on plain HTTP.

Follow one request#

request-through-the-alb
  1. You run curl http://hello-api-alb-123.ap-southeast-1.elb.amazonaws.com/health
  2. The ALB security group allows port 80 from anywhere, so it gets in.
  3. The listener on port 80 forwards it to the target group hello-api-tg.
  4. The target group picks a healthy task, for example 172.31.5.20 on port 3000.
  5. The task security group lets it in, because it comes from the ALB security group.
  6. Express (the web framework hello-api uses) answers {"status":"ok"}
  7. The task answers the ALB, and the ALB sends the answer back to you.
step 1 / 7
A request sent straight to a task's public IP is blocked by the task security group.
quick-check

You set the task security group to allow port 3000 from 0.0.0.0/0. What is the problem?

The same setup with the CLI#

Fill in your own IDs. Each command prints the ID or ARN the next one needs. Run them from the hello-api folder, where you saved task-definition.json.

# setup with the CLI (key lines)
aws elbv2 create-target-group --name hello-api-tg --protocol HTTP --port 3000 \
  --vpc-id vpc-0abc --target-type ip --health-check-path /health
# ...
aws ecs create-service --cluster hello-api-cluster --service-name hello-api-service \
  --task-definition hello-api --desired-count 2 --launch-type FARGATE \
  --health-check-grace-period-seconds 30 \
  --deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true}" \
Show full code: the same setup with the CLI
aws ec2 create-security-group --group-name hello-api-alb-sg \
  --description "hello-api ALB" --vpc-id vpc-0abc
aws ec2 authorize-security-group-ingress --group-id sg-alb \
  --protocol tcp --port 80 --cidr 0.0.0.0/0

aws ec2 create-security-group --group-name hello-api-task-sg \
  --description "hello-api tasks" --vpc-id vpc-0abc
aws ec2 authorize-security-group-ingress --group-id sg-task \
  --protocol tcp --port 3000 --source-group sg-alb

aws elbv2 create-target-group --name hello-api-tg --protocol HTTP --port 3000 \
  --vpc-id vpc-0abc --target-type ip --health-check-path /health
aws elbv2 create-load-balancer --name hello-api-alb \
  --subnets subnet-a subnet-b --security-groups sg-alb
aws elbv2 create-listener --load-balancer-arn ALB_ARN --protocol HTTP --port 80 \
  --default-actions Type=forward,TargetGroupArn=TG_ARN

aws logs create-log-group --log-group-name /ecs/hello-api
aws logs put-retention-policy --log-group-name /ecs/hello-api --retention-in-days 30
aws ecs register-task-definition --cli-input-json file://task-definition.json
aws ecs create-cluster --cluster-name hello-api-cluster

aws ecs create-service --cluster hello-api-cluster --service-name hello-api-service \
  --task-definition hello-api --desired-count 2 --launch-type FARGATE \
  --health-check-grace-period-seconds 30 \
  --deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true}" \
  --network-configuration "awsvpcConfiguration={subnets=[subnet-a,subnet-b],securityGroups=[sg-task],assignPublicIp=ENABLED}" \
  --load-balancers targetGroupArn=TG_ARN,containerName=hello-api,containerPort=3000

The Console turns the circuit breaker on by default. With the CLI, set it yourself, like above. The CLI uses the region from your profile.

Test, debug and clean up#

Words you need:

  • Stopped reason: the message ECS keeps on a task that stopped. It says why.
  • Reason code: the short code the target group shows for an unhealthy target, like Target.Timeout.

Test it#

Copy the ALB's DNS name from EC2, Load balancers. Then:

curl -i http://hello-api-alb-123.ap-southeast-1.elb.amazonaws.com/health

You get HTTP/1.1 200 OK and {"status":"ok"}. Check two more places:

  • EC2, Target groups, hello-api-tg, Targets: 2 targets, both healthy.
  • The logs: aws logs tail /ecs/hello-api --follow prints listening on port 3000 once per task.

When it does not work#

Look in this order: the service's Events tab, the stopped reason of a stopped task, the target group's Targets tab, then the logs. The target health reason codes come from the ALB docs.

Common failures and their fixes
What you seeLikely causeFix
Task stops with CannotPullContainerErrorwrong image URI or tag, or Public IP off in a public subnetcopy the URI from ECR, turn Public IP on
exec format error in the logsan arm64 image on an X86_64 taskrebuild with --platform linux/amd64, push a new tag
Target unhealthy, Target.ResponseCodeMismatchthe check path returns 404set the health check path to /health
Target unhealthy, Target.Timeoutthe task SG does not allow 3000 from the ALB SG, so the check gets no answerfix the SG rule
Target unhealthy, Target.FailedHealthChecksnothing listens on port 3000: wrong port, or the app listens on 127.0.0.1listen on 0.0.0.0 and the port in portMappings (Docker from Zero)
Tasks start, stop, start againthe app crashes on boot, often a missing environment variableread the logs for the first error
quick-check

Both targets show Target.Timeout. The app logs say listening on port 3000. What do you check first?

Clean up#

Delete in this order. A security group can't go while something still uses it or a rule points at it.

aws ecs delete-service --cluster hello-api-cluster --service hello-api-service --force
aws ecs delete-cluster --cluster hello-api-cluster
aws elbv2 delete-load-balancer --load-balancer-arn ALB_ARN
aws elbv2 delete-target-group --target-group-arn TG_ARN
aws ec2 delete-security-group --group-id sg-task    # first: it points at sg-alb
aws ec2 delete-security-group --group-id sg-alb
aws ecr delete-repository --repository-name hello-api --force
aws logs delete-log-group --log-group-name /ecs/hello-api

Wait until the tasks have stopped before the cluster delete. If a security group delete fails with DependencyViolation, wait a few minutes and run it again. The Console works in the same order.

Doing the CI/CD chapters next? Keep everything and clean up after. When you are done with those too, also delete the github-deploy-hello-api role and the GitHub identity provider in IAM.

OIDC#

You deployed hello-api by hand: build, push, register a revision, update the service. That is fine once. On every change it gets slow, and a tired person skips a step.

So now you set up CI/CD (continuous integration and continuous delivery): a robot that builds and deploys every change the same way. Here the robot is GitHub Actions. It deploys on every push to main, without a single AWS key stored in GitHub.

Here is the old way, which many guides still show:

# the old way: do not copy this
- uses: aws-actions/configure-aws-credentials@v4
  with:
    aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
    aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

That key never expires on its own. It works from any computer until someone deletes it. If it leaks, from a log line or a laptop, the attacker gets all of its access. Here is the new way:

permissions:
  id-token: write
  contents: read
steps:
  - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
    with:
      role-to-assume: arn:aws:iam::123456789012:role/github-deploy-hello-api
      aws-region: ap-southeast-1

No secret at all. Just a role name, which is not a secret.

Words you need:

  • OIDC (OpenID Connect): a standard way for one system to prove who it is to another, with a signed token.
  • ID token: a short-lived signed token that GitHub makes for one workflow run. It holds claims: facts like the repo name and branch.
  • sub claim: the subject. It says which repo, and which branch or environment, the run comes from.
  • aud claim: the audience. It says who the token is for. For AWS it is sts.amazonaws.com.
  • STS (Security Token Service): the AWS service that swaps a trusted token for temporary AWS keys.

When do you use OIDC? Any time a CI system needs to call a cloud. My Cloud Run guide uses the same idea on Google Cloud, where it is called Workload Identity Federation.

Watch one deploy job get its keys:

oidc-token-exchange
  1. The job asks GitHub for an ID token.
  2. GitHub sends back a signed token with the sub and aud claims.
  3. The job calls AssumeRoleWithWebIdentity with the token and the role ARN.
  4. STS checks the signature and the trust policy.
  5. STS sends back temporary AWS keys, valid 1 hour.
  6. The job pushes the image and updates the service.
step 1 / 6
No key is stored anywhere. Each run gets its own keys, and they expire.

The same flow as a diagram:

The keys expire after 1 hour, the default in configure-aws-credentials. Nothing long-lived exists to steal.

quick-check

Why is OIDC safer than an access key in GitHub secrets?

The deploy role#

You set up three things in IAM, once.

Words you need:

  • Trust policy: the part of a role that says who may use it. The permissions policy says what the role may do.
  • GitHub environment: a named deploy target in the repo settings, like production, with its own rules.
  • Least privilege: only the actions a job uses, on only its own resources.

1. The identity provider#

IAM, Identity providers, Add provider:

  • Provider type: OpenID Connect
  • Provider URL: https://token.actions.githubusercontent.com
  • Audience: sts.amazonaws.com

This tells AWS to trust tokens signed by GitHub. Older guides also ask for a certificate thumbprint. The configure-aws-credentials README says a thumbprint you give is ignored.

2. The trust policy#

Our workflow runs in the production environment. The rule we want: only the main branch may deploy to it.

Why does that matter here? The GitHub OIDC docs say a job that uses an environment sends the environment form of sub. It has no branch in it:

The jobIts sub claim
push to main, no environmentrepo:my-org/hello-api:ref:refs/heads/main
uses environment: productionrepo:my-org/hello-api:environment:production
runs on a pull requestrepo:my-org/hello-api:pull_request

These are the name forms. Newer repos add numeric IDs to the names, as shown below.

If the trust policy expects the branch form but the job sends the environment form, the login fails. The error is Not authorized to perform sts:AssumeRoleWithWebIdentity.

There is one more twist. Repos created after July 15, 2026 put numeric IDs after the names in sub (GitHub changelog). So do repos renamed or moved after that date, and older repos can opt in.

With IDs in sub, a stranger who later takes your old org name can't match your policy. Get both IDs with gh, GitHub's command-line tool:

gh api repos/my-org/hello-api --jq '.owner.id, .id'

Now create the role. IAM, Roles, Create role, Web identity, pick the provider and the audience. Fill in your org, repo and branch, name the role github-deploy-hello-api, and create it.

Then open Trust relationships and replace the whole policy with this one, so nothing from the wizard stays behind:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:my-org@123456/hello-api@789012:environment:production"
        }
      }
    }
  ]
}

Put your two IDs in place of 123456 and 789012. Is your repo older and not opted in? Then drop the IDs: repo:my-org/hello-api:environment:production.

A warning: the changelog only shows the branch form, repo:octocat@123456/my-repo@456789:ref:refs/heads/main. The environment form above is my inference from that pattern.

If the login fails, compare it with the real sub. Open CloudTrail, Event history and find the AssumeRoleWithWebIdentity event. Its userName is the sub GitHub sent (CloudTrail example).

The sub names no branch, so GitHub must guard the branch. Set two rules in the repo Settings:

  1. Environments, production, Deployment branches and tags: allow only main. Now only main can run jobs in production.
  2. Rules, Rulesets: add a branch ruleset on main that requires a pull request. Without it, anyone with write access can push to main and deploy without a review.

AWS's IAM guide for GitHub recommends protection rules like these too.

3. The permissions policy#

Give the role least privilege. Create this policy and attach it to the role:

// deploy permissions policy (key lines)
      "Action": "ecr:GetAuthorizationToken",
      "Resource": "*"
      // ...
      "Resource": "arn:aws:ecr:ap-southeast-1:123456789012:repository/hello-api"
      // ...
      "Action": "ecs:RegisterTaskDefinition",
      "Resource": "*"
      // ...
      "Action": ["ecs:UpdateService", "ecs:DescribeServices"],
      "Resource": "arn:aws:ecs:ap-southeast-1:123456789012:service/hello-api-cluster/hello-api-service"
      // ...
      "Action": "iam:PassRole",
      "Resource": [
        "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
        "arn:aws:iam::123456789012:role/hello-api-task-role"
      ],
      "Condition": {
        "StringEquals": { "iam:PassedToService": "ecs-tasks.amazonaws.com" }
      }
Show full code: deploy permissions policy
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EcrLogin",
      "Effect": "Allow",
      "Action": "ecr:GetAuthorizationToken",
      "Resource": "*"
    },
    {
      "Sid": "EcrPush",
      "Effect": "Allow",
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:BatchGetImage",
        "ecr:CompleteLayerUpload",
        "ecr:GetDownloadUrlForLayer",
        "ecr:InitiateLayerUpload",
        "ecr:PutImage",
        "ecr:UploadLayerPart"
      ],
      "Resource": "arn:aws:ecr:ap-southeast-1:123456789012:repository/hello-api"
    },
    {
      "Sid": "RegisterTaskDefinition",
      "Effect": "Allow",
      "Action": "ecs:RegisterTaskDefinition",
      "Resource": "*"
    },
    {
      "Sid": "DeployService",
      "Effect": "Allow",
      "Action": ["ecs:UpdateService", "ecs:DescribeServices"],
      "Resource": "arn:aws:ecs:ap-southeast-1:123456789012:service/hello-api-cluster/hello-api-service"
    },
    {
      "Sid": "PassRolesToEcsTasks",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": [
        "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
        "arn:aws:iam::123456789012:role/hello-api-task-role"
      ],
      "Condition": {
        "StringEquals": { "iam:PassedToService": "ecs-tasks.amazonaws.com" }
      }
    }
  ]
}

The ECR and ECS actions come from the READMEs of amazon-ecr-login and amazon-ecs-deploy-task-definition. GetAuthorizationToken and RegisterTaskDefinition can't be limited to one resource, so they use *.

Why iam:PassRole? A task definition names roles. Registering it hands those roles to ECS, which is called "passing" a role. Without this check, anyone who can register a task definition could pass a powerful role and run code with it.

  • List both roles. hello-api has no task role yet, so the second ARN is for later. Without it, the deploy fails on the day your app gets one.
  • iam:PassedToService lets the roles go to ECS tasks only, not to EC2 or Lambda (IAM condition keys).
quick-check

Your deploy job has environment: production. The trust policy sub is repo:my-org/hello-api:ref:refs/heads/main. What happens?

The deploy workflow#

First, put the task definition in the repo, so it is reviewed like code:

mkdir -p .aws
aws ecs describe-task-definition --task-definition hello-api \
  --query taskDefinition > .aws/task-definition.json

The file has fields that ECS adds, like revision. The deploy action drops those for you before it registers.

Words you need:

  • $GITHUB_OUTPUT: a file GitHub gives each step. A name=value line written there becomes an output, read later as steps.build.outputs.image.
  • Pinned action: an action named by a full commit SHA, with the version in a comment.

Now save this as .github/workflows/deploy.yml:

# deploy.yml (key lines)
concurrency:
  group: deploy-production
  cancel-in-progress: false
# ...
    environment: production
    permissions:
      contents: read
      id-token: write
    steps:
      # ...
      - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-deploy-hello-api
          # ...
          IMAGE_TAG: ${{ github.sha }}
        run: |
          docker build -t "$REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" .
          docker push "$REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG"
          echo "image=$REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> "$GITHUB_OUTPUT"
      # ...
          wait-for-service-stability: true
          wait-for-minutes: 15
          wait-max-delay-seconds: 15
Show full code: deploy.yml
name: deploy

on:
  push:
    branches: [main]

concurrency:
  group: deploy-production
  cancel-in-progress: false

env:
  AWS_REGION: ap-southeast-1
  ECR_REPOSITORY: hello-api
  ECS_CLUSTER: hello-api-cluster
  ECS_SERVICE: hello-api-service
  CONTAINER_NAME: hello-api

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false

      - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-deploy-hello-api
          aws-region: ${{ env.AWS_REGION }}

      - id: ecr
        uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2.1.7

      # add the Trivy scan gate from Docker from Zero ("Scan before you push") before the push
      - id: build
        env:
          REGISTRY: ${{ steps.ecr.outputs.registry }}
          IMAGE_TAG: ${{ github.sha }}
        run: |
          docker build -t "$REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" .
          docker push "$REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG"
          echo "image=$REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> "$GITHUB_OUTPUT"

      - id: render
        uses: aws-actions/amazon-ecs-render-task-definition@8d79160660ad39c402a16e5fc7cd2a32e8f7d6b7 # v1.9.1
        with:
          task-definition: .aws/task-definition.json
          container-name: ${{ env.CONTAINER_NAME }}
          image: ${{ steps.build.outputs.image }}

      - uses: aws-actions/amazon-ecs-deploy-task-definition@a00d4d57ac0de1a99b39fe469f3d898d38717c2b # v2.6.4
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          cluster: ${{ env.ECS_CLUSTER }}
          service: ${{ env.ECS_SERVICE }}
          wait-for-service-stability: true
          wait-for-minutes: 15
          wait-max-delay-seconds: 15

The workflow uses three AWS actions: configure-aws-credentials logs in, render-task-definition puts the new image into your JSON file, and deploy-task-definition registers it and updates the service.

Follow one push to main:

push-to-deploy
  1. You push to main, and the deploy job starts in the production environment.
  2. configure-aws-credentials swaps the GitHub ID token for 1-hour AWS keys.
  3. Docker builds the image and pushes it to ECR, tagged with the full commit SHA.
  4. render-task-definition copies the JSON file and swaps in the new image.
  5. deploy-task-definition registers a new revision and points the service at it.
  6. The job waits until the service is stable on the new revision, then turns green.
step 1 / 6
Steps 4 and 5 are the same register and update you clicked by hand in the first deploy.

What each part is for:

  • environment: production must match the sub in the trust policy. Change one, change the other.
  • id-token: write lets the job ask GitHub for an ID token. Without it, the AWS login step fails.
  • concurrency runs one deploy at a time. With cancel-in-progress: false, a new push waits instead of stopping a running deploy. GitHub keeps only one waiting run, so a third push replaces the waiting one.
  • persist-credentials: false stops checkout from saving the GitHub token in .git/config. Its default is true. Also put .git in your .dockerignore, so git history and config stay out of the image.
  • $GITHUB_OUTPUT turns the image=... line into the steps.build.outputs.image output.
  • ${{ github.sha }} is the full 40-character commit SHA. It can't clash with the short tags you pushed by hand (Push to ECR chapter).
  • wait-for-service-stability: true keeps the job open until the new tasks are healthy. Without it, the job turns green while broken tasks are still starting.
  • wait-max-delay-seconds: 15 checks every 15 seconds at most. The README warns the default gap between checks can grow to 10 minutes.

Every action is pinned to a commit SHA, with the version in a comment. A tag like @v4 can be moved to other code. Docker from Zero explains why. These were the latest releases on 24 October 2026.

Check each SHA yourself before you copy it. A commit from a fork can show up under the real repo's name. So confirm the SHA belongs to the release tag:

gh api repos/actions/checkout/commits/v7.0.1 --jq .sha

It must print the same SHA as the workflow. Do the same for the other four actions.

quick-check

You forget id-token: write in the job permissions. Which step fails?

Rolling deploys and rollback#

Words you need:

  • Rolling deploy: new tasks start and old tasks stop a few at a time, so users always have a healthy task.
  • Draining: the ALB stops sending new requests to a task, and waits for open ones to finish.
  • Deregistration delay: the longest the target group waits while a task drains.
  • SIGTERM: the signal that asks a process to stop.
  • Circuit breaker: the ECS setting that stops a failing deploy and rolls it back.

A good deploy#

Your service has a desired count of 2. The deployment settings are at their defaults: min running tasks 100% and max running tasks 200% (deployment configuration docs). For 2 tasks, that means never fewer than 2 healthy, and at most 4 at once.

rolling-deploy-good
  1. The workflow registers hello-api:3 and updates the service.
  2. ECS starts 2 new tasks, 4 in total, which max 200% allows.
  3. The new tasks join hello-api-tg and pass GET /health.
  4. Now the ALB sends requests to old and new tasks.
  5. ECS takes the 2 old tasks out of the target group, waits for them to drain, then stops them.
  6. The service is stable on hello-api:3, and the job turns green.
step 1 / 6
At no point were fewer than 2 healthy tasks serving users.

Ship Without Fear explains rolling deploys with Kubernetes. There, maxSurge and maxUnavailable do the job of ECS's maximumPercent and minimumHealthyPercent.

The drain step takes time. Draining waits for open connections, up to the deregistration delay. That is 300 seconds by default.

For a service whose requests finish in under a second, like hello-api, AWS's draining guide suggests as low as 5 seconds.

Then ECS sends SIGTERM. The handler from Docker from Zero lets Node finish its requests and exit.

A bad deploy and the circuit breaker#

Now you push a commit that crashes on boot. Who stops it? The circuit breaker, which you left on when you created the service.

rolling-deploy-bad
  1. The workflow registers hello-api:4 and updates the service.
  2. ECS starts new tasks, and each one crashes before it is healthy.
  3. The 2 hello-api:3 tasks keep serving, because min running tasks is 100%.
  4. ECS counts the failures, and the threshold for 2 tasks is 3.
  5. The circuit breaker marks the deployment FAILED and rolls back to hello-api:3.
  6. The deploy action sees the rollback and fails the job, so you get a red X.
step 1 / 6
Users kept getting the old version the whole time.

Where does 3 come from? The circuit breaker docs set the threshold at 50% of the desired count, with a minimum of 3 and a maximum of 200. Half of 2 is 1, so the minimum wins.

Rollback goes to the last deployment in the COMPLETED state. The deploy action checks for that rollback after its wait (its source). That is where the red X comes from.

Rolling back by hand#

The circuit breaker catches tasks that can't start or can't pass health checks. It can't catch a bug that returns wrong data with status 200. For that, you roll back yourself.

Don't re-run the old workflow run. It would push the old SHA tag again, and the immutable repository refuses it. Use one of these:

  • git revert the bad commit and push. A new commit, a new SHA, a normal deploy. main keeps matching what runs. This is my default.
  • Point the service at the old revision when you need it right now: aws ecs update-service --cluster hello-api-cluster --service hello-api-service --task-definition hello-api:3. Then revert in git, so the next push doesn't bring the bug back.

ECS also has built-in blue/green, linear and canary strategies. Ship Without Fear explains when those beat a rolling deploy.

quick-check

The new version returns HTTP 200 on /health, but every order total is wrong. Does the circuit breaker roll back?

ECS can also fail a deploy on CloudWatch alarms, for example a spike in 5xx errors. That catches some bugs a health check can't see.

Recap#

Step of the storyWhat you can now do
How ECS fits togethername the task definition, task, service and cluster, and pick Fargate or EC2
The load balancerexplain the listener, target group and health check, and why /health stays light
The two rolesuse the execution role for image pulls and logs, the task role for your app's AWS calls
First deploypush a SHA tag to an immutable ECR repo, register a task definition, run 2 tasks behind an ALB
Debug and clean upread a stopped reason or reason code, and delete everything in the right order
OIDCgive a workflow 1-hour AWS keys with nothing stored in GitHub
Deploy role and workflowmatch the sub to an environment, use least privilege with iam:PassRole, pin and check every action
Rollbackexplain a rolling deploy, the circuit breaker, and how to roll back by hand

Try it yourself:

  • Deploy hello-api, then point the health check at /healthz and watch the targets go unhealthy.
  • Push a commit that crashes on boot, and watch the circuit breaker roll it back.
  • Find your real sub in CloudTrail and compare it with your trust policy.

Read next: Docker from Zero shows how to make the hello-api image small and fast to build.