TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท cloud ยท containers ยท ecs ยท eks ยท fargate

Amazon ECS, Fargate and EKS

Running containers on AWS. ECS schedules tasks from versioned task definitions and keeps services at their desired count behind a load balancer, EKS runs a managed Kubernetes control plane, and both run on EC2 instances you manage or on Fargate, which bills per task for the CPU and memory it asks for.

16 min6 animations

๐Ÿ“š Builds on๐Ÿ“ฆ Docker and containersโš“ Kubernetes๐Ÿ›ฌ Elastic Load Balancing: ALB and NLB

๐Ÿ–จ๏ธ Cheat sheet

A port for working containers

You've packed your app into a shipping container: everything it needs is inside one standard box. At this port the boxes aren't just cargo. Open the doors and each one is a little workshop that does a job, like taking orders.

First you leave your packed container at the port's container depot, a store where packed boxes wait until they're needed. Then you write a loading sheet: "take the orders box from the depot, give it this much room and power, and let it use this door pass". A loading sheet is called a task definition. Change anything, and you write a new version of the sheet with the next number on it. The old versions stay on file.

Then you ask the yard foreman to start one load from the sheet. The foreman reads the sheet, picks a lorry, and the port's porter fetches the box from the depot and sets it down on it. Then its doors open. One load, working, made from one sheet.

ECR, task definitions and tasks

Amazon Elastic Container Service (ECS) runs Docker containers on AWS. The pieces:

  • Amazon ECR (Elastic Container Registry) is AWS's private image registry. You docker push an image to a repository and ECS pulls it from there (Docker Hub and other registries work too).
  • A task definition is a versioned JSON document describing one unit of work: one or more container definitions (image, port mappings, environment, secrets, log configuration, health check), task-level cpu and memory, the networkMode, and up to two IAM roles. Each registration creates an immutable revision, referenced as family:revision, such as orders:7.
  • A task is a running instance of a task definition: its containers, started together on the same capacity.
  • A cluster is the logical group that tasks and services run in, together with the capacity behind them.
1{2  "family": "orders",3  "requiresCompatibilities": ["FARGATE"],4  "networkMode": "awsvpc",5  "cpu": "512",6  "memory": "1024",7  "executionRoleArn": "arn:aws:iam::123456789012:role/ordersExecutionRole",8  "taskRoleArn": "arn:aws:iam::123456789012:role/ordersTaskRole",9  "containerDefinitions": [10    {11      "name": "orders",12      "image": "123456789012.dkr.ecr.eu-west-1.amazonaws.com/orders:1.4",13      "portMappings": [{ "containerPort": 8080 }],14      "essential": true15    }16  ]17}

ECS itself (the scheduler and API) has no separate charge for EC2 or Fargate capacity: you pay for the instances or Fargate resources the tasks use. ECS Managed Instances and ECS Anywhere add a per-instance fee.

From image to running task5 steps
Loading sheets012๐Ÿง‘You๐Ÿฌ Container depot๐Ÿ‘ทYard foreman
Press play and watch it happen!

A standing order

Starting loads one by one is fine for a job that runs once and is done. But an orders workshop should always be open. So you give the foreman a standing order: "keep 3 loads from the orders sheet working, all the time". A standing order is called a service.

Customers don't walk up to the loads themselves. They come through the port gate, where a gate desk sends each one to a load that's ready, and keeps checking that every load still answers.

When a load breaks down, the gate desk stops sending customers to it. The foreman sees only 2 loads working instead of 3, and starts a fresh one from the same sheet. Nobody has to phone anyone.

Services: desired count and a load balancer

RunTask starts tasks once, which suits batch jobs. An ECS service keeps a long-running workload at its desired count: the service scheduler starts tasks until runningCount matches desiredCount, and replaces any task that stops or is marked unhealthy, spreading tasks across Availability Zones by default.

Attach the service to an Application or Network load balancer target group and ECS registers each new task as a target and deregisters it before stopping it. With awsvpc networking (always the case on Fargate) every task gets its own elastic network interface and private IP, so the target group uses ip targets.

A task can be marked unhealthy by the load balancer's health check or by a container healthCheck in the task definition. Set healthCheckGracePeriodSeconds on the service so slow-starting apps (a JVM warming up, for example) aren't killed before they're ready. Service Auto Scaling can change the desired count from CloudWatch metrics, with target tracking on CPU, memory or ALB requests per target.

A service keeps the desired count4 steps
โš“ Loads on duty๐Ÿ‘ฅCustomers๐Ÿ›‚Gate desk๐Ÿ‘ทYard foreman๐Ÿ“ฆLoad 1๐Ÿ“ฆLoad 2๐Ÿ“ฆLoad 3
Press play and watch it happen!

Swapping loads without closing

You've packed a new version of the orders box and written sheet number 2. You tell the foreman: "the standing order now uses sheet 2". The foreman swaps the loads over without ever closing the workshop. This swap is called a rolling deployment.

You set two limits. "Never fewer than 2 working loads" keeps customers served. "Never more than 4 at once" stops the yard getting crowded. So the foreman sets down 2 new loads next to the old ones first. The gate desk checks the new loads answer properly, then starts sending customers to them. Only then are the old loads closed and driven away.

If the new loads keep breaking, the foreman can stop the swap and go back to sheet 1.

Rolling deployments

Updating a service to a new task definition revision starts a deployment. With the default rolling update (ECS) deployment controller, two settings bound it, both as percentages of the desired count:

  • minimumHealthyPercent (rounded up): how many tasks must stay running. Default 100 for replica services.
  • maximumPercent (rounded down): how many may be running or pending at once. Default 200.

With desired 2 and the defaults, ECS starts 2 new tasks, waits for them to pass health checks, then drains and stops the old ones. Lowering minimumHealthyPercent to 50 lets ECS stop an old task first, which needs less spare capacity but serves with fewer tasks for a while.

The deployment circuit breaker watches whether new tasks reach a steady state. If they keep failing, it marks the deployment failed and, with rollback enabled, returns the service to the last completed deployment. ECS also offers blue/green deployments, where a whole new set of tasks is tested before traffic is switched over.

๐Ÿ”ง Going deeper

Stopping tasks cleanly

  • When ECS stops a task it sends SIGTERM, waits the container's stopTimeout (30 seconds by default), then sends SIGKILL. Spring Boot's graceful shutdown handles SIGTERM; keep its timeout below stopTimeout.
  • The load balancer's deregistration delay (300 seconds by default) is how long a draining task keeps finishing in-flight requests. Lower it for short requests, or every deployment waits five minutes per batch.
  • Point the target group's health check at an endpoint that checks only the task, such as /actuator/health/readiness (on ECS, enable it with management.endpoint.health.probes.enabled=true; Spring Boot turns the probes on by itself only on Kubernetes). A check that includes a shared database fails every task at once during a database outage, and ECS replaces them all without fixing anything.
A rolling deployment5 steps
Loading sheets012๐Ÿ‘ทYard foreman๐Ÿ›‚Gate desk๐Ÿ“ฆOld load 1๐Ÿ“ฆOld load 2
Press play and watch it happen!

Your own lorries or rented ones

Every load has to sit on a lorry. The port gives you two ways to get lorries.

Bring your own. You buy or hire your lorries, keep them fuelled and repaired, and the foreman fits as many loads onto each one as there's room for. You pay for every lorry the whole time it's in the yard, even when half of it is empty. In return you choose the lorry, and you can look under the bonnet.

Or rent a lorry by the trip, called Fargate. You only say how much room and power each load needs. The port brings a lorry that size, just for that load, and takes it away when the load is done. You pay for the size you asked for, for as long as the load works. You never see or fix a lorry, and you can't tinker with one either.

Capacity: EC2 or Fargate

Tasks need compute, and ECS offers two kinds:

EC2Fargate
What you runEC2 instances in your account, registered to the cluster as container instancesNothing: AWS supplies isolated compute per task
PackingMany tasks per instance; you manage spare room and scalingOne task per isolated environment
You manageAMI, patching, the ECS agent, instance scalingThe task definition only
You pay forInstances while they run, used or notThe vCPU and memory the task requests, per second (one-minute minimum on Linux), from image pull until the task stops
Good forGPUs, special instance types, daemons on every host, high steady useMost services and batch jobs; spiky or small workloads

On Fargate, cpu and memory must be one of the supported combinations (0.25 vCPU allows 0.5, 1 or 2 GB, for example), the network mode is always awsvpc, and each task gets 20 GiB of ephemeral storage before extra is billed. You can't SSH to the host; use ECS Exec for a shell in a container.

Capacity providers tie a cluster or service to its capacity: FARGATE, FARGATE_SPOT (spare capacity at a discount that can be reclaimed with a two-minute warning), or an Auto Scaling group of your own instances (see EC2) that ECS scales as tasks need room. A strategy can mix them, for example a base on FARGATE plus extra tasks on FARGATE_SPOT. ECS Managed Instances is a middle option: EC2 instances that AWS provisions and patches for you, for an extra per-instance management fee.

Capacity on EC2 or Fargate4 steps
๐Ÿš› Your own lorry๐Ÿšš Rented lorry๐Ÿšš Rented lorry๐Ÿ‘ทYard foreman
Press play and watch it happen!

Door passes for each load

Your orders workshop needs to drop receipts at the port's warehouse. You could hide a warehouse key inside the box, but then anyone who opens the box has a key that works forever.

Instead, the loading sheet names two passes. The porter's pass lets the port's own porter fetch your box from the depot and write in the port's log book. The load's own pass, called the task role, says which doors the workshop itself may open: the warehouse, yes; the records office, no.

The workshop asks the porter for today's copy of its pass whenever it needs one. Copies run out after a while, so a lost one is soon useless, and the porter hands out fresh ones.

Task roles and execution roles

A task definition names two IAM roles, and mixing them up is a classic mistake:

RoleUsed byTypical permissions
Task execution role (executionRoleArn)The ECS agent and Fargate, while starting the taskPull from ECR, write to CloudWatch Logs with the awslogs driver, read Secrets Manager or SSM parameters injected into the environment
Task role (taskRoleArn)Your application code, at runtimeWhatever the app calls: s3:PutObject on one bucket, sqs:SendMessage on one queue

CannotPullContainerError or ResourceInitializationError points at the execution role or at the task's network path to ECR and Secrets Manager; AccessDenied from your code means the task role is wrong. The task role's temporary credentials come from a credentials endpoint ECS exposes to the containers (AWS_CONTAINER_CREDENTIALS_RELATIVE_URI), and the AWS SDKs refresh them before they expire. Never bake access keys into the image.

In Java, the AWS SDK's default credentials chain finds the task role by itself:

1S3Client s3 = S3Client.builder()2        .region(Region.EU_WEST_1)3        .build();   // DefaultCredentialsProvider: env, ..., container credentials (the task role)4 5s3.putObject(6        PutObjectRequest.builder().bucket("orders-receipts").key(orderId + ".json").build(),7        RequestBody.fromString(receiptJson));

The same code runs unchanged on a laptop with a local profile, on EC2 with an instance profile and on ECS with a task role; only the credentials source differs.

Execution role and task role5 steps
๐Ÿง‘โ€๐Ÿ”งPort porter๐Ÿฌ Container depot๐Ÿ“ฆOrders load๐Ÿญ Warehouse๐Ÿ—„๏ธ Records office
Press play and watch it happen!

The international yard system

The foreman's rules belong to this port: simple, and nothing extra to pay. But many ports around the world use one standard yard system with its own rulebook, its own forms and its own tools. Crews who already know it can work in any port that uses it. This port offers it too, called EKS.

With it, the port runs the rule office for your yard, keeps it staffed and up to date, and charges a fee by the hour for it. You still need lorries. Bring a fleet of your own that the port helps you keep in shape, or rent lorries by the trip, one lorry for each load. Your crew writes the same standard forms they'd write anywhere else.

So pick the port's own rules when you want the simplest way to run containers here. Pick the standard system when your crew already uses it, or wants to move between ports.

EKS: managed Kubernetes

Amazon Elastic Kubernetes Service (EKS) runs the Kubernetes control plane for you: the API server and etcd, spread across several AZs, patched and scaled by AWS. A cluster is billed per hour (higher once its Kubernetes version leaves standard support and enters extended support), and you pay separately for the compute.

You run your workloads as standard Kubernetes objects (Deployments, Services, Ingresses) with kubectl or Helm, on:

  • Managed node groups: EC2 instances in an Auto Scaling group that EKS creates, updates and drains for you.
  • Self-managed nodes: your own instances that join the cluster.
  • Fargate profiles: pods whose namespace and labels match a profile run on Fargate, each in its own isolated compute environment. DaemonSets, privileged containers and hostNetwork aren't supported there, so node agents become sidecars.
  • EKS Auto Mode, where EKS also chooses, launches and patches the nodes.

Pods get AWS permissions through EKS Pod Identity (or the older IAM roles for service accounts), the counterpart of an ECS task role.

Choose ECS whenChoose EKS when
You want the fewest moving parts and only run on AWSYour team already runs Kubernetes, or needs the same platform across clouds and on premises
You don't need the Kubernetes ecosystemYou rely on Helm charts, operators, CRDs or service meshes
You'd rather not pay or upgrade a control planeYou can own regular Kubernetes version upgrades
EKS runs the Kubernetes control plane4 steps
โš“ Run by the port๐Ÿš› Your lorry fleet๐Ÿšš Rented lorry๐Ÿง‘โ€๐Ÿ”งYour crew๐Ÿ›๏ธRule office
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Amazon ECS, Fargate and EKS, told the same way as the story.
  1. The standing order says keep 3 loads working, and one load breaks down. What happens?
  2. You rent lorries by the trip. What are you paying for?
  3. Your orders workshop needs to drop receipts at the warehouse. Where should that permission go?
  4. During a swap to sheet 2, the yard must keep at least 2 working loads and hold at most 4. When are the old loads closed?
  5. Your crew already uses the standard international yard system at other ports and wants the same forms here. Which should you pick?
Answer every question to check.Passing marks Amazon ECS, Fargate and EKS as done.
Got the hang of Amazon ECS, Fargate and EKS? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ›ฐ๏ธ AWS in productionStep 3 of 7

โ† Previous on the path๐Ÿชง Amazon Route 53Next on the path โ†’๐Ÿ“ข Amazon EventBridge