Skip to content

Lesson 13 of 30Modern AWS

Containers on AWS

Push images to ECR, run them on ECS with Fargate, and know when EKS or ECS Express Mode is the better fit.

23 min read0/7 questions

You already know how to build a Docker image and push it to a registry from the Docker course (Writing a Dockerfile, and Registries and Image Distribution), so this lesson does not re-teach images or Dockerfiles. The next question in every real job is "where does it run?", and on AWS the most common answer is ECS on Fargate: you hand AWS a container image and a CPU and memory size, and it runs, restarts and scales it without you managing a single server. This lesson walks the path from docker build to a load-balanced service in private subnets.

ECR: your private image registry

Amazon ECR (Elastic Container Registry) is a private Docker registry in your account. Each app gets a repository; images are tagged like any registry. IAM controls who can push and pull, and ECR can scan images for known vulnerabilities on push.

build and push
ACCOUNT=123456789012REGION=us-east-1REPO=$ACCOUNT.dkr.ecr.$REGION.amazonaws.com/apiaws ecr create-repository --repository-name api --image-scanning-configuration scanOnPush=trueaws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin $ACCOUNT.dkr.ecr.$REGION.amazonaws.comdocker build --platform linux/arm64 -t $REPO:1.4.2 .docker push $REPO:1.4.2

Tag images with something immutable (a version or the git SHA), not just latest, so you always know exactly what is running and can roll back. Add a lifecycle policy to delete old untagged images, or storage grows forever.

ECS: tasks, task definitions and services

Amazon ECS (Elastic Container Service) is AWS's container orchestrator. Its vocabulary maps neatly onto Docker Compose (see the Docker Compose lesson if you need a refresher):

  • A task definition is the recipe: image, CPU, memory, ports, environment, secrets, log settings, IAM roles. Like a service block in compose.yaml. It is versioned (api:7, api:8).
  • A task is one running copy of a task definition: one or more containers started together.
  • A service keeps N tasks running, replaces failed ones, registers them with a load balancer's target group and does rolling deploys.
  • A cluster is the logical group your services live in.

And where tasks run is the launch type (or capacity provider):

  • Fargate: serverless. You choose CPU and memory per task; AWS finds the machine. No instances to patch.
  • EC2: tasks run on EC2 instances you manage in the cluster. Cheaper at large steady scale and needed for GPUs, but you own the fleet.
task-definition.json (trimmed)
{
  "family": "api",
  "requiresCompatibilities": ["FARGATE"],
  "networkMode": "awsvpc",
  "cpu": "512",
  "memory": "1024",
  "runtimePlatform": { "cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX" },
  "executionRoleArn": "arn:aws:iam::123456789012:role/api-execution-role",
  "taskRoleArn": "arn:aws:iam::123456789012:role/api-task-role",
  "containerDefinitions": [
    {
      "name": "api",
      "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/api:1.4.2",
      "portMappings": [{ "containerPort": 8000 }],
      "environment": [{ "name": "APP_ENV", "value": "production" }],
      "secrets": [
        { "name": "DATABASE_URL", "valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/db-url" }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": { "awslogs-group": "/ecs/api", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "api" }
      },
      "healthCheck": { "command": ["CMD-SHELL", "curl -f http://localhost:8000/health || exit 1"] }
    }
  ]
}

Notice the two roles, a classic interview question:

  • The execution role is used by ECS itself, before your code runs: pull the image from ECR, fetch the secrets, create the log stream.
  • The task role is what your code uses at runtime to call AWS (S3, SQS, DynamoDB). Same idea as an EC2 instance profile.
Quick check
Your task fails to start with ResourceInitializationError: unable to pull secrets. Which role needs fixing?
Need a nudge? A hint rules out a wrong answer.

The standard architecture

ALB to an ECS Fargate service to RDS
VPCPublic subnetsPrivate app subnets (ECS service, desired 2)Private DB subnetsUsersUsersInternet GWInternet GWALB: HTTPS :443ALBHTTPS :443NAT gatewayNAT gatewayapi task: AZ aapi taskAZ aapi task: AZ bapi taskAZ bRDS Postgres: Multi-AZRDS PostgresMulti-AZECR: api:1.4.2ECRapi:1.4.2Secrets ManagerSecrets ManagerCloudWatch LogsCloudWatch LogsHTTPS:8000:5432pullsecrets

Startup: using the execution role, ECS pulls the image from ECR (through the NAT, or VPC endpoints) and injects secrets from Secrets Manager.

1/5

Deploys and scaling

When you register a new task definition revision and update the service, ECS does a rolling deployment: start new tasks, wait for them to pass health checks, drain and stop old ones. Two settings control the pace: minimumHealthyPercent (how low you can dip) and maximumPercent (how many extra you can run). The deployment circuit breaker rolls back automatically if new tasks keep failing.

Pythonrolling_deploy.py
desired = 4max_percent = 150 # may run up to 6 tasks during the deploymin_healthy = 100 # never fewer than 4 healthy old, new = desired, 0step = 0while old > 0: room = desired * max_percent // 100 - (old + new) start = min(room, desired - new) new += start stop = min(old, (old + new) - desired * min_healthy // 100) old -= stop step += 1 print(f"step {step}: started {start}, stopped {stop} -> old={old} new={new}")
Output
Press Run (⌘ Enter) to see what happens.

Service auto scaling works like EC2's: a target tracking policy on CPU, memory, or ALB requests per target adds and removes tasks between a min and a max.

Put it in order5 steps

Order what happens when CI deploys a new version to ECS.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Three health checks, and why tasks die in a loop

A new service that starts, runs for a minute, gets killed and starts again is the most common first-week ECS problem. Usually the app is fine. One of three different health checks is failing, and each one has a different owner and a different fix.

CheckWhere it is setWho acts on a failureCommon mistake
Container healthCheckTask definitionECS marks the container unhealthy and replaces the taskThe command needs curl, which slim images do not include
Target group health checkLoad balancerThe ALB stops sending traffic; ECS replaces tasks the ALB reports unhealthyThe path returns 404 or a 302 redirect to a login page, and only 200 counts by default
Grace period (healthCheckGracePeriodSeconds)ECS serviceNobody, for that long after startLeft at 0 for an app that needs 45 seconds to warm up

Look back at the task definition above: its container check runs curl. On python:3.13-slim there is no curl, so the check fails forever and the task is replaced every few minutes, with nothing useful in the app's own logs. Either install it, or use the language you already have, as the Docker Compose lesson in the Docker course does: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"]. The container check also has a startPeriod (up to a few minutes) during which failures do not count.

For the ALB check, point it at a dedicated endpoint such as /health that returns 200 without auth and without redirects. Keep it cheap and shallow: if it checks the database too, a short database blip marks every task unhealthy at once, ECS replaces them all, and a small problem becomes a full outage. Deeper dependency checks belong in a separate readiness or diagnostics endpoint that alarms rather than kills.

When the deployment circuit breaker is on, repeated health check failures roll the deploy back. That is good, but it can hide the reason, so read the stopped tasks before trying again (see the debugging section below).

Quick check
A new Fargate service keeps replacing its tasks every two to three minutes. App logs show it started fine and served /health with 200. The task definition's container health check is curl -f http://localhost:8000/health || exit 1 and the image is python:3.13-slim. Most likely cause?
Need a nudge? A hint rules out a wrong answer.

Stopping tasks without dropping requests

Every deploy and every scale-in stops tasks. Done carelessly, each one cuts off the requests that task was serving, and users see a burst of 502s on every release. ECS stops a task behind a load balancer in a fixed order:

How ECS stops a task behind an ALB
ECSALBTaskderegister targetfinish in-flight requestsdraining doneSIGTERMSIGKILL after stopTimeout

ECS removes the task from the target group first. The ALB stops sending it new requests.

1/5

Three settings, tuned together:

  • Deregistration delay on the target group: set it a little above your slowest normal request. For an API whose requests finish in under a few seconds, 30 seconds or less is common, and it cuts minutes off every deploy. Long uploads or streaming responses need more.
  • stopTimeout in the task definition: long enough for your shutdown code to finish background work, such as flushing a batch or finishing the current queue message.
  • The app itself must handle SIGTERM. Uvicorn and Gunicorn do, as long as they are PID 1 or behind a proper init and your CMD uses the exec form. Docker in Production covers why a shell-form CMD swallows the signal.

Queue workers need the same thought from the other side: on SIGTERM, stop pulling new messages, finish the current one, and let unfinished messages return to the queue after their visibility timeout.

Put it in order5 steps

Order what happens when ECS stops a task during a deploy.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Debugging a task that will not stay up

When a service is unhealthy, start with why the last tasks stopped. ECS records a stop reason on every stopped task, and it keeps stopped tasks visible for only a short time (about an hour at the time of writing), so look soon.

aws ecs list-tasks --cluster prod --service-name api --desired-status STOPPEDaws ecs describe-tasks --cluster prod --tasks <task-arn> --query "tasks[].{reason:stoppedReason,containers:containers[].{name:name,exit:exitCode,why:reason,health:healthStatus}}"aws ecs describe-services --cluster prod --services api --query "services[].events[:5].message"

The service events are the other half: "has reached a steady state", "unable to place a task", "has stopped 2 running tasks due to health checks". Between the two, most problems name themselves.

Match the pairs0/4 matched

Match the stop reason to its usual cause.

Choose an item, then its match on the other side.

Once a task is running but misbehaving, ECS Exec opens a shell in it, like docker exec, through Systems Manager. It needs three things: the service created or updated with --enable-execute-command (existing tasks only get it after a new deployment), a task role allowed to open the SSM message channels, and the Session Manager plugin on your machine.

aws ecs update-service --cluster prod --service api --enable-execute-command --force-new-deploymentaws ecs execute-command --cluster prod --task <task-id> --container api --interactive --command "sh"

Every Exec session can be logged to CloudWatch or S3, and access is controlled by IAM, so it is a far better option than opening SSH anywhere. Treat it as a diagnostic tool, not a way to change production by hand: whatever you fix inside a task disappears on the next deploy.

Fargate sizing and cost

Fargate tasks come in fixed CPU and memory combinations (0.25 vCPU with 0.5 to 2 GB, up to 16 vCPU with 120 GB). You pay per second for the vCPU and GB you reserve, whether or not the app uses them.

Pythonfargate_cost.py
# Example Linux/ARM prices; check the current Fargate pricing page.VCPU_HOUR = 0.03238GB_HOUR = 0.00356HOURS = 730 def monthly(vcpu, gb, tasks): return round((vcpu * VCPU_HOUR + gb * GB_HOUR) * HOURS * tasks, 2) print("2 tasks, 0.5 vCPU / 1 GB:", monthly(0.5, 1, 2))print("2 tasks, 1 vCPU / 2 GB: ", monthly(1, 2, 2))print("6 tasks, 1 vCPU / 2 GB: ", monthly(1, 2, 6))
Output
Press Run (⌘ Enter) to see what happens.

Fargate Spot runs interruptible tasks at a large discount, which suits workers that pull from a queue.

EKS, App Runner and ECS Express Mode

Amazon EKS (Elastic Kubernetes Service) runs a managed Kubernetes control plane. Choose it when you need Kubernetes: your team already runs it, you want Helm charts and the Kubernetes ecosystem, or you want the same platform across clouds. The control plane is billed per cluster before any nodes (check the EKS pricing page), and it is much more to learn and operate. EKS Auto Mode manages the nodes for you, which narrows the gap.

AWS App Runner was the simplest path: point it at an image and get an HTTPS URL with auto scaling and no VPC, ALB or task definition. AWS closed it to new customers on 30 April 2026. Existing customers can keep running their services, but new features go elsewhere, so do not start anything new on it, and plan a move if you inherit one.

The replacement AWS recommends is ECS Express Mode. You give it an image and two roles, and it creates an ordinary ECS service on Fargate with an ALB, HTTPS, health checks, auto scaling and logging, all as normal resources in your account. You get App Runner's "one command to a URL" start without its ceiling, because everything it built is regular ECS that you can tune later with the rest of this lesson. Choosing Container Compute: ECS, Fargate, EKS and Lambda walks through an Express Mode deploy and when to step past it.

ECS on FargateEKSApp Runner (existing customers only)
You learnECS concepts (small)Kubernetes (large)Almost nothing
Control plane costFreeHourly per clusterIncluded
Networking controlFull (your VPC)FullLimited
PortabilityAWS onlyAny KubernetesAWS only
Best forMost teams on AWSTeams standardized on KubernetesSimple web services, prototypes
Match the pairs0/4 matched

Where should it run?

Choose an item, then its match on the other side.
Quick check
Your Fargate tasks are in private subnets with no NAT gateway and no VPC endpoints. The service never starts: CannotPullContainerError. Why?
Need a nudge? A hint rules out a wrong answer.
Key terms
ECR
Elastic Container Registry: a private Docker image registry in your account.
task definition
The versioned ECS recipe: image, CPU, memory, ports, env, secrets, roles, logs.
ECS service
Keeps N tasks running, registers them with a load balancer, and does rolling deploys.
Fargate
Serverless compute for containers: pick CPU and memory per task, no instances to manage.
execution role vs task role
Execution role: ECS pulls images and secrets. Task role: your code calls AWS at runtime.
EKS
Managed Kubernetes on AWS. Choose it when you need the Kubernetes ecosystem.
ECS Express Mode
Creates a complete ECS service (Fargate, ALB, HTTPS, scaling) from an image; AWS's replacement for App Runner.
deregistration delay
How long a load balancer keeps draining a target's in-flight requests before ECS stops the task.
ECS Exec
A shell or command inside a running task through Systems Manager, controlled and logged by IAM.