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 pushan 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
cpuandmemory, thenetworkMode, and up to two IAM roles. Each registration creates an immutable revision, referenced asfamily:revision, such asorders: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.
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.
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.
Stopping tasks cleanly
- When ECS stops a task it sends
SIGTERM, waits the container'sstopTimeout(30 seconds by default), then sendsSIGKILL. Spring Boot's graceful shutdown handlesSIGTERM; keep its timeout belowstopTimeout. - 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 withmanagement.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.
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:
| EC2 | Fargate | |
|---|---|---|
| What you run | EC2 instances in your account, registered to the cluster as container instances | Nothing: AWS supplies isolated compute per task |
| Packing | Many tasks per instance; you manage spare room and scaling | One task per isolated environment |
| You manage | AMI, patching, the ECS agent, instance scaling | The task definition only |
| You pay for | Instances while they run, used or not | The vCPU and memory the task requests, per second (one-minute minimum on Linux), from image pull until the task stops |
| Good for | GPUs, special instance types, daemons on every host, high steady use | Most 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.
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:
| Role | Used by | Typical permissions |
|---|---|---|
Task execution role (executionRoleArn) | The ECS agent and Fargate, while starting the task | Pull 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 runtime | Whatever 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)45s3.putObject(6PutObjectRequest.builder().bucket("orders-receipts").key(orderId + ".json").build(),7RequestBody.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.
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
hostNetworkaren'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 when | Choose EKS when |
|---|---|
| You want the fewest moving parts and only run on AWS | Your team already runs Kubernetes, or needs the same platform across clouds and on premises |
| You don't need the Kubernetes ecosystem | You rely on Helm charts, operators, CRDs or service meshes |
| You'd rather not pay or upgrade a control plane | You can own regular Kubernetes version upgrades |