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
mainwith 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 Fargate | ECS on EC2 | Cloud Run | |
|---|---|---|---|
| You manage | task definitions, services, a load balancer | all of that, plus the EC2 machines | your container and its settings |
| No traffic | tasks keep running and billing | machines keep running and billing | scales to zero by default |
| Good for | teams on AWS who don't want servers | GPUs, special host settings | apps 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.
Your API needs a GPU. Which ECS option fits?
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.
256CPU 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:
256is the CPU (a quarter core), and512is 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.
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:
| Setting | Default | For hello-api |
|---|---|---|
| Path | / | /health |
| Interval | every 30 seconds | keep |
| Timeout | 5 seconds | keep |
| Unhealthy after | 2 failed checks in a row | keep |
| Healthy again after | 5 passed checks in a row | keep |
| Success code | 200 | keep |
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:
- The ALB calls GET /health on task 1 and task 2 every 30 seconds.
- Task 2 hangs, and its check gets no answer within 5 seconds.
- A second failed check in a row: the ALB marks task 2 unhealthy.
- The ALB sends new requests only to task 1.
- The ECS service sees the failed health check and stops task 2.
- The service starts a new task in place of task 2. It passes its first check, and it gets traffic.
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?
The target group checks /healthz, but hello-api only has /health. What happens?
The two IAM roles#
Think about two jobs:
- Before your code starts, something must download the image from ECR and set up the log stream in CloudWatch (AWS's log service).
- 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 role | Task role | |
|---|---|---|
| Used by | ECS and the Fargate agent | your app code |
| When | around your container: pull the image, send logs, read secrets | while your app runs and calls AWS |
| Usual permissions | the AWS managed policy AmazonECSTaskExecutionRolePolicy | only what your app needs, like reading one S3 bucket |
| Does hello-api need it? | yes | no, 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.
Which role pulls the image from ECR?
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 attachAdministratorAccessto itself. - At work, ask your admin to create the roles. Also ask for
iam:PassRoleon those roles.PowerUserAccessblocks it too, so registering a task definition that namesexecutionRoleArnwould 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:
- Open ECR, choose Create repository.
- Name:
hello-api. Image tag mutability: Immutable. Create. - 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 buildsarm64images by default. The task definition (next chapter) asks forX86_64. A mismatch makes the container fail on start withexec 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.
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:
- Open CloudWatch, then Log groups, Create log group.
- 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"
}
}
}
]
}
| Field | Value | Why |
|---|---|---|
family | hello-api | the name; this first one becomes hello-api:1 |
networkMode | awsvpc | required on Fargate; each task gets its own network interface and private IP |
cpu, memory | 256, 512 | 0.25 vCPU and 512 MiB, the smallest Fargate size |
runtimePlatform | Linux, X86_64 | must match the --platform you built with |
executionRoleArn | ecsTaskExecutionRole | lets the agent pull the image and write logs |
image | ...:3f9c2a1 | the exact tag you pushed |
portMappings | 3000 | the port hello-api listens on |
essential | true | if this container stops, the whole task stops, so the service replaces it |
logConfiguration | awslogs | sends 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 needslogs: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'ssecretsfield:"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_URLenvironment variable. The execution role then needsssm:GetParameterson that one parameter (execution role docs). hello-api has no secrets, so it skips this.
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#
- EC2, Security groups, Create. Name
hello-api-alb-sg, default VPC. Inbound: HTTP, port 80, source0.0.0.0/0. - Create a second one. Name
hello-api-task-sg. Inbound: Custom TCP, port 3000, source: the security grouphello-api-alb-sg, not an IP range. - 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. - EC2, Load balancers, Create, Application Load Balancer. Name
hello-api-alb, internet-facing, default VPC, at least 2 subnets in different zones. Security group: onlyhello-api-alb-sg. Listener: HTTP 80, forward tohello-api-tg. - ECS, Clusters, Create cluster. Name
hello-api-cluster. Fargate is the default. - Open the cluster, Services, Create:
- Compute options: Launch type, FARGATE.
- Task definition
hello-api, latest revision. Service namehello-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 grouphello-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#
- You run curl http://hello-api-alb-123.ap-southeast-1.elb.amazonaws.com/health
- The ALB security group allows port 80 from anywhere, so it gets in.
- The listener on port 80 forwards it to the target group hello-api-tg.
- The target group picks a healthy task, for example 172.31.5.20 on port 3000.
- The task security group lets it in, because it comes from the ALB security group.
- Express (the web framework hello-api uses) answers {"status":"ok"}
- The task answers the ALB, and the ALB sends the answer back to you.
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, bothhealthy. - The logs:
aws logs tail /ecs/hello-api --followprintslistening on port 3000once 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 see | Likely cause | Fix |
|---|---|---|
Task stops with CannotPullContainerError | wrong image URI or tag, or Public IP off in a public subnet | copy the URI from ECR, turn Public IP on |
exec format error in the logs | an arm64 image on an X86_64 task | rebuild with --platform linux/amd64, push a new tag |
Target unhealthy, Target.ResponseCodeMismatch | the check path returns 404 | set the health check path to /health |
Target unhealthy, Target.Timeout | the task SG does not allow 3000 from the ALB SG, so the check gets no answer | fix the SG rule |
Target unhealthy, Target.FailedHealthChecks | nothing listens on port 3000: wrong port, or the app listens on 127.0.0.1 | listen on 0.0.0.0 and the port in portMappings (Docker from Zero) |
| Tasks start, stop, start again | the app crashes on boot, often a missing environment variable | read the logs for the first error |
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.
subclaim: the subject. It says which repo, and which branch or environment, the run comes from.audclaim: the audience. It says who the token is for. For AWS it issts.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:
- The job asks GitHub for an ID token.
- GitHub sends back a signed token with the sub and aud claims.
- The job calls AssumeRoleWithWebIdentity with the token and the role ARN.
- STS checks the signature and the trust policy.
- STS sends back temporary AWS keys, valid 1 hour.
- The job pushes the image and updates the service.
The same flow as a diagram:
The keys expire after 1 hour, the default in configure-aws-credentials. Nothing long-lived exists to steal.
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 job | Its sub claim |
|---|---|
push to main, no environment | repo:my-org/hello-api:ref:refs/heads/main |
uses environment: production | repo:my-org/hello-api:environment:production |
| runs on a pull request | repo: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:
- Environments, production, Deployment branches and tags: allow only
main. Now onlymaincan run jobs inproduction. - Rules, Rulesets: add a branch ruleset on
mainthat requires a pull request. Without it, anyone with write access can push tomainand 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:PassedToServicelets the roles go to ECS tasks only, not to EC2 or Lambda (IAM condition keys).
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. Aname=valueline written there becomes an output, read later assteps.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:
- You push to main, and the deploy job starts in the production environment.
- configure-aws-credentials swaps the GitHub ID token for 1-hour AWS keys.
- Docker builds the image and pushes it to ECR, tagged with the full commit SHA.
- render-task-definition copies the JSON file and swaps in the new image.
- deploy-task-definition registers a new revision and points the service at it.
- The job waits until the service is stable on the new revision, then turns green.
What each part is for:
environment: productionmust match thesubin the trust policy. Change one, change the other.id-token: writelets the job ask GitHub for an ID token. Without it, the AWS login step fails.concurrencyruns one deploy at a time. Withcancel-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: falsestops checkout from saving the GitHub token in.git/config. Its default istrue. Also put.gitin your.dockerignore, so git history and config stay out of the image.$GITHUB_OUTPUTturns theimage=...line into thesteps.build.outputs.imageoutput.${{ 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: truekeeps 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: 15checks 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.
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.
- The workflow registers hello-api:3 and updates the service.
- ECS starts 2 new tasks, 4 in total, which max 200% allows.
- The new tasks join hello-api-tg and pass GET /health.
- Now the ALB sends requests to old and new tasks.
- ECS takes the 2 old tasks out of the target group, waits for them to drain, then stops them.
- The service is stable on hello-api:3, and the job turns green.
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.
- The workflow registers hello-api:4 and updates the service.
- ECS starts new tasks, and each one crashes before it is healthy.
- The 2 hello-api:3 tasks keep serving, because min running tasks is 100%.
- ECS counts the failures, and the threshold for 2 tasks is 3.
- The circuit breaker marks the deployment FAILED and rolls back to hello-api:3.
- The deploy action sees the rollback and fails the job, so you get a red X.
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 revertthe bad commit and push. A new commit, a new SHA, a normal deploy.mainkeeps 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.
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 story | What you can now do |
|---|---|
| How ECS fits together | name the task definition, task, service and cluster, and pick Fargate or EC2 |
| The load balancer | explain the listener, target group and health check, and why /health stays light |
| The two roles | use the execution role for image pulls and logs, the task role for your app's AWS calls |
| First deploy | push a SHA tag to an immutable ECR repo, register a task definition, run 2 tasks behind an ALB |
| Debug and clean up | read a stopped reason or reason code, and delete everything in the right order |
| OIDC | give a workflow 1-hour AWS keys with nothing stored in GitHub |
| Deploy role and workflow | match the sub to an environment, use least privilege with iam:PassRole, pin and check every action |
| Rollback | explain 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
/healthzand watch the targets go unhealthy. - Push a commit that crashes on boot, and watch the circuit breaker roll it back.
- Find your real
subin 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.