This chapter covers ECS Fargate task definitions—the blueprint for running containers on AWS without managing servers. You will learn how to define container configurations, resource requirements, networking, and IAM roles in a task definition. This topic is critical for the DVA-C02 exam, appearing in roughly 10-15% of questions across development and deployment domains. Understanding task definitions deeply ensures you can design scalable, secure containerized applications for the AWS Certified Developer exam.
Jump to a section
Imagine you run a large corporate event and need to serve lunch to hundreds of attendees. You have two options: build a full kitchen (EC2) or order catered boxed lunches (Fargate). With Fargate, you call a catering company and specify exactly what you want in each box: a sandwich type (container image), a drink (environment variables), and utensils (storage mounts). The caterer handles all the logistics—they buy the ingredients, prepare the food, pack the boxes, and deliver them at the specified time. You never see the kitchen, you never worry about oven temperature or staffing. Each box is a task, and the caterer runs many boxes simultaneously across their facilities. If you need 50 boxes with turkey sandwiches and 50 with veggie, you submit a task definition that describes each box type. The caterer scales up to meet demand, and you only pay for the boxes delivered, not for the idle kitchen capacity. In AWS terms, the task definition is your order form; Fargate is the caterer that runs your containers without you managing servers.
What is an ECS Task Definition?
An ECS task definition is a JSON document that describes one or more containers that form your application. For Fargate launch type, it defines everything AWS needs to run your containers without provisioning EC2 instances: the container image, CPU and memory requirements, networking mode, environment variables, secrets, logging, storage volumes, and IAM roles. The task definition is versioned; each revision is immutable. You reference a task definition revision (e.g., my-app:3) when you run a task or create a service.
Why Task Definitions Exist
Task definitions decouple the application specification from the infrastructure. On Fargate, you never touch servers, so the task definition is the sole source of truth for how your containerized workload runs. It allows you to define multiple containers that share resources (e.g., a web server and a sidecar logging agent) and control their interactions via networking and volumes.
Key Components of a Task Definition
- family: The logical name for the task definition (e.g., my-web-app). All revisions share the same family.
- containerDefinitions: An array of container specifications. Each includes:
- name: Container name unique within the task.
- image: Docker image URI (e.g., 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:latest). For ECR images, the task execution role must have ecr:GetAuthorizationToken, ecr:BatchCheckLayerAvailability, ecr:GetDownloadUrlForLayer, ecr:BatchGetImage.
- cpu, memory: Resource reservations at the container level (optional; total task CPU/memory must match sum).
- portMappings: Maps container ports to host ports. For Fargate, hostPort must be the same as containerPort or 0 (ephemeral). Use protocol: tcp or udp.
- environment: Key-value pairs for env vars. Hard-coded; for secrets use secrets.
- secrets: References to AWS Secrets Manager or SSM Parameter Store. Requires secretsmanager:GetSecretValue or ssm:GetParameters permission.
- mountPoints: Binds volumes from the task-level volumes array.
- logConfiguration: Specifies log driver (e.g., awslogs). For CloudWatch Logs, requires logs:CreateLogStream, logs:PutLogEvents.
- readonlyRootFilesystem: Boolean; recommended for security.
- taskRoleArn: IAM role that the containers assume (e.g., to access DynamoDB). Different from execution role.
- executionRoleArn: IAM role that ECS assumes to pull images, send logs, and manage secrets. Required for Fargate.
- networkMode: For Fargate, must be awsvpc. Each task gets its own elastic network interface (ENI) with a private IP.
- cpu, memory: Task-level resource requirements. For Fargate, you must specify both. Valid combinations are predefined (see below).
- volumes: Defines named volumes (e.g., efsVolumeConfig for Amazon EFS, dockerVolumeConfiguration for Docker volumes).
- requiresCompatibilities: Must include FARGATE.
Fargate CPU and Memory Combinations
Fargate task definitions must use one of the following CPU/memory pairs. The exam tests these exact values: - 256 (.25 vCPU) – 512 MB, 1 GB, 2 GB - 512 (.5 vCPU) – 1 GB, 2 GB, 3 GB, 4 GB - 1024 (1 vCPU) – 2 GB, 3 GB, 4 GB, 5 GB, 6 GB, 7 GB, 8 GB - 2048 (2 vCPU) – 4 GB, 5 GB, 6 GB, 7 GB, 8 GB, 9 GB, 10 GB, 11 GB, 12 GB, 13 GB, 14 GB, 15 GB, 16 GB - 4096 (4 vCPU) – 8 GB, 9 GB, ..., 30 GB (in 1 GB increments) - 8192 (8 vCPU) – 16 GB, 17 GB, ..., 60 GB (in 1 GB increments) - 16384 (16 vCPU) – 32 GB, 33 GB, ..., 120 GB (in 1 GB increments) Memory must be between the minimum and maximum allowed for the CPU. The exam may ask: "Which memory value is valid for 1 vCPU?" Correct: 4 GB. Wrong: 1 GB (too low) or 10 GB (too high).
How Fargate Executes a Task Definition
You call RunTask or update a service with a new task definition revision.
ECS control plane validates the task definition (e.g., correct CPU/memory combo, required roles).
Fargate provisions an ENI in your VPC subnet. The ENI gets a private IP from the subnet's CIDR. If assignPublicIp is ENABLED, a public IP is also assigned via an Internet Gateway.
The execution role is used to pull the container image from ECR or Docker Hub, and to create the CloudWatch log stream.
The container runtime starts the container with the specified environment, secrets, and volumes.
The task role is injected into the container as AWS credentials (via the metadata endpoint).
Health checks (if defined) start after the container enters RUNNING state.
Networking with awsvpc
Each Fargate task gets its own ENI. This means:
Security groups apply at the task level (you attach security groups to the task, not the host).
Tasks can communicate with each other via private IPs if they are in the same security group or rules allow.
No port mapping conflicts—each task has its own IP.
You cannot use host or bridge network modes with Fargate.
Storage Options
Amazon EFS: Use efsVolumeConfiguration in the volumes array. The task must be in the same VPC as the EFS file system. Mount points are defined in container definitions. EFS is persistent and can be shared across tasks.
Bind mounts: Not supported on Fargate (they require host file system access).
Docker volumes: Supported via dockerVolumeConfiguration with scope = shared or task. For Fargate, scope must be task (ephemeral storage tied to task lifecycle).
Ephemeral storage: Each Fargate task gets 20 GB of ephemeral storage by default (can be increased up to 200 GB via ephemeralStorage in task definition).
IAM Roles
Task execution role (required): Grants ECS permissions to pull images, send logs, and access secrets. Example policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}Task role (optional): Grants the application inside the container permissions to call AWS APIs (e.g., DynamoDB, S3). This is what your code uses.
Logging
Use logConfiguration with awslogs driver. Required parameters:
- awslogs-group: CloudWatch Logs group name.
- awslogs-region: Region (must match task's region).
- awslogs-stream-prefix: Prefix for log stream name.
Configuration Commands
Register a new task definition revision:
aws ecs register-task-definition --cli-input-json file://task-def.jsonList task definitions:
aws ecs list-task-definitions --family-prefix my-appDescribe a task definition:
aws ecs describe-task-definition --task-definition my-app:3Deregister a task definition revision (not reversible):
aws ecs deregister-task-definition --task-definition my-app:3Interaction with Services
ECS Service: Uses a task definition to maintain desired count of running tasks.
Elastic Load Balancer: A service can register tasks with an ALB/NLB using the task's ENI IP and container port.
Auto Scaling: Target tracking scaling policies use CloudWatch metrics (CPU, memory, ALB request count) to adjust desired count.
CloudWatch Events / EventBridge: Can trigger RunTask based on events (e.g., S3 bucket notification).
Versioning and Immutability
Task definitions are immutable. You cannot modify a revision; you must register a new revision. The family remains the same, but the revision number increments. Services can be updated to use a new revision with update-service.
Environmental Variables and Secrets
Environment variables are passed as plain text in the task definition. For sensitive data, use secrets referencing AWS Secrets Manager or Parameter Store.
Secrets are injected at container start. The execution role must have secretsmanager:GetSecretValue (or ssm:GetParameters).
Health Checks
You can define a health check command in the container definition (similar to Docker HEALTHCHECK). ECS does not use container health checks for service scheduling; it uses ELB health checks if behind a load balancer. Container health checks appear in the ECS console but do not replace ELB checks.
Task Lifecycle
PENDING: Task is being accepted and resources allocated.
ACTIVATING: Container is being started.
RUNNING: Container is healthy and running.
DEACTIVATING: Service is stopping the task (e.g., scale-in).
STOPPING: Container is being stopped.
STOPPED: Task exited. Reason codes include EssentialContainerExited, ResourceInitializationError, Timeout.
Common Pitfalls
Forgetting to set requiresCompatibilities to FARGATE. Without it, ECS assumes EC2 launch type.
Using incorrect CPU/memory combination. The task will fail to run.
Not specifying executionRoleArn. Fargate requires it.
Using host network mode. Only awsvpc is allowed.
Mounting an EFS volume without proper security group rules (NFS port 2049).
Using a task role that doesn't have necessary permissions for your application.
Exam Relevance
DVA-C02 tests your ability to write and interpret task definitions, choose correct CPU/memory combos, configure IAM roles, and set up networking. Scenario questions often ask: "Which task definition change allows the container to access DynamoDB?" Answer: Add a task role with appropriate permissions. Or: "A Fargate task fails to start with 'ResourceInitializationError'. What is the cause?" Likely: Invalid CPU/memory combination, missing execution role, or wrong network mode.
Advanced: Sidecar Pattern
You can define multiple containers in one task definition. They share the same lifecycle and network namespace (can communicate via localhost). Example: main app container + a sidecar that sends logs to a remote aggregator. All containers must be in the same task definition and share the same networkMode.
Summary
Task definitions are the blueprint for your containers on ECS Fargate. They specify everything from image to IAM roles to storage. Mastering their structure, valid CPU/memory combos, and networking is essential for the DVA-C02 exam and real-world deployments.
Define Container Blueprint
Start by creating the task definition JSON. Choose a family name (e.g., `my-api`). Under `containerDefinitions`, specify the image URI from Amazon ECR or Docker Hub. Set essential container parameters: `name`, `image`, `memory` and `cpu` at container level (optional, but if set they must sum to task-level values). Define `portMappings` for your application port. For a web app, map container port 80 to host port 80 (Fargate requires same port). Add environment variables for configuration (e.g., `DATABASE_URL`). For secrets, use `secrets` array referencing ARNs in Secrets Manager.
Configure Task Resources
Set task-level `cpu` and `memory` using valid Fargate combinations. For example, for a 1 vCPU task, set `cpu: 1024` and `memory: 2048` (2 GB). Ensure the sum of container-level resources (if specified) does not exceed these values. If container-level resources are omitted, the task resources are divided equally among containers. Set `networkMode` to `awsvpc`. Add `requiresCompatibilities: ['FARGATE']`. Optionally set `ephemeralStorage` if you need more than the default 20 GB (max 200 GB).
Attach IAM Roles
Create an execution role with trust policy for `ecs-tasks.amazonaws.com`. Attach managed policy `AmazonECSTaskExecutionRolePolicy` or custom policy with permissions for ECR, CloudWatch Logs, and secrets. Set `executionRoleArn` in the task definition. For application permissions, create a task role with trust policy for `ecs-tasks.amazonaws.com`. Attach policies for your app's AWS service access (e.g., DynamoDB read). Set `taskRoleArn`. The task role is assumed by the container's AWS SDK calls.
Define Networking and Storage
In the task definition, specify `networkConfiguration` when running the task (not in the definition itself). For a service, you set network config in the service definition. This includes `subnets`, `securityGroups`, and `assignPublicIp`. For persistent storage, add a `volumes` entry with `efsVolumeConfiguration`. Provide `fileSystemId`, `rootDirectory`, and optionally `transitEncryption` (recommended `ENABLED`). In the container definition, add a `mountPoints` entry referencing the volume name and container path (e.g., `/data`). Ensure security groups allow NFS (port 2049) from the task's ENI to the EFS mount target.
Register and Deploy
Register the task definition using AWS CLI: `aws ecs register-task-definition --cli-input-json file://task-def.json`. The output includes the revision number (e.g., `my-api:1`). Create an ECS cluster (or use default). Create a service with `aws ecs create-service` specifying the task definition, desired count, network configuration, and optionally a load balancer. Alternatively, use `RunTask` for one-off tasks. Monitor task status with `aws ecs describe-tasks`. Check CloudWatch Logs for container output. If tasks fail, examine the `stoppedReason` field for clues.
Enterprise Scenario 1: Microservices API with Sidecar
A financial services company runs a Node.js API on Fargate. They need centralized logging and metrics. They define a task definition with two containers: the main API and a sidecar running the Datadog agent. The sidecar shares the same network namespace, so the API sends logs to localhost:8125. The task definition includes an EFS volume for storing transaction logs persistently. The execution role pulls images from ECR, and the task role grants access to DynamoDB and SQS. They use a CPU of 512 and memory of 2 GB. The service is fronted by an ALB with health checks on /health. During peak hours, auto scaling adds tasks based on CPU utilization. A common misconfiguration is forgetting to set readonlyRootFilesystem: true for security, which the exam might ask about.
Enterprise Scenario 2: Batch Processing Job
A media company processes video files uploaded to S3. They use EventBridge to trigger a Fargate task via RunTask. The task definition specifies a container that runs FFmpeg. The task role allows reading from an S3 bucket and writing to another. The ephemeral storage is increased to 100 GB because video files are large. The task definition sets cpu: 4096 and memory: 8192 for fast processing. The execution role has permissions for ECR and CloudWatch Logs. They use awslogs to stream logs. A key challenge is ensuring the task definition's CPU/memory combo is valid; using 4096 CPU with 6 GB memory would fail because the minimum for 4 vCPU is 8 GB. The exam loves this trap.
Enterprise Scenario 3: Legacy Migration
A retail company migrates a monolithic .NET application from EC2 to Fargate. The app requires Windows containers, but Fargate only supports Linux containers. They must first containerize the app using Linux-compatible .NET Core. The task definition uses port mapping for HTTP (80) and HTTPS (443). They mount an EFS volume for shared session state. The task role grants access to an RDS MySQL database. They set environment variables for connection strings. The execution role includes permissions for ECR and CloudWatch. A common mistake is using bridge network mode, which is not allowed on Fargate. The exam tests that Fargate only supports awsvpc.
Performance and Scale Considerations
Fargate tasks can scale to thousands per account. Each task gets its own ENI, so plan for ENI limits per subnet. Use multiple subnets across AZs for high availability. EFS can handle many concurrent tasks, but monitor burst credits. For high I/O, consider provisioned throughput. Always test CPU/memory combinations; over-provisioning wastes cost. Use CloudWatch Container Insights for monitoring.
What Goes Wrong
Task fails to start: ResourceInitializationError often due to invalid CPU/memory combo, missing execution role, or incorrect network mode.
Container exits immediately: Check stoppedReason; often missing environment variables or secrets.
Cannot pull image: Execution role missing ECR permissions; or image URI wrong.
Cannot connect to database: Security group not allowing outbound traffic; or task role missing permissions.
EFS mount fails: Security group missing NFS inbound rule; or EFS file system in different VPC.
DVA-C02 Objective Coverage
This topic falls under Domain 1: Development with AWS Services, Objective 1.1: Write code that uses AWS services to build scalable, resilient, and secure applications. Exam questions on task definitions test your ability to configure containerized applications correctly. Specific sub-objectives include: selecting appropriate launch types, configuring IAM roles for tasks, setting networking and storage, and troubleshooting deployment failures.
Common Wrong Answers and Why
"Set networkMode to bridge" – Candidates confuse Fargate with EC2 launch type. Fargate only supports awsvpc. The exam will present bridge as a distractor.
"Use host port 0 for dynamic mapping" – While allowed, the exam expects you to know that for Fargate, hostPort must equal containerPort or be 0. But many candidates think you can use any port; the key is that Fargate doesn't support port mapping to different host ports.
"Task execution role is used by the application" – Wrong. The execution role is for ECS to pull images and send logs. The task role is for the application. The exam will ask which role to modify for DynamoDB access; answer: task role.
"Memory can be any value between 512 MB and 120 GB" – No, it must match the valid combinations for the chosen CPU. The exam gives a CPU value and asks for a valid memory; the wrong answer is often a value outside the allowed range.
"You can modify a task definition revision" – Task definitions are immutable. You must register a new revision. The exam tests this with a scenario where you need to change an environment variable; correct action is to register a new revision and update the service.
Specific Numbers and Terms on the Exam
Valid CPU: 256, 512, 1024, 2048, 4096, 8192, 16384 (in CPU units, where 1024 = 1 vCPU).
Valid memory ranges per CPU (memorize the table above).
Default ephemeral storage: 20 GB; max: 200 GB.
Network mode: awsvpc only.
Required IAM roles: executionRoleArn and optional taskRoleArn.
Log driver: awslogs for CloudWatch.
Secrets: secrets array referencing Secrets Manager or SSM.
Volume types: efsVolumeConfiguration or dockerVolumeConfiguration.
Edge Cases and Exceptions
Windows containers: Not supported on Fargate (only Linux). Exam may ask which launch type supports Windows; answer: EC2.
GPU support: Fargate does not support GPUs; use EC2.
Bind mounts: Not supported on Fargate. Use EFS or Docker volumes.
Task definition size limit: 64 KB (JSON). For large definitions, consider using SSM for environment variables.
Secrets: Maximum 60 secrets per container definition.
How to Eliminate Wrong Answers
Identify the launch type: if Fargate, eliminate any answer with host or bridge network mode, or with instanceRole.
Check CPU/memory: if the combination is not in the valid table, that answer is wrong.
Determine which role: if the question asks about pulling images or sending logs, it's execution role. If it's about accessing AWS services from the app, it's task role.
If the question involves modifying a task definition, the answer must involve registering a new revision; never in-place modification.
For storage, if the scenario requires persistent storage across tasks, EFS is the answer; ephemeral storage is lost when the task stops.
Task definitions are the blueprint for running containers; they are immutable and versioned.
Fargate requires `networkMode: awsvpc` and `requiresCompatibilities: ['FARGATE']`.
Valid CPU/memory combos are predefined: memorize the table for the exam.
The execution role is for ECS to pull images and send logs; the task role is for the application.
Persistent storage on Fargate is achieved via Amazon EFS or Docker volumes (not bind mounts).
Ephemeral storage defaults to 20 GB, max 200 GB.
Secrets must be referenced via `secrets` array using Secrets Manager or SSM Parameter Store.
You cannot modify a task definition revision; register a new revision to make changes.
Fargate does not support Windows containers or GPU workloads.
Common task failure reasons: invalid CPU/memory, missing execution role, incorrect network mode.
These come up on the exam all the time. Here's how to tell them apart.
Fargate Launch Type
No EC2 instances to manage; AWS handles infrastructure.
Network mode must be `awsvpc`.
CPU and memory must use predefined valid combinations.
Only supports Linux containers; no Windows or GPU.
Billed per second for resources consumed by tasks.
EC2 Launch Type
You manage EC2 instances in the cluster.
Supports `bridge`, `host`, `awsvpc`, and `none` network modes.
CPU and memory can be any values up to instance limits.
Supports Windows containers and GPU instances.
Billed for EC2 instances regardless of task usage.
Mistake
Fargate tasks can use any network mode like EC2 launch type.
Correct
Fargate only supports the `awsvpc` network mode. `bridge`, `host`, and `none` are not allowed. Each task gets its own ENI with a private IP.
Mistake
The task execution role is the IAM role that the application uses to call AWS APIs.
Correct
The execution role is used by ECS to pull container images, send logs to CloudWatch, and retrieve secrets. The application uses the task role (`taskRoleArn`) to call AWS services.
Mistake
You can specify any memory value for a given CPU on Fargate.
Correct
Memory must be one of the predefined valid combinations. For example, with CPU 1024 (1 vCPU), valid memory values are 2, 3, 4, 5, 6, 7, or 8 GB. Values like 1 GB or 10 GB are invalid.
Mistake
You can modify an existing task definition revision to update container settings.
Correct
Task definitions are immutable. To make changes, you must register a new revision (e.g., `my-app:2`). The old revision remains unchanged.
Mistake
Fargate supports bind mounts for sharing files between containers.
Correct
Bind mounts are not supported on Fargate because they require access to the host file system. Use EFS volumes or Docker volumes with `scope: task` instead.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
The execution role (`executionRoleArn`) is assumed by the ECS agent to perform actions on your behalf: pulling container images from ECR, sending logs to CloudWatch, and retrieving secrets from Secrets Manager or SSM. The task role (`taskRoleArn`) is assumed by the containers themselves to call AWS APIs (e.g., S3, DynamoDB). For the exam, remember: execution role = infrastructure actions; task role = application actions.
For Fargate tasks, the `hostPort` must be either the same as the `containerPort` or set to `0` (which assigns an ephemeral port). You cannot map container port 80 to host port 8080. This is because each task gets its own ENI, so there is no port conflict. The exam may present a scenario where you need to set both ports to the same value.
Valid combinations are: CPU 256 (0.25 vCPU) with memory 512 MB, 1 GB, or 2 GB; CPU 512 (0.5 vCPU) with 1-4 GB in 1 GB increments; CPU 1024 (1 vCPU) with 2-8 GB in 1 GB increments; CPU 2048 (2 vCPU) with 4-16 GB in 1 GB increments; CPU 4096 (4 vCPU) with 8-30 GB in 1 GB increments; CPU 8192 (8 vCPU) with 16-60 GB; CPU 16384 (16 vCPU) with 32-120 GB. The exam expects you to know these ranges.
When running the task (via service or RunTask), set `assignPublicIp: ENABLED` in the network configuration. This assigns a public IP from the subnet's Internet Gateway. Also ensure the task's security group allows inbound traffic on the container port (e.g., 80) from 0.0.0.0/0. Alternatively, place the task behind an Application Load Balancer with public subnets.
Fargate supports: (1) Ephemeral storage – 20 GB default, up to 200 GB, lost when task stops; (2) Amazon EFS – persistent, shared across tasks, must be in same VPC; (3) Docker volumes – with `scope: task` (ephemeral) or `scope: shared` (requires external driver). Bind mounts are not supported. For the exam, know that EFS is the primary persistent option.
Common causes: invalid CPU/memory combination (e.g., CPU 1024 with memory 1024 MB – not allowed), missing execution role, incorrect network mode (not `awsvpc`), or the task definition not including `requiresCompatibilities: ['FARGATE']`. Check the `stoppedReason` in the task description for details. Also verify that the execution role has necessary permissions.
Yes. Define multiple containers in the `containerDefinitions` array. They share the same network namespace (can communicate via localhost), same lifecycle, and same storage volumes. This is useful for sidecar patterns (e.g., logging agent, proxy). Each container can have its own resource limits, but the sum must not exceed task-level CPU/memory.
You've just covered ECS Fargate Task Definitions — now see how well it sticks with free DVA-C02 practice questions. Full explanations included, no account needed.
Done with this chapter?