Ship a container image to ECS on Fargate
Push an image to ECR and run it as an ECS service on Fargate with the right task and execution roles, logs and deployment settings.
By Invicly Tech, , in AWS Cloud Engineering. About 12 minutes to read.
In short
Amazon ECS runs containers for you, and Fargate supplies the compute so there are no servers to patch. You push an image to Amazon ECR, describe how to run it in a task definition, and an ECS service keeps the desired number of tasks running, replacing failures and rolling out new versions. Two IAM roles matter: the execution role lets ECS pull the image and write logs, and the task role is what your code uses to call AWS.
Think of it like this: The image is a packed lunch, the task definition is the label saying how much space it needs, and the ECS service is the canteen manager who makes sure the right number of lunches is always out.
Explained simply
A container packs your app and everything it needs into one image, so it runs the same on your laptop and in the cloud. To run that image on AWS, you first store it in Amazon ECR, a private registry in your account.
Amazon ECS is the service that starts and watches containers. You tell it what to run with a task definition: the image, how much CPU and memory, which port, which roles and where logs go. One running copy is a task. A service keeps a set number of tasks alive and replaces any that stop.
Fargate is where the tasks run. You do not create or patch servers; you just ask for CPU and memory per task and pay for that while it runs. Each Fargate task gets its own network card in your subnet, with its own security group.
Two roles cause the most confusion. The execution role is for ECS itself: pulling the image and writing logs. The task role is for your code: reading S3, sending to SQS and so on. If the app gets AccessDenied, look at the task role first.
Press Play on a diagram to walk through it one step at a time.
- 1Build image
docker build, tag with a version
- 2Push to ECR
Private registry in your account
- 3Register task definition
Image, CPU, memory, roles, logs, port
- 4Create or update service
Desired count, subnets, security group
- 5Rolling deployment
New tasks pass health checks, old ones stop
- Used by the ECS agent and Fargate
- Pulls the image from ECR
- Writes logs to CloudWatch Logs
- Reads secrets injected as environment variables
- Used by your application code
- Calls S3, SQS, DynamoDB and so on
- Credentials come from the task metadata endpoint
- Keep it to the least privilege the app needs
- Image pull failed
- No route to ECR (NAT or endpoints missing)
- Execution role lacks ECR permissions
- Wrong tag or architecture
- Container exited
- App error: read the log stream
- Missing environment variable or secret
- Health check failed
- Wrong port or path in target group
- Security group blocks the ALB
- Resources
- Out of memory: exit code 137
- Invalid CPU and memory pair
In depth
Inside a task definition
A task definition is a versioned JSON document. Each registration creates a new revision, such as files-api:7, and a service points at one revision. Key fields: family, the task-level cpu and memory, networkMode (always awsvpc on Fargate), requiresCompatibilities FARGATE, runtimePlatform with the CPU architecture, executionRoleArn, taskRoleArn and a list of containerDefinitions.
Each container definition names the image, port mappings, environment variables, secrets pulled from Secrets Manager or Parameter Store, a health check command, and logConfiguration. Fargate accepts only certain CPU and memory pairs: 256 CPU units (a quarter vCPU) allows 512 MB, 1 GB or 2 GB, and larger CPU sizes allow larger memory ranges. Each task also gets 20 GiB of ephemeral storage by default, which you can raise.
- One revision per registration; services point at a revision
- Fargate requires awsvpc network mode
- CPU and memory must be a supported pair
- Secrets are injected at start by the execution role
Execution role, task role and where credentials come from
When a task starts, the ECS agent uses the execution role to authenticate to ECR, pull image layers, create the log stream and fetch any secrets in the container definition. Your code never sees these credentials.
Once running, the AWS SDK in your container finds credentials through the container credentials provider: ECS sets the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI variable, and the SDK calls that local endpoint to get temporary credentials for the task role. They rotate automatically. That is why you never put access keys in the image or environment.
Keep them apart. The execution role can use the managed policy AmazonECSTaskExecutionRolePolicy plus read access to specific secrets. The task role should name exact resources, such as s3:GetObject on the uploads bucket and sqs:ReceiveMessage on one queue.
- ECS agent to ECR and Logs: Execution role: pull image, create log stream1Execution role: pull image, create log stream
- ECS agent to App container: Start container with secrets injected2Start container with secrets injected
- App container to ECS agent: SDK asks credentials endpoint for task role3SDK asks credentials endpoint for task role
- App container to S3: Task role: GetObject uploads/42.csv4Task role: GetObject uploads/42.csv
- App container to ECR and Logs: stdout lines sent by awslogs driver5stdout lines sent by awslogs driver
Logs with the awslogs driver
Containers should write logs to standard output and standard error. The awslogs log driver ships those lines to CloudWatch Logs. In logConfiguration set awslogs-group, awslogs-region and awslogs-stream-prefix; each task then gets a stream named prefix/container-name/task-id, which makes it easy to find the logs for one failed task. Add awslogs-create-group true only if the execution role is allowed to create log groups.
Set a retention period on the log group. The default is to keep logs forever, and storage costs grow silently. For richer routing, such as sending logs to several destinations, use FireLens with Fluent Bit instead, but awslogs is enough for most services.
How a rolling deployment behaves
When you update a service with a new task definition revision, the default rolling update uses two numbers. minimumHealthyPercent is the floor of running healthy tasks during the deployment, and maximumPercent is the ceiling. With desired count 2, 100 and 200 mean ECS may start 2 new tasks, wait until they are healthy (container health check and load balancer health check if attached), then stop the 2 old ones. Lower the minimum to deploy with fewer spare resources but less capacity.
Turn on the deployment circuit breaker with rollback. If new tasks keep failing to reach a steady state, ECS marks the deployment failed and returns to the last completed revision. ECS also offers blue/green and other deployment strategies for more control, which the release module covers. Watch progress in the service's deployments and events list.
- Defaults for replica services: minimum 100, maximum 200
- Health = container health check plus target group check
- Circuit breaker with rollback stops a bad release
- Service events explain stuck deployments
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Push an image to ECR~40m
- 2Write a task definition~40m
- 3Separate task and execution roles~40m
- 4Send logs to CloudWatch~40m
- 5Watch a rolling deployment~40m
Key points
- Fargate tasks always use the awsvpc network mode, so each task gets its own network interface and security group.
- Pick a valid Fargate CPU and memory pair, for example 256 CPU units with 512 MB.
- Send container logs to CloudWatch Logs with the awslogs log driver.
- Tag images with a version or commit SHA, not only latest, so you can roll back.
- Turn on the deployment circuit breaker with rollback so a broken release stops itself.
Key terms
Tap a card to flip it. 0/6 known
Examples
ACCT=111122223333; REGION=eu-west-1
REPO=$ACCT.dkr.ecr.$REGION.amazonaws.com/files-api
aws ecr create-repository --repository-name files-api
aws ecr get-login-password --region $REGION \
| docker login --username AWS --password-stdin $ACCT.dkr.ecr.$REGION.amazonaws.com
docker build -t $REPO:1.0.0 .
docker push $REPO:1.0.0The account ID is a placeholder. Build for the CPU architecture your task definition declares (X86_64 or ARM64).
Lab: run the files API as a Fargate service
Prerequisites: the image pushed to ECR (see the explainer), the VPC with private subnets and NAT or endpoints, a log group /ecs/files-api with 7-day retention, and the two roles. Cost: Fargate bills per vCPU and GB per second while tasks run; one small task for an hour costs cents, but an ALB and NAT add hourly charges. Step 1: register the task definition below. Step 2: create a cluster and a service with desired count 1. Evidence: the task reaches RUNNING and log lines appear in CloudWatch. Cleanup: set desired count to 0, delete the service and cluster, deregister task definitions and delete the ECR repository with --force.
{
"family": "files-api", "networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"], "cpu": "256", "memory": "512",
"runtimePlatform": {"cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX"},
"executionRoleArn": "arn:aws:iam::111122223333:role/filesApiExecutionRole",
"taskRoleArn": "arn:aws:iam::111122223333:role/filesApiTaskRole",
"containerDefinitions": [{
"name": "api", "image": "111122223333.dkr.ecr.eu-west-1.amazonaws.com/files-api:1.0.0",
"portMappings": [{"containerPort": 8080}], "essential": true,
"logConfiguration": {"logDriver": "awslogs", "options": {
"awslogs-group": "/ecs/files-api", "awslogs-region": "eu-west-1",
"awslogs-stream-prefix": "api"}}
}]
}Ship version 1.1.0 and watch the rolling deployment
Step 1: build and push files-api:1.1.0. Step 2: register a new task definition revision with the new tag. Step 3: update the service to that revision with the circuit breaker on. Evidence: describe-services shows two deployments, PRIMARY with the new revision and ACTIVE with the old, until the old one drains away and rolloutState is COMPLETED. If you push a broken image on purpose, the circuit breaker marks it FAILED and the service returns to the previous revision. Rollback by hand is just another update-service pointing at the old revision.
aws ecs register-task-definition --cli-input-json file://taskdef-1.1.0.json
aws ecs update-service --cluster files --service files-api \
--task-definition files-api:2 \
--deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},minimumHealthyPercent=100,maximumPercent=200"
aws ecs describe-services --cluster files --services files-api \
--query "services[0].deployments[].[status,taskDefinition,rolloutState,runningCount]"Quick reference
- Login: aws ecr get-login-password | docker login --username AWS --password-stdin ACCOUNT.dkr.ecr.REGION.amazonaws.com
- Execution role = ECS pulls image, writes logs, reads secrets; task role = your code's AWS calls
- Fargate: awsvpc networking, valid CPU and memory pairs, 20 GiB ephemeral storage by default
- awslogs driver: set group, region and stream prefix; set log retention
- Rolling defaults: minimumHealthyPercent 100, maximumPercent 200
- Enable deploymentCircuitBreaker with rollback=true
- Exit code 137 usually means the container ran out of memory
- Tag images with a version or commit SHA for easy rollback
Common mistakes
- Giving S3 permissions to the execution role and wondering why the app still gets AccessDenied; the app uses the task role.
- Running tasks in private subnets with no NAT or ECR, S3 and Logs endpoints, so image pulls fail.
- Building an arm64 image on a laptop and running it on an X86_64 task, which fails with an exec format error.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write the minimum task role policy for an app that reads objects from the bucket example-uploads and sends messages to the queue files-jobs.
- Exercise 2medium
A task keeps restarting and the stopped reason says Essential container in task exited, exit code 137. Explain and fix.
- Exercise 3hard
Design the network and IAM pieces so a Fargate service in private subnets with no NAT can pull its image, write logs, read one secret and read from S3.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use Fargate or EC2 capacity for ECS?
- Start with Fargate: no servers to patch and simple per-task billing. Move to EC2 or ECS Managed Instances when you need GPUs, special instance types, or lower cost at steady high usage.
- Can I run a one-off job instead of a service?
- Yes. Use aws ecs run-task for a single task, or EventBridge Scheduler to run it on a schedule. A service is only needed for long-running workloads.
- How do I get a shell inside a running Fargate container?
- Turn on ECS Exec for the service, give the task role the required Systems Manager permissions, and use aws ecs execute-command. It uses the same channel as Session Manager.