AWS Fargate in practice: serverless ECS, from Dockerfile to ALB
Learn what AWS Fargate is, compare it with ECS on EC2, Lambda, and EKS on Fargate, and ship an ARM64 container on ECS with ECR, a task definition, an ALB, ECS Exec, Fargate Spot, and Terraform.
Cloud$ aws ecs create-cluster --cluster-name shop▍You have a Docker image and want to run it in production on AWS without looking after instances, AMIs, operating system patches, and node scaling. That is exactly the problem AWS Fargate solves: you describe how much CPU and memory each task needs, and AWS finds somewhere to run it. In this guide we go from docker build to a service behind an Application Load Balancer, covering ECS Exec, Service Connect, Fargate Spot, Terraform, and Fargate on EKS along the way.
What Fargate is
Fargate is a serverless compute engine for containers. It is not an orchestrator: Amazon ECS or Amazon EKS schedules the tasks. Fargate is the “where” the container runs. Each task (or pod, on EKS) gets its own isolated environment, with its own elastic network interface (ENI) inside your VPC. That is why the network mode is always awsvpc.
If you are still choosing between containers, VMs, and functions, read containers vs virtual machines vs serverless first.
| ECS on Fargate | ECS on EC2 | AWS Lambda | EKS on Fargate | |
|---|---|---|---|---|
| You manage | Image and task definition | Image, instances, AMI, node scaling | Function code or image | Kubernetes manifests and the EKS cluster |
| Unit | Task | Task on your instance | Invocation | Pod |
| Maximum size | 32 vCPU and up to 244 GB | Whatever the instance offers | 10,240 MB of memory, proportional CPU | Follows Fargate sizes |
| GPU | No | Yes | No | No |
| Long-running processes | Yes | Yes | Up to 30 min per invocation | Yes |
| DaemonSets / privileged mode | Not applicable / no | Yes | No | No |
| Good for | APIs and workers without managing nodes | GPUs, host-level tuning, high density | Short events and unpredictable spikes | Teams already standardized on Kubernetes |
Rule of thumb: start with Fargate. Move to EC2 when you need GPUs, host access, or density that pays for managing instances. Use Lambda when the work is event-driven and short (see the AWS Lambda practical guide).
Valid task sizes
On Fargate, CPU and memory are set at the task level, and only some combinations are accepted:
| CPU (units) | vCPU | Memory | OS |
|---|---|---|---|
| 256 | 0.25 | 512 MiB, 1 GB, 2 GB | Linux |
| 512 | 0.5 | 1 to 4 GB | Linux |
| 1024 | 1 | 2 to 8 GB | Linux, Windows |
| 2048 | 2 | 4 to 16 GB (1 GB steps) | Linux, Windows |
| 4096 | 4 | 8 to 30 GB (1 GB steps) | Linux, Windows |
| 8192 | 8 | 16 to 60 GB (4 GB steps) | Linux |
| 16384 | 16 | 32 to 120 GB (8 GB steps) | Linux |
| 32768 | 32 | 60, 120, or 244 GB | Linux |
The 32 vCPU size is new (June 2026) and works on both x86 and ARM. Sizes from 8 vCPU up require Linux platform version 1.4.0, which is LATEST today. Check the current docs before sizing.
Step 1: a small image
A minimal Python API, using only the standard library:
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
body, ctype = b"ok", "text/plain"
else:
body = json.dumps({"service": "orders", "version": os.getenv("APP_VERSION", "dev")}).encode()
ctype = "application/json"
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
HTTPServer(("0.0.0.0", int(os.getenv("PORT", "8080"))), Handler).serve_forever()
FROM python:3.14-slim
WORKDIR /app
COPY app.py .
RUN useradd --uid 10001 --no-create-home app
USER 10001
ENV PORT=8080
EXPOSE 8080
CMD ["python", "app.py"]
This Dockerfile was built and run locally with docker buildx build --platform linux/arm64, and the / and /health endpoints responded. The container runs as an unprivileged user. For smaller images, see Docker multi-stage builds.
Step 2: push to ECR
aws ecr create-repository --repository-name orders \
--image-scanning-configuration scanOnPush=true \
--image-tag-mutability IMMUTABLE
aws ecr get-login-password --region sa-east-1 \
| docker login --username AWS --password-stdin 123456789012.dkr.ecr.sa-east-1.amazonaws.com
docker buildx build --platform linux/arm64 \
-t 123456789012.dkr.ecr.sa-east-1.amazonaws.com/orders:1.0.0 --push .
Immutable tags keep 1.0.0 from pointing at a different image tomorrow. The aws commands were checked with aws <cmd> help and run against a local mock (moto); the real push was not tested, because the lab has no AWS account.
Step 3: the task definition
{
"family": "orders",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "1024",
"memory": "2048",
"runtimePlatform": { "cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX" },
"ephemeralStorage": { "sizeInGiB": 30 },
"executionRoleArn": "arn:aws:iam::123456789012:role/orders-execution-role",
"taskRoleArn": "arn:aws:iam::123456789012:role/orders-task-role",
"containerDefinitions": [
{
"name": "app",
"image": "123456789012.dkr.ecr.sa-east-1.amazonaws.com/orders:1.0.0",
"essential": true,
"portMappings": [
{ "name": "http", "containerPort": 8080, "protocol": "tcp", "appProtocol": "http" }
],
"environment": [{ "name": "APP_VERSION", "value": "1.0.0" }],
"healthCheck": {
"command": ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')"],
"interval": 30, "timeout": 5, "retries": 3, "startPeriod": 10
},
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/orders",
"awslogs-region": "sa-east-1",
"awslogs-stream-prefix": "app",
"awslogs-create-group": "true"
}
}
}
]
}
The points that trip people up most:
cpu/memorymust be a combination from the table above (here, 1 vCPU and 2 GB).runtimePlatformwithARM64runs on Graviton (Linux only). The image must have been built forlinux/arm64.ephemeralStorage: the default is 20 GiB; you can ask for 21 to 200 GiB.- The execution role is used by the ECS agent to pull the image from ECR, create the log stream, and read secrets. It usually gets the managed policy
AmazonECSTaskExecutionRolePolicy. - The task role is your application’s identity: access to S3, DynamoDB, SQS, and also the
ssmmessagespermissions that ECS Exec requires. awslogs-create-grouponly works if the execution role can calllogs:CreateLogGroup. In production, prefer creating the log group beforehand, with a retention period.
This task definition was validated with the botocore 1.44.11 Stubber, which checks parameters against the real service model (a wrong field such as sizeGiB is rejected), and with aws ecs register-task-definition --generate-cli-skeleton. The health check was run inside the local container.
aws ecs register-task-definition --cli-input-json file://taskdef.json
Step 4: cluster, ALB, and service
The ALB needs an ip target group, because each task has its own IP in the VPC. The tasks sit in private subnets with no public IP, and their security group only accepts traffic from the ALB’s security group.
aws ecs create-cluster --cluster-name shop \
--capacity-providers FARGATE FARGATE_SPOT \
--default-capacity-provider-strategy capacityProvider=FARGATE,weight=1,base=1 \
--settings name=containerInsights,value=enhanced
TG_ARN=$(aws elbv2 create-target-group --name orders-tg --protocol HTTP --port 8080 \
--vpc-id vpc-0abc --target-type ip --health-check-path /health \
--query 'TargetGroups[0].TargetGroupArn' --output text)
aws ec2 authorize-security-group-ingress --group-id sg-tasks \
--protocol tcp --port 8080 --source-group sg-alb
# ALB and listener: aws elbv2 create-load-balancer / create-listener (in production, HTTPS with ACM)
aws ecs create-service --cluster shop --service-name orders \
--task-definition orders --desired-count 2 \
--capacity-provider-strategy capacityProvider=FARGATE,weight=1,base=1 capacityProvider=FARGATE_SPOT,weight=3 \
--network-configuration 'awsvpcConfiguration={subnets=[subnet-priv-a,subnet-priv-b],securityGroups=[sg-tasks],assignPublicIp=DISABLED}' \
--load-balancers targetGroupArn=$TG_ARN,containerName=app,containerPort=8080 \
--health-check-grace-period-seconds 30 \
--deployment-configuration 'deploymentCircuitBreaker={enable=true,rollback=true}' \
--enable-execute-command
aws ecs wait services-stable --cluster shop --services orders
The circuit breaker rolls back automatically if the new deployment does not stabilize. Private subnets need a way out to ECR and CloudWatch Logs, through a NAT gateway or VPC endpoints. All of these commands ran against local moto; real ALB behavior was not tested.
ECS Exec, Service Connect, Spot, and Express Mode
ECS Exec opens a shell inside a running task, through SSM, with no SSH. It needs --enable-execute-command on the service, ssmmessages permissions on the task role, and the Session Manager plugin on your machine:
aws ecs execute-command --cluster shop --task <task-id> \
--container app --interactive --command "/bin/sh"
Service Connect provides service discovery and load balancing between services in the same namespace (Cloud Map), using the name from portMappings. Other services can then call http://orders:
aws ecs update-service --cluster shop --service orders \
--service-connect-configuration 'enabled=true,namespace=shop,services=[{portName=http,clientAliases=[{port=80,dnsName=orders}]}]'
I found no recent changes to Service Connect, but check the current docs.
Fargate Spot uses spare capacity at a discount and can interrupt the task with a two-minute warning (SIGTERM). Use it for idempotent workers or as part of your capacity, as in the strategy above: base=1 guarantees one on-demand task and the rest leans 3:1 toward Spot. Windows does not run on Spot. The ARM64 + Fargate Spot combination on ECS appears in the 32 vCPU size announcement, but confirm it in the docs before you rely on it; if in doubt, use X86_64 for Spot tasks.
ECS Express Mode (GA in November 2025, ARM64 since September 2026) is the shortcut for anyone who just wants “image → HTTPS URL.” It creates a shared ALB, target groups, security groups, auto scaling, and an AWS-provided domain:
aws ecs create-express-gateway-service --service-name orders \
--execution-role-arn arn:aws:iam::123456789012:role/ecsTaskExecutionRole \
--infrastructure-role-arn arn:aws:iam::123456789012:role/ecsExpressInfrastructureRole \
--primary-container image=123456789012.dkr.ecr.sa-east-1.amazonaws.com/orders:1.0.0,containerPort=8080 \
--cpu-architecture ARM64 --health-check-path /health
It is a recent feature: the parameters were validated with the Stubber, but not in a real account. There is also the new ECS Gateway (October 2026), managed ingress that shares ALBs across services. Read the current docs before adopting either one.
The same service in Terraform
Validated with terraform validate and terraform fmt -check (provider hashicorp/aws 6.74.0), with no plan or apply:
resource "aws_ecs_cluster" "shop" {
name = "shop"
setting {
name = "containerInsights"
value = "enhanced"
}
}
resource "aws_ecs_cluster_capacity_providers" "shop" {
cluster_name = aws_ecs_cluster.shop.name
capacity_providers = ["FARGATE", "FARGATE_SPOT"]
}
resource "aws_ecs_task_definition" "orders" {
family = "orders"
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = "1024"
memory = "2048"
execution_role_arn = var.execution_role_arn
task_role_arn = var.task_role_arn
runtime_platform {
cpu_architecture = "ARM64"
operating_system_family = "LINUX"
}
ephemeral_storage {
size_in_gib = 30
}
container_definitions = jsonencode([{
name = "app"
image = var.image
essential = true
portMappings = [{ name = "http", containerPort = 8080, protocol = "tcp" }]
logConfiguration = {
logDriver = "awslogs"
options = {
awslogs-group = "/ecs/orders"
awslogs-region = "sa-east-1"
awslogs-stream-prefix = "app"
}
}
}])
}
resource "aws_ecs_service" "orders" {
name = "orders"
cluster = aws_ecs_cluster.shop.id
task_definition = aws_ecs_task_definition.orders.arn
desired_count = 2
enable_execute_command = true
capacity_provider_strategy {
capacity_provider = "FARGATE"
base = 1
weight = 1
}
capacity_provider_strategy {
capacity_provider = "FARGATE_SPOT"
weight = 3
}
network_configuration {
subnets = var.private_subnet_ids
security_groups = [var.tasks_sg_id]
assign_public_ip = false
}
load_balancer {
target_group_arn = var.target_group_arn
container_name = "app"
container_port = 8080
}
deployment_circuit_breaker {
enable = true
rollback = true
}
depends_on = [aws_ecs_cluster_capacity_providers.shop]
}
The variables (image, roles, subnets, security group, and target group) go in a variables.tf. The tested file also creates the log group with retention.
EKS on Fargate
On EKS, Fargate is selected through Fargate profiles: each profile has namespace selectors and, optionally, labels. A pod that matches a profile runs on Fargate; a pod that matches none stays Pending if there are no EC2 nodes.
aws eks create-fargate-profile --cluster-name shop-eks --fargate-profile-name apps \
--pod-execution-role-arn arn:aws:iam::123456789012:role/AmazonEKSFargatePodExecutionRole \
--subnets subnet-priv-a subnet-priv-b \
--selectors 'namespace=shop,labels={compute=fargate}'
The limits weigh heavily on the decision: no DaemonSets, no privileged containers, no GPUs, no hostPort/hostNetwork, private subnets only, and load balancers with IP targets only. Logging and monitoring agents have to become sidecars. To build the cluster itself, see install EKS with Terraform.
Costs: what goes into the bill
No price table here (prices vary by Region), but these are the dimensions:
- vCPU and memory for the time the task runs, billed per second, with different rates for x86 and ARM, and for on-demand and Spot.
- Ephemeral storage beyond the included 20 GiB.
- ALB per hour and per LCU; NAT gateway per hour and per GB processed.
- CloudWatch Logs per GB ingested and stored; ECR per GB stored; public IPv4 addresses per hour.
Compute Savings Plans also cover Fargate. For the full method, read FinOps: cut AWS costs and Savings Plans and Reserved Instances.
Checklist
- Image built for the task’s architecture (
linux/arm64for Graviton) with an immutable tag in ECR - CPU and memory in a valid combination, and
ephemeralStorageonly if you need more than 20 GiB - Separate execution role and task role, each with least privilege
- Tasks in private subnets, a SG that only accepts the ALB, and an
iptarget group - Circuit breaker with rollback and
aws ecs wait services-stablein the pipeline - ECS Exec enabled and audited; Fargate Spot only for tasks that tolerate interruption
- Log group with retention and a periodic review of the cost dimensions
Fargate does not eliminate operations; it trades “looking after servers” for “getting the task definition, networking, and permissions right,” which is a much better job to have.