Sub topic 5
Writing a Fargate task definition
A task definition is the blueprint ECS uses to start containers. It names the images, sets the CPU and memory, wires in IAM roles, and chooses the network mode and the log destination. This chapter walks through every field of a working Fargate task definition and covers the errors that most often block a first deployment.
This chapter assumes you can build a Docker image and read JSON. It also assumes you know what an IAM role, a VPC subnet, and a security group are. The image has already been pushed to Amazon ECR, as covered earlier in this tutorial.
What a task definition is
A task definition is a versioned, immutable document. Each time you register a definition with the same family, ECS creates a new numbered revision, such as web-app:1, then web-app:2. You never edit a revision. You register a new one and point your service at it.
A task definition has two levels:
- Task level: settings shared by the whole task, such as
cpu,memory,networkMode, and the two IAM roles. - Container level: settings for each container in
containerDefinitions, such as the image, ports, environment, health check, and logging.
A task can hold more than one container. All containers in a task run on the same Fargate micro-VM and share its network namespace, so they can reach each other on localhost.
A complete example
The following definition runs one web container on Fargate. Save it as taskdef.json.
{
"family": "web-app",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::123456789012:role/webAppTaskRole",
"runtimePlatform": {
"cpuArchitecture": "X86_64",
"operatingSystemFamily": "LINUX"
},
"containerDefinitions": [
{
"name": "web",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/web-app:1.0.0",
"essential": true,
"portMappings": [
{ "containerPort": 8080, "protocol": "tcp" }
],
"environment": [
{ "name": "APP_ENV", "value": "production" }
],
"secrets": [
{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/db-AbCdEf"
}
],
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 30
},
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/web-app",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "web"
}
}
}
]
}Register it with:
aws ecs register-task-definition --cli-input-json file://taskdef.jsonTask-level fields
family and revisions
family groups revisions together. A service can reference web-app (the latest active revision) or a pinned web-app:3. Pinning makes rollbacks predictable, so prefer it in automated pipelines.
requiresCompatibilities and networkMode
requiresCompatibilities: ["FARGATE"] makes ECS validate the definition against Fargate rules. Fargate supports only awsvpc for networkMode. In this mode every task gets its own elastic network interface (ENI) and its own private IP address, and security groups apply to the task directly. Networking details come in a later chapter.
cpu and memory
Fargate needs cpu and memory at the task level, written as strings. Only certain combinations are valid. The next chapter covers the full table. For now, 256 CPU units (0.25 vCPU) with 512 MiB of memory is the smallest common pairing.
Container-level cpu and memory are optional on Fargate. If you set them, the sum across containers must not exceed the task totals.
runtimePlatform
runtimePlatform selects the operating system and CPU architecture. The architecture must match the image you built. An arm64 image on an X86_64 task fails at start with an exec format error. To run on Graviton, set "cpuArchitecture": "ARM64" and push an ARM-compatible image.
The two IAM roles
The definition names two roles that do different jobs:
| Field | Used by | Typical permissions |
|---|---|---|
| `executionRoleArn` | The ECS agent, before your code starts | Pull from ECR, write to CloudWatch Logs, read secrets named in `secrets` |
| `taskRoleArn` | Your application code, while it runs | Whatever your app calls, such as S3 or DynamoDB |
Both roles use the same trust policy, which lets the ECS tasks service assume them:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ecs-tasks.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}For the execution role, also attach the AWS managed policy AmazonECSTaskExecutionRolePolicy. If you use secrets, add a statement allowing secretsmanager:GetSecretValue on that secret. The task role is optional. Omit it if your code calls no AWS APIs.
Container-level fields
name, image, and essential
name identifies the container within the task. Use a full ECR URI with an explicit tag for image. A mutable tag such as latest makes deployments hard to reproduce, so prefer a version tag or a digest.
essential: true means that if this container stops, ECS stops the whole task. At least one container must be essential. Set essential: false for helper containers, such as a log shipper, whose failure should not kill the task.
portMappings
containerPort is the port your process listens on. With awsvpc, the container port is the port on the task's ENI, so no host port mapping is needed. The load balancer target group registers the task's IP at this port.
environment and secrets
environment holds plain values. They are visible in the console and in describe-task-definition, so never put credentials there.
secrets references a Secrets Manager secret or a Systems Manager Parameter Store parameter through valueFrom. ECS resolves the value at task start using the execution role and injects it as an environment variable. Two consequences follow:
- A missing permission on the execution role fails the task before your container starts.
- Rotating the secret does not update running tasks. Start new tasks to pick up the new value.
healthCheck
The container health check runs a command inside the container. In the example, curl must exist in the image, or the check always fails. The fields work as follows:
interval: seconds between checks.timeout: seconds before a single check counts as failed.retries: consecutive failures before the container is marked unhealthy.startPeriod: seconds during which failures are ignored while the app boots.
If an essential container becomes unhealthy, ECS stops the task. Load balancer health checks are separate and are covered in a later chapter.
logConfiguration
The awslogs driver sends the container's stdout and stderr to CloudWatch Logs. Streams are named prefix/container-name/task-id. The log group in awslogs-group must already exist unless you add "awslogs-create-group": "true" to the options and grant the execution role logs:CreateLogGroup.
How the pieces fit
Common errors
| Symptom | Likely cause |
|---|---|
| `Invalid CPU or memory value specified` | The `cpu` and `memory` pair is not a valid Fargate combination |
| `CannotPullContainerError` | Execution role lacks ECR permissions, or the task has no route to ECR (no NAT gateway, public IP, or VPC endpoints) |
| `ResourceInitializationError` when fetching a secret | Execution role cannot read the secret, or the task cannot reach Secrets Manager |
| `exec format error` in logs | Image architecture differs from `runtimePlatform` |
| Task stops right after start | Essential container exited, or the health check failed after `startPeriod` |
| `AccessDenied` from your app code | The permission belongs on the task role, not the execution role |
Registering and inspecting revisions
After registering, list and inspect revisions to confirm what ECS stored:
aws ecs list-task-definitions --family-prefix web-app
aws ecs describe-task-definition --task-definition web-app:1To retire a revision that must not be used again, run aws ecs deregister-task-definition --task-definition web-app:1. Running tasks keep going, but no new task can start from that revision.
Exercise
A container starts successfully, but every call it makes to an S3 bucket returns AccessDenied. The execution role has AmazonECSTaskExecutionRolePolicy attached and the image pulled without trouble. Which role should you change, and why?
Show answer
Change the task role (taskRoleArn). The execution role is used by the ECS agent for pulling images, writing logs, and fetching secrets. Calls your application code makes to S3 use the task role's credentials, so the S3 permissions must be added there.
Exercise
You build your image on an Apple Silicon laptop without specifying a platform and register a task definition with "cpuArchitecture": "X86_64". The task stops immediately and the logs show "exec format error". What is wrong, and what are two ways to fix it?
Show answer
The image is built for arm64 but the task runs on x86_64. Either rebuild the image for linux/amd64 (for example with docker buildx build --platform linux/amd64), or change runtimePlatform to "cpuArchitecture": "ARM64" and keep the arm64 image.