English translation of the Chinese courseware. Check linked official documentation for version-sensitive details.

Docker Hour 4: Going to the Cloud (AWS)

Push the same myapp to Amazon ECR, deploy it to Amazon ECS on AWS Fargate behind an ALB, practice releases, rollbacks and cloud troubleshooting, then move on to Amazon EKS
Amazon ECS · AWS FargateECR · Secrets Manager · ElastiCache (Valkey)ALB · CloudWatch · EKS Auto ModeVerified against official docs · 2026-11
Overall learning objectives
  • Choose between EC2 + Docker, ECS on Fargate, ECS on EC2, EKS and Lambda container images for a given scenario, and know that App Runner no longer accepts new customers (as of 2026-04-30); new projects should use ECS Express Mode instead.
  • Master ECR immutable tags, scanning (basic scanning / Amazon Inspector enhanced scanning), lifecycle policies, pull through cache and cross-Region replication.
  • Understand how clusters, task definitions, services and tasks relate, distinguish the task execution role from the task role, deploy myapp to Fargate, and reach it through an ALB (target type ip).
  • Inject secrets with the task definition's secrets (Secrets Manager / SSM Parameter Store) and connect to ElastiCache Serverless (Valkey, TLS).
  • Master rolling update parameters, automatic rollback with the deployment circuit breaker, ECS native blue/green deployments and Application Auto Scaling target tracking.
  • Diagnose cloud failures with the stoppedReason from describe-tasks, CloudWatch Logs / Logs Insights and ECS Exec; deploy the same image to EKS.

1-hour schedule

#TimeModuleKey contentAnimation / interactiveLab
0Before classWarm-up and AWS setupAWS CLI v2, IAM Identity Center (SSO) profile, Region ca-central-1, variables file, VPC trade-offs, cost and permissions—aws configure sso + variables
100–05Choosing a cloud container service (AWS)EC2 / ECS Fargate / ECS on EC2 / EKS / App Runner (closed to new customers) / Lambda; ECS object modelSelection wizardConfirm identity and Region
205–13ECR in depthImmutable tags, scanning, 12-hour login token, lifecycle policies, pull through cache, replication, multi-archLifecycle policy simulatorCreate repository, push, scan
313–24Deploy to ECS on Fargate ⭐Two IAM roles, awsvpc and security groups, CPU/memory combinations, ALB + target group, health checkscreate-service animation + Fargate size validatorDeploy myapp and access it through the ALB
424–32Configuration, secrets and cacheenvironment vs secrets, force new deployment, ElastiCache Serverless (Valkey), TLS, security groups"When do secrets take effect" simulatorSecrets Manager + Valkey
532–40Release strategies, rollback and scalingmin/maxPercent, circuit breaker, native blue/green (bake time), CodeDeploy comparison, target tracking scalingRolling vs blue/green simulatorCircuit breaker rollback + blue/green + load test
640–50Cloud troubleshooting in practiceFour local failure types; CannotPull, ResourceInitialization, Essential exited, health checks, OOM, exec format6 cloud failure drillsBreak things on purpose and fix them
750–57Moving to Kubernetes (EKS)EKS Auto Mode / eksctl, nodes pulling from ECR, task definition → K8s manifestsECS/Compose → K8s mapper(Optional) EKS Auto Mode deployment
857–60Cost, cleanup and self-checkBilling for Fargate, ALB, NAT, ElastiCache, EKS and logs; cleanup in dependency orderCleanup order exerciseFull cleanup script
—After classCheat sheet · Capstone labEnd to end: ECR (immutable + scanning) → Fargate + ALB → secrets → circuit breaker rollback → scaling → cleanupFinal quizCapstone lab

Azure ↔ AWS concept mapping

If you took Lesson 3 (Azure), use this table to carry over what you already know. The mappings mean "similar purpose", not exact equivalence.

TopicLesson 3 (Azure)This lesson (AWS)Key differences
Image registryACRAmazon ECR (each repository created separately)ECR tag immutability is set per repository; ACR locks per image
Registry cleanupacr purge (scheduled via ACR Tasks)ECR lifecycle policies (JSON rules, applied automatically on the service side)With ECR you don't schedule any tasks yourself
Upstream cacheArtifact Cache (credential set in Key Vault)Pull through cache (credentials in Secrets Manager, name prefix ecr-pullthroughcache/)Both need credentials to access Docker Hub
Serverless container platformAzure Container AppsAmazon ECS on AWS FargateACA has built-in HTTPS ingress; with ECS you set up an ALB yourself (Express Mode can create one automatically)
Platform boundaryContainer Apps environmentECS cluster + VPC/subnets/security groupsOn AWS you design the network explicitly
App / versionApp / revisionService / task definition revision (family:revision)Every task definition registration creates a new revision number
ReplicaReplicaTaskEach Fargate task has its own ENI and private IP
Identity for pulling imagesUser-assigned managed identity + AcrPullTask execution role (AmazonECSTaskExecutionRolePolicy)Application code uses a different role to access AWS: the task role
Secretssecretref / Key Vault referenceTask definition secrets: valueFrom = Secrets Manager / SSM parameter ARNECS injects only at container start, so you must force a new deployment after an update; an unversioned Key Vault reference refreshes automatically within 30 minutes
Managed RedisAzure Managed RedisElastiCache Serverless (Valkey)Serverless always has TLS enabled; access control is RBAC user groups only
Traffic splitting / canaryMultiple revision mode + weightsECS native blue/green / linear / canary deployments (ALB listener rules), CodeDeployECS native blue/green is a one-time full cutover + bake time
Automatic rollback on failureIn single mode, traffic isn't shifted unless the new revision is readyDeployment circuit breaker deploymentCircuitBreaker {enable, rollback}The circuit breaker applies only to rolling updates (ECS deployment controller)
ScalingKEDA rules (HTTP concurrency, etc.)Application Auto Scaling target tracking (CPU, ALBRequestCountPerTarget)ECS services don't scale to zero (minimum can be 0, but no request triggers a wake-up)
LogsLog Analytics + KQLCloudWatch Logs (awslogs driver) + Logs InsightsFor platform events, check the events in describe-services and the task stoppedReason
Shell into a containeraz containerapp execECS Exec: aws ecs execute-commandRequires the Session Manager plugin and ssmmessages permissions on the task role
KubernetesAKS (--attach-acr)EKS (eksctl / EKS Auto Mode; node role includes AmazonEC2ContainerRegistryPullOnly)The EKS control plane is billed hourly
Cleanupaz group deleteDelete resources one by one in dependency order (or delete a CloudFormation stack)AWS has no equivalent of "delete the resource group in one go"; use tags to find resources

How this lesson relates to earlier lessons

Lessons 1 and 2
myapp (Python/gunicorn + Redis counter), non-root, /healthz, multi-stage Dockerfile, graceful shutdown, tagging strategy. This lesson reuses them directly: the ALB health check targets /healthz, and task definition revisions map to image tags.
Lesson 3 (Azure)
This lesson is its AWS counterpart, with modules mapped one to one. You can take this lesson without Lesson 3: the app.py changes you need are given again in the Module 2 lab.
Lesson 5
Hour 5 is "Image CI, Supply Chain and Release". It uses both Lesson 3's ACR / Container Apps and this lesson's ECR / ECS. This lesson's variables live in ~/hour4-aws.env; Lesson 5 uses ~/hour5.env.
Cost noteThis lesson creates ECR, an ECS cluster (free in itself), Fargate tasks, an ALB, a CloudWatch log group, a Secrets Manager secret and ElastiCache Serverless; EKS is optional. As long as you clean up the same day following Module 8, the total cost is usually a few US dollars (refer to the official ca-central-1 pricing pages and the AWS Pricing Calculator). The ALB, ElastiCache, the EKS control plane and NAT gateways are all billed hourly, even when idle.
Security noteDon't use the root user; use temporary credentials from IAM Identity Center. Don't open 0.0.0.0/0 to any port other than 80/443; the task security group should allow traffic only from the ALB security group.

Module 0 · Warm-up and AWS setup (complete before class)

Quick local review; set up the CLI, identity, Region, variables and network for the cloud
Before class ≈ 15 minAWS account required
Prerequisites
  • You have completed Lessons 1 and 2, and have ~/myapp (Flask + gunicorn + Redis, listening on 5000, serving /healthz) on an Ubuntu VM (or any Linux/macOS machine).
  • You have an AWS account (ideally a dedicated sandbox account in AWS Organizations) that you can sign in to through IAM Identity Center. The permission set must at least be able to manage ECR, ECS, EC2 (VPC/security groups/ELB), IAM roles (create ECS roles and iam:PassRole), Secrets Manager, ElastiCache, CloudWatch Logs and Application Auto Scaling. In a learning account the simplest option is the AdministratorAccess permission set; in production, use least privilege.
  • Docker works locally; to build ARM64 images you need the Buildx + QEMU setup from Lesson 2.

Warm-up: answer from memory

What does exit code 137 mean?

The process was terminated by SIGKILL, most often because it exceeded its memory limit and was OOM-killed; it can also be a forced kill after a stop timeout (PID 1 doesn't handle SIGTERM). The same applies on ECS: when ECS stops a task, it first sends SIGTERM, waits for stopTimeout (30 seconds by default on Fargate), then sends SIGKILL.

Why not use latest in production?

latest gets overwritten, so you can't trace or roll back. In this lesson the ECR repository is set to IMMUTABLE, so pushing a duplicate tag fails immediately with ImageTagAlreadyExistsException.

What happens if the container listens only on 127.0.0.1?

Neither port mappings nor load balancers can reach it. gunicorn must listen on 0.0.0.0:5000; on Fargate (awsvpc mode), the ALB connects directly to the private IP of the task's ENI.

1. Install AWS CLI v2

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install            # add --update if already installed
aws --version                 # aws-cli/2.x.x …

On ARM64 Linux, use the file name awscli-exe-linux-aarch64.zip; on macOS/Windows, use the official installer. Don't use pip install awscli (that's v1). ECS Exec in Module 6 also needs the Session Manager plugin; see "AWS Systems Manager User Guide → Install the Session Manager plugin for the AWS CLI".

2. Sign in with an IAM Identity Center (SSO) profile

aws configure sso
# SSO session name (Recommended): my-sso
# SSO start URL [None]: https://<your-portal>.awsapps.com/start
# SSO region [None]: <Region where Identity Center lives>
# SSO registration scopes [sso:account:access]: press Enter
#   → authorize in the browser, choose the account and permission set
# Default client Region [None]: ca-central-1
# CLI default output format [None]: json
# Profile name [...]: docker-lab

aws sso login --profile docker-lab          # sign in again after the token expires
aws sts get-caller-identity --profile docker-lab
{
    "UserId": "AROA…:alice@example.com",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_AdministratorAccess_…/alice@example.com"
}
Don't use the root user, and don't create long-term access keysIf the Arn contains :root, you're using the root user. Sign out immediately and switch to Identity Center. An SSO profile gets temporary credentials; when they expire, just refresh them with aws sso login.

3. Region and variables file (reload in every new terminal)

Matching canadacentral in Lesson 3, this lesson uses ca-central-1 (Canada Central) by default. Variables go in ~/hour4-aws.env, kept separate from Lesson 5's variables file ~/hour5.env.

export AWS_PROFILE=docker-lab AWS_REGION=ca-central-1
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
cat > ~/hour4-aws.env <<EOF
export AWS_PROFILE=docker-lab
export AWS_REGION=ca-central-1
export AWS_DEFAULT_REGION=ca-central-1
export ACCOUNT_ID=${ACCOUNT_ID}
export REPO=myapp
export ECR=${ACCOUNT_ID}.dkr.ecr.ca-central-1.amazonaws.com
export CLUSTER=ecs-docker-lab
export SVC=myapp
export FAMILY=myapp
export LOG_GROUP=/ecs/myapp
export TAG_KV="Key=course,Value=docker-hour4"
EOF
source ~/hour4-aws.env; cat ~/hour4-aws.env

AWS has no "resource groups" in the Azure sense, so this lesson tags every resource with course=docker-hour4. During cleanup you can find anything left over with aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=docker-hour4.

4. Network: default VPC or a new VPC?

OptionHowProsCons / risks
Default VPC + public subnets (this lesson's labs)Tasks use assignPublicIp=ENABLED and reach ECR, CloudWatch and Secrets Manager directly through the internet gateway; the task security group allows only port 5000 from the ALB security groupNo extra cost; you can start in minutesTasks have public IPs (although the security group blocks inbound traffic), which doesn't meet most production security baselines
New VPC: private subnets + NAT gatewayALB in public subnets, tasks in private subnets, outbound traffic through NATCommon production topologyNAT gateways are billed per hour plus per GB processed, a common "hidden" source of lab bills
New VPC: private subnets + VPC endpointsCreate endpoints for ECR (ecr.api, ecr.dkr), an S3 gateway endpoint (image layers are stored in S3), CloudWatch Logs, Secrets Manager, etc.Traffic stays on the AWS network; no NAT neededInterface endpoints are billed per hour × Availability Zone; missing even one causes CannotPullContainerError / ResourceInitializationError (Module 6)
source ~/hour4-aws.env
VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true --query 'Vpcs[0].VpcId' --output text)
SUBNETS=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID Name=default-for-az,Values=true \
  --query 'Subnets[].SubnetId' --output text | tr '\t' ',')
echo "export VPC_ID=$VPC_ID" >> ~/hour4-aws.env
echo "export SUBNETS=$SUBNETS" >> ~/hour4-aws.env
echo $VPC_ID $SUBNETS

If the default VPC has been deleted from your account, recreate it with aws ec2 create-default-vpc, or use the "VPC and more" wizard in the VPC console to create a VPC spanning two Availability Zones.

5. Cost estimate and required permissions

StepBilled resourcesEstimate (refer to official pricing pages)Required permissions (examples)
Module 2ECR storage, Inspector enhanced scanning (optional)A few hundred MB of images costs a few cents; enhanced scanning is billed per image scanned, with a 30-day free trial (check the official terms)ecr:*, inspector2:Enable
Module 3Fargate tasks (vCPU/GB per second), ALB (per hour + LCU), CloudWatch logs2 tasks at 0.5 vCPU/1 GB + 1 ALB: roughly a few cents to a little over ten cents per hourecs:*, elasticloadbalancing:*, ec2:*SecurityGroup*, iam:CreateRole, iam:PassRole, logs:CreateLogGroup
Module 4Secrets Manager (per secret per month + API calls), ElastiCache Serverless (per GB-hour of data stored + ECPUs)A secret costs under 1 USD per month (prorated daily); Serverless has a minimum billed storage amount that accrues hourlysecretsmanager:*, elasticache:*
Module 5Task count doubles during blue/green deployments; scale-out during the load testTask count ×2 for a short timeapplication-autoscaling:*, cloudwatch:PutMetricAlarm
Module 7 (optional)EKS control plane (hourly) + Auto Mode nodes (EC2 + Auto Mode management fee)About 0.10 USD per cluster per hour for the control plane during standard support (refer to the EKS pricing page) + nodeseks:*, iam:*, ec2:*, cloudformation:* (eksctl uses CloudFormation)
TipBefore starting the labs, create a 10 USD AWS Budgets alert in the Billing console.

Module 1 · Choosing a Container Service on AWS and the ECS Object Model

00:00 – 05:00 · The same image can run on six AWS services - which one should you pick?
5 minAmazon ECS · AWS FargateApp Runner no longer accepts new customers
Learning objectives
  • Explain the differences and use cases of EC2 + Docker, ECS on Fargate, ECS on EC2, EKS, App Runner, and Lambda container images.
  • Understand the ECS object model: cluster → service → task (described by a task definition revision) → container.
  • Know the current status of App Runner and its officially recommended replacement, ECS Express Mode.

What: six ways to run containers on AWS

ServiceWhat you manageScalingGood forNot good for
EC2 + Docker/ComposeOS, patching, Docker, high availability, load balancingManual or EC2 Auto Scaling groupLegacy apps, full host control, small single-host toolsServices that need elasticity and rolling releases
ECS on Fargate ⭐Image, task definition, networking (VPC/subnets/security groups), load balancerApplication Auto Scaling (target tracking/step/scheduled)Web/API, background workers, scheduled jobs; teams that don't want to manage serversGPUs (check the official docs), privileged containers, DaemonSet-style host agents
ECS on EC2 (incl. ECS Managed Instances)Additionally capacity providers and instance types (AWS patches Managed Instances)Service scaling + capacity provider scalingSpecific instance types/GPUs, cost-sensitive large steady workloadsSimple apps run by small teams
Amazon EKSKubernetes manifests, add-ons, upgrades (Auto Mode manages nodes and core add-ons)HPA / Karpenter / Auto ModeKubernetes API, CRDs, Operators, multi-cloud consistencySmall teams with just a few simple APIs
AWS App RunnerAlmost nothingAutomatic, by concurrencyExisting customers onlyNew projects: no new customers accepted since 2026-04-30
Lambda (container image)Function code packaged as an image (must implement the Lambda Runtime API)Automatic per request, down to 0Event-driven, short-lived processing (max 15 minutes per invocation)Long-lived connections, always-on processes (a gunicorn service like myapp needs rework)
App Runner status (verified)Per the official AWS documentation "AWS App Runner availability change": App Runner no longer accepts new customers as of 2026-04-30. Existing customers can continue to use it normally (including creating new services), and AWS continues to invest in security and availability, but has no plans to release new features. AWS recommends Amazon ECS Express Mode for new projects and migrations. For this reason, this lesson does not treat App Runner as an option.

Why: the ECS object model

  • Cluster: a logical grouping of tasks and services; a Fargate cluster itself is free and has no nodes to manage.
  • Task definition: a JSON blueprint - image, CPU/memory, ports, environment variables, secrets, logging, health check, and two IAM roles. Each registration creates a new revision number (myapp:1, myapp:2…); old revisions are immutable, similar to revisions in ACA.
  • Task: a running instance of a task definition. It can contain multiple containers (main container + sidecars) that share a network namespace (with awsvpc they share one ENI and can reach each other via localhost).
  • Service: maintains the desired number of tasks (desiredCount); replaces failed tasks, performs rolling/blue/green deployments, registers tasks with load balancer target groups, and works with Auto Scaling.
  • Capacity provider: where tasks run - FARGATE, FARGATE_SPOT, or an EC2 Auto Scaling group / Managed Instances.

How: what ECS Express Mode is

ECS Express Mode requires only three things: a container image, a task execution role, and an infrastructure role. A single aws ecs create-express-gateway-service call creates a Fargate service in your account, an ALB with TLS (multiple Express services can share an ALB), auto scaling, logging, and networking, and returns a unique URL. Express Mode itself has no additional charge; you pay only for the underlying resources. It offers "App Runner-style simplicity", but every resource is a regular ECS/ELB resource, so you can take over the details at any time.

When: why this lesson builds everything by hand

To understand each layer (roles, networking, target groups, health checks, deployment configuration), this lesson creates everything step by step with the CLI. Once you have mastered it, day-to-day you can do it in one step with Express Mode, CloudFormation/CDK, or Terraform.

VPC (default VPC, ca-central-1, subnets in 2+ AZs) ALBListener :80 → rulesg-alb: 80 from 0.0.0.0/0 Target grouptype=ip :5000Health /healthz Cluster ecs-docker-lab · service myapp (desired=2) Task #1 (Fargate)ENI 172.31.x.xContainer web :5000sg-task: 5000 from sg-alb only Task #2 (other AZ)ENI 172.31.y.yTask def myapp:3 ECR: myapp:1.1 (immutable) Secrets Manager / SSM ElastiCache Serverless CloudWatch Logs (awslogs) Application Auto Scaling Two IAM rolesExecution role: agent pulls image, secrets, logsTask role: your code calls AWS APIs (incl. Exec)
Figure 1-1 ALB → target group (ip) → service → tasks (one ENI per task), depending on ECR, secrets, cache, and logs

Service selection wizard

CommandDescription
aws sts get-caller-identityConfirm the current identity and account (should not be root)
aws configure list / aws configure get regionShow the active profile and Region
aws ecs list-clustersList clusters
aws ecs create-cluster --cluster-name $CLUSTERCreate a cluster (a Fargate cluster itself is free)
aws ecs list-services --cluster $CLUSTER / list-tasksList services / tasks
aws ecs create-express-gateway-service --primary-container image=… --execution-role-arn … --infrastructure-role-arn …Express Mode creates a complete application stack in one call (for awareness only)
aws ecs put-account-setting --name containerInsights --value enhancedTurn on Container Insights by default for new clusters (enhanced observability, billed separately; check the official docs for valid values)

Lab 1: Confirm identity, Region, and cluster (about 2 minutes)

source ~/hour4-aws.env
aws sts get-caller-identity --query Arn --output text
aws configure get region
aws ecs create-cluster --cluster-name $CLUSTER --tags key=course,value=docker-hour4 \
  --query 'cluster.[clusterName,status]' --output text
aws ecs describe-clusters --clusters $CLUSTER --query 'clusters[0].status' --output text
arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_AdministratorAccess_…/alice@example.com
ca-central-1
ecs-docker-lab  ACTIVE
ACTIVE

Note that ECS --tags uses lowercase key/value, while most other services such as ECR and EC2 use Key/Value - a common AWS CLI pitfall. The first time you use ECS in an account, the service-linked role AWSServiceRoleForECS is created automatically.

Case: migrating from EC2 + Compose to ECS Fargate

A team ran 12 internal APIs on 4 EC2 instances managed with Compose, and spent a lot of time every month patching, expanding disks, and releasing by hand. After migrating to ECS Fargate: one service per API, all sharing one ALB (listener rules by host name/path); the deployment circuit breaker automatically rolls back bad versions; and Auto Scaling reduces the task count to the minimum at night. Only one inference service that needs a GPU runs on ECS on EC2 (with a GPU-instance capacity provider).

Lesson learned the hard way: EKS for a single API

A 3-person team built an EKS cluster for a single API and ended up spending most of their time on add-on versions, node AMI upgrades, Ingress, and IAM role mappings - while also paying hourly for the control plane. Lesson: start with the simplest managed service (ECS Fargate or Express Mode), and move to EKS only when you clearly need Kubernetes capabilities.

Case: migrating App Runner users

Teams with existing App Runner services are not affected, but will get no new features. The approach in the official migration guide: create an ECS Express Mode service from the same image, then use Route 53 weighted routing to gradually shift traffic from App Runner to the new service (blue/green + DNS weights).

Unable to locate credentials / The SSO session associated with this profile has expired

AWS_PROFILE is not set, or the SSO token has expired: source ~/hour4-aws.env && aws sso login.

You must specify a region

The profile has no default Region: set AWS_REGION / AWS_DEFAULT_REGION, or add --region ca-central-1 to the command.

AccessDeniedException … is not authorized to perform: ecs:CreateCluster

The permission set is missing the required permission. The error message shows the denied action and resource ARN; give it to your administrator. Don't switch to the root user to save time.

Unable to assume the service linked role. Please verify that the ECS service linked role exists

On first use of ECS, the service-linked role has not been created or has not propagated yet. Wait a moment and retry, or run aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com (requires IAM permissions).

or score ≥ 70% on the "Quiz" tab

Module 2 · ECR in depth: immutable tags, scanning, lifecycle and caching

05:00 – 13:00 · Make the registry traceable, self-cleaning and independent of Docker Hub
8 minIMMUTABLE · Lifecycle policiesPull through cache · Inspector
Learning objectives
  • Create a repository with immutable tags and understand the get-login-password token (valid for 12 hours).
  • Configure registry-level scanning (basic scanning / Amazon Inspector enhanced scanning) and read the findings.
  • Clean up temporary tags with a lifecycle policy; use pull through cache and cross-Region replication to manage where images come from and where they are distributed.
  • Build images that match the Fargate architecture (X86_64 or ARM64/Graviton).

What: ECR structure and authentication

  • Each account has one private registry per Region: <account-ID>.dkr.ecr.<region>.amazonaws.com. It is organized into repositories (myapp, docker-hub/library/redis, ...), which must be created first (pull through cache and repository creation templates can create them automatically).
  • aws ecr get-login-password calls GetAuthorizationToken and returns the username AWS plus a password. Per the official docs, the token has the same permission scope as the IAM principal that requested it and is valid for 12 hours. In CI, simply fetch a new one for each job.
  • ECS does not use this command to pull images: the task execution role does it (the managed policy AmazonECSTaskExecutionRolePolicy includes ECR pull and log write permissions).

Why: tag mutability

SettingBehaviorBest for
MUTABLE (default)A tag with the same name can be overwrittenPull through cache repositories (officially recommended, so the cache can be updated)
IMMUTABLEPushing an existing tag returns ImageTagAlreadyExistsException; applies to all tags in the repositoryApplication image repositories (this lesson)
IMMUTABLE_WITH_EXCLUSION / MUTABLE_WITH_EXCLUSIONWildcard filters exempt a few tags (for example, allow latest to stay mutable)When you need one "floating" tag but want to protect release tags

Compared with Azure: ACR locks individual images with --write-enabled false; ECR uses a per-repository policy, closer to "lock everything by default".

How: scanning

TypeCoverageFrequencyNotes
Basic scanningOS package CVEsScan on push / manualAWS native technology; read findings with DescribeImageScanFindings (newer versions no longer populate imageScanStatus in DescribeImages)
Enhanced scanningOS + programming language packages (pip, npm, ...)On push / continuousIntegrates with Amazon Inspector; findings are updated and EventBridge events are sent when new vulnerabilities appear; billed at Inspector pricing

Official best practice: configure scanning at the registry level (put-registry-scanning-configuration, with filters to select repositories). The repository-level scanOnPush applies only to basic scanning. Switching between basic and enhanced scanning makes previous scan findings unavailable.

When: lifecycle policies, caching and replication

  • Lifecycle policies: JSON rules (rulePriority, selection, action) that select images by tag status/prefix/pattern, by count (imageCountMoreThan) or by age (sinceImagePushed, sinceImagePulled). The action is expire (delete) or transition to archive storage. ECR applies them server-side automatically; preview first with start-lifecycle-policy-preview.
  • Pull through cache: a rule = repository prefix + upstream URL. Docker Hub (registry-1.docker.io), GitHub, GitLab and others require credentials, stored in a Secrets Manager secret whose name starts with ecr-pullthroughcache/ (same account, same Region). ECR Public, registry.k8s.io and Quay can be used anonymously.
  • Replication: registry-level cross-Region/cross-account replication (put-replication-configuration) for multi-Region deployments or disaster recovery. Only images pushed after the configuration takes effect are replicated.
  • Multi-architecture: Fargate supports X86_64 and ARM64 (Graviton). The task definition's runtimePlatform.cpuArchitecture must match the image, or the container fails with exec format error (Module 6). Building a multi-arch manifest with docker buildx build --platform linux/amd64,linux/arm64 --push is the safest option.
Local / CIget-login-password (12h)buildx --push Docker Hub, other upstreamsCreds: ecr-pullthroughcache/* ECR private registry (ca-central-1) myapp (IMMUTABLE): 1.1 · 1.2 · sha-3f2a... Scanning: registry rules (Basic on push / Inspector continuous) Lifecycle: untagged > 1 day expire; keep 10 sha-* docker-hub/library/redis (pull through cache, auto-created) Replication rule → us-east-1 (optional) Layers live in S3 (private subnets need S3 gateway endpoint) ECS taskExecution role pulls EKS nodeNode role PullOnly

Lifecycle policy simulator

The repository holds 30 sha-* CI tags (one per day), 4 release tags 1.x and some untagged images. Adjust the two rules to see which images the expire action would remove (equivalent to start-lifecycle-policy-preview).


      
CommandDescription
aws ecr create-repository --repository-name myapp --image-tag-mutability IMMUTABLECreate a repository with immutable tags (encryption settings cannot be changed after creation)
aws ecr get-login-password | docker login --username AWS --password-stdin $ECRLog in (token valid for 12 hours)
aws ecr put-registry-scanning-configuration --scan-type BASIC --rules '[…SCAN_ON_PUSH…]'Registry-level basic scanning (on push)
aws ecr put-registry-scanning-configuration --scan-type ENHANCED --rules '[…CONTINUOUS_SCAN…]'Enable Inspector enhanced scanning
aws ecr wait image-scan-complete --repository-name myapp --image-id imageTag=1.1Wait for the scan to complete
aws ecr describe-image-scan-findings --repository-name myapp --image-id imageTag=1.1Read scan findings
aws ecr put-lifecycle-policy --repository-name myapp --lifecycle-policy-text file://lifecycle.jsonSet a lifecycle policy
aws ecr start-lifecycle-policy-preview / get-lifecycle-policy-previewPreview which images will be affected
aws ecr create-pull-through-cache-rule --ecr-repository-prefix docker-hub --upstream-registry-url registry-1.docker.io --credential-arn …Docker Hub cache rule (credentials required)
aws ecr put-replication-configuration --replication-configuration file://repl.jsonCross-Region/cross-account replication
aws ecr describe-images --repository-name myapp --query 'imageDetails[].[imageTags,imagePushedAt]'List images
docker buildx imagetools inspect $ECR/myapp:1.1Show which platforms the manifest contains

Lab 2: create a repository, push, scan, lifecycle (about 7 minutes)

Update app.py: support cloud Redis/Valkey (password + TLS) and expose /healthz (same as Lesson 3; skip if already done)
cd ~/myapp
cat > app.py <<'EOF'
import os, socket
from flask import Flask
import redis

app = Flask(__name__)
r = redis.Redis(
    host=os.getenv("REDIS_HOST", "redis"),
    port=int(os.getenv("REDIS_PORT", "6379")),
    password=os.getenv("REDIS_PASSWORD") or None,
    ssl=os.getenv("REDIS_SSL", "false").lower() == "true",
    socket_connect_timeout=1,
)
VERSION = os.getenv("APP_VERSION", "dev")

@app.route("/")
def index():
    try:
        hits = r.incr("hits")
    except redis.exceptions.RedisError:
        hits = "N/A (redis not connected)"
    return f"[{VERSION}] Hello from {socket.gethostname()}, hits={hits}\n"

@app.route("/healthz")
def healthz():
    return "ok"
EOF

/healthz does not touch Redis: the ALB health check should only decide "can this task serve traffic". Don't let a flaky dependency pull every task out of service at once.

Create an immutable repository and log in
source ~/hour4-aws.env
aws ecr create-repository --repository-name $REPO \
  --image-tag-mutability IMMUTABLE --tags $TAG_KV \
  --query 'repository.repositoryUri' --output text
aws ecr get-login-password | docker login --username AWS --password-stdin $ECR
111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp
Login Succeeded
Enable registry-level "basic scan on push", then build and push 1.1 (amd64)
aws ecr put-registry-scanning-configuration --scan-type BASIC \
  --rules '[{"repositoryFilters":[{"filter":"*","filterType":"WILDCARD"}],"scanFrequency":"SCAN_ON_PUSH"}]'
docker buildx build --platform linux/amd64 -t $ECR/$REPO:1.1 --push .
aws ecr wait image-scan-complete --repository-name $REPO --image-id imageTag=1.1
aws ecr describe-image-scan-findings --repository-name $REPO --image-id imageTag=1.1 \
  --query 'imageScanFindings.findingSeverityCounts'
{
    "MEDIUM": 3,
    "LOW": 12
}

To see vulnerabilities in Python dependencies you need enhanced scanning: --scan-type ENHANCED (this enables Amazon Inspector and is billed at its pricing; switch back to BASIC when you're done).

Verify immutable tags
echo "# rebuild" >> app.py
docker buildx build --platform linux/amd64 -t $ECR/$REPO:1.1 --push . 2>&1 | tail -2
git checkout app.py 2>/dev/null || sed -i '$d' app.py
… tag invalid: The image tag '1.1' already exists in the 'myapp' repository and cannot be overwritten because the repository is immutable.

The exact error text may differ in your output; at the API level the exception name is ImageTagAlreadyExistsException.

Lifecycle policy: clean up only temporary CI tags and untagged images
cat > lifecycle.json <<'EOF'
{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Expire untagged images older than 1 day",
      "selection": { "tagStatus": "untagged", "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 1 },
      "action": { "type": "expire" }
    },
    {
      "rulePriority": 2,
      "description": "Keep only the last 10 CI images",
      "selection": { "tagStatus": "tagged", "tagPatternList": ["sha-*"], "countType": "imageCountMoreThan", "countNumber": 10 },
      "action": { "type": "expire" }
    }
  ]
}
EOF
aws ecr put-lifecycle-policy --repository-name $REPO --lifecycle-policy-text file://lifecycle.json
aws ecr start-lifecycle-policy-preview --repository-name $REPO
aws ecr get-lifecycle-policy-preview --repository-name $REPO --query 'summary'

Release tags 1.* match no rule, so they are never cleaned up - this is the ECR version of "locking release tags".

(Optional) Docker Hub pull through cache
# Store a Docker Hub access token in Secrets Manager (the name must start with ecr-pullthroughcache/)
SECRET_ARN=$(aws secretsmanager create-secret --name ecr-pullthroughcache/docker-hub \
  --secret-string '{"username":"<Docker Hub username>","accessToken":"<Docker Hub access token>"}' \
  --query ARN --output text)
aws ecr create-pull-through-cache-rule --ecr-repository-prefix docker-hub \
  --upstream-registry-url registry-1.docker.io --credential-arn $SECRET_ARN
docker pull $ECR/docker-hub/library/python:3.13-slim     # The first pull creates the repository and caches the image automatically

For the secret's JSON field names, follow the official doc "Storing your upstream repository credentials in an AWS Secrets Manager secret". Afterwards you can point the Dockerfile's FROM at the cached path in ECR to avoid Docker Hub rate limits.

Case 1: a lifecycle rule deleted an image still in use in production

Someone wrote a tagStatus: any, sinceImagePushed: 14 rule to "tidy up" every image older than two weeks. A service that hadn't been released for two weeks then failed during task replacement with CannotPullContainerError … not found. ECR lifecycle policies do not know which images ECS is currently using. Fix: have rules match only temporary CI tags (sha-*, pr-*) and untagged images; keep release tags separately, or use sinceImagePulled + archiving instead.

Case 2: Docker Hub rate limits caused a scale-out to fail

During a peak-sale scale-out, the build pipeline and sidecar images all pulled redis and python from Docker Hub at the same time and hit toomanyrequests. Fix: create pull through cache rules, switch every FROM and sidecar image to ECR paths, and use SCP/IAM conditions to allow pulls only from the internal ECR.

Case 3: an image pushed from Apple Silicon won't start on Fargate

A developer ran docker build on an M-series Mac and pushed the result, so the image was arm64 only; the task definition defaulted to X86_64, and the task exited immediately on start (exec format error). Fix: standardize CI on buildx --platform linux/amd64,linux/arm64, or simply switch the task definition to ARM64 and enjoy Graviton's price-performance.

denied: Your authorization token has expired. Reauthenticate and try again.

The login token is older than 12 hours. Rerun aws ecr get-login-password | docker login …; in CI, fetch one at the start of every job.

name unknown: The repository with name 'myapp' does not exist in the registry

ECR does not create repositories on push (unless a repository creation template is configured or pull through cache is used). Run create-repository first, and check that the Region and account ID match.

ImageTagAlreadyExistsException / tag invalid … cannot be overwritten

The repository is IMMUTABLE. This is expected behavior: use a new tag (such as 1.1.1 or sha-<commit>).

no basic auth credentials

You haven't logged in, or the registry you logged in to differs from the one you're pushing to (for example, a different Region).

Pull through cache rule created, but pulls fail

The secret name doesn't start with ecr-pullthroughcache/, the secret is in a different Region, the fields are wrong, or the Docker Hub token has expired. Check with aws ecr validate-pull-through-cache-rule --ecr-repository-prefix docker-hub (see the CLI reference for details).

or score ≥ 70% on the Quiz

Module 3 · Deploying to Amazon ECS on AWS Fargate ⭐

13:00 – 24:00 · Two IAM roles, awsvpc networking, valid CPU/memory combinations, ALB and health checks
11 minregister-task-definition · create-serviceKey topic
Learning objectives
  • Explain how clusters, task definitions, services and tasks relate; distinguish the task execution role from the task role.
  • Use a security group chain (ALB SG → task SG) for minimal exposure; create an ALB, a target group (target type ip) and a listener.
  • Choose a valid Fargate CPU/memory combination, write a task definition, deploy with create-service and run wait services-stable.
  • Understand how the container healthCheck and the ALB health check differ and work together.

What: resources a deployment needs

ResourcePurposeCommand
Task execution roleLets the ECS/Fargate agent call AWS on your behalf: pull images from ECR, write CloudWatch Logs, fetch secrets from Secrets Manager/SSM (trusted principal ecs-tasks.amazonaws.com)aws iam create-role + AmazonECSTaskExecutionRolePolicy
Task roleUsed when your code in the container calls AWS APIs (e.g. reading S3); ECS Exec requires it to have ssmmessages:*Channel permissionsaws iam create-role + inline policy
Security groups ×2sg-alb: port 80 from 0.0.0.0/0; sg-task: port 5000 only from sg-albaws ec2 create-security-group
ALB + target group + listenerThe target group's target type must be ip (with awsvpc, each task gets its own IP); health check /healthzaws elbv2 …
Log groupWritten to by the awslogs driver; the execution role's managed policy only includes CreateLogStream/PutLogEvents, so the log group must be created in advanceaws logs create-log-group
Task definitionImage, CPU/memory, ports, environment, logging, health check, both roles, runtimePlatformaws ecs register-task-definition
ServiceDesired task count, networking, load balancer, deployment configuration, ECS Execaws ecs create-service

Why: why two roles

The execution role holds "the permissions the platform needs to start your container"; the task role holds "the permissions your application needs at runtime". Keeping them separate means your application code can't pull every image or read every secret. The most common mistake is adding secretsmanager:GetSecretValue to the task role and still getting ResourceInitializationError, because secrets are fetched by the execution role.

How: awsvpc networking and Fargate sizes

  • Fargate tasks always use the awsvpc network mode: each task gets an ENI and a private VPC IP, and security groups apply directly to the task. Containers in the same task share that ENI (they can reach each other on localhost).
  • There is no "host port" in the port mapping: containerPort is the exposed port, and the ALB connects directly to taskIP:5000.
  • CPU/memory are specified at the task level and must be a valid combination (official table):
CPUMemory
256 (.25 vCPU)512 MiB, 1 GB, 2 GB
512 (.5 vCPU)1–4 GB (1 GB increments)
1024 (1 vCPU)2–8 GB (1 GB increments)
2048 (2 vCPU)4–16 GB (1 GB increments)
4096 (4 vCPU)8–30 GB (1 GB increments)
8192 (8 vCPU)*16–60 GB (4 GB increments)
16384 (16 vCPU)*32–120 GB (8 GB increments)
32768 (32 vCPU)*60 GB, 120 GB, 244 GB

* Requires Linux platform version 1.4.0 or later; 8/16/32 vCPU are Linux only. Windows containers need at least 1 vCPU. Compared with ACA: ACA uses a fixed 1:2 ratio, while Fargate lets you mix values freely within a range.

When: two kinds of health checks

Container healthCheck (task definition)ALB target group health check
Who runs itThe container runtime runs a command inside the container (like Docker HEALTHCHECK, but ECS does not read HEALTHCHECK from the image; you must define it in the task definition)The ALB sends HTTP requests from outside to taskIP:5000/healthz
On failureEssential container UNHEALTHY → the service scheduler replaces the taskTarget unhealthy → no more traffic is routed to it, and the service scheduler replaces the task
Defaultsinterval 30s, timeout 5s, retries 3, startPeriod configurableSet by the target group (this lesson: 15s interval, healthy threshold 2)
NotesThe command depends on tools in the image (python:slim has no curl, so use python to send the request)The service's healthCheckGracePeriodSeconds ignores ELB health check failures during startup

Both are taken into account by "stage 2" of the deployment circuit breaker (Module 5).

Userhttp://ALB-DNS ALB (sg-alb)Listener :80 → rule→ target group ip:5000 Fargate task (sg-task)ENI private IP · gunicorn 0.0.0.0:5000512 CPU / 1024 MiB · X86_64healthCheck: python urlopen /healthzawslogs → /ecs/myapp Task execution roleECR pull · logs · secrets ECR myapp:1.1 Task roleApp calls AWS · ECS Exec ALB health check: GET /healthz every 15s, 2 x 200 in a row → healthy sg-task inbound: TCP 5000, source = sg-alb (not 0.0.0.0/0)

Animation: what happens after create-service

Fargate CPU / memory combination validator

CommandDescription
aws iam create-role --role-name myappTaskExecutionRole --assume-role-policy-document file://ecs-tasks-trust.jsonCreate the execution role (trusts ecs-tasks.amazonaws.com)
aws iam attach-role-policy --role-name … --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicyAttach the managed policy
aws ec2 authorize-security-group-ingress --group-id $TASK_SG --protocol tcp --port 5000 --source-group $ALB_SGSecurity group chain: only the ALB can reach the tasks
aws elbv2 create-target-group … --target-type ip --health-check-path /healthzTarget group (Fargate requires ip)
aws ecs register-task-definition --cli-input-json file://taskdef.jsonRegister a task definition (creates a new revision)
aws ecs create-service … --load-balancers targetGroupArn=…,containerName=web,containerPort=5000Create the service and attach it to the target group
aws ecs wait services-stable --cluster $CLUSTER --services $SVCWait for the service to stabilize (polls; returns non-zero on timeout)
aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].events[:5]'Service events (first stop for troubleshooting)
aws elbv2 describe-target-health --target-group-arn $TG_BLUETarget health state and reason
aws ecs update-service --cluster $CLUSTER --service $SVC --task-definition myapp:3Switch to a new task definition revision (triggers a deployment)
aws ecs update-service … --desired-count 3Manual scaling

Lab 3: deploy myapp to Fargate + ALB (about 10 minutes)

Cost and riskFrom this step on, the ALB (hourly + LCU) and Fargate tasks (per vCPU/GB-second) start incurring charges. Open port 80 to 0.0.0.0/0 only on the ALB; the task security group accepts traffic only from the ALB security group. Requires iam:CreateRole, iam:PassRole, elasticloadbalancing:*, ec2:*SecurityGroup*, ecs:*, logs:*.
Two IAM roles
source ~/hour4-aws.env
cat > ecs-tasks-trust.json <<'EOF'
{ "Version": "2012-10-17",
  "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ecs-tasks.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
EOF
aws iam create-role --role-name myappTaskExecutionRole --assume-role-policy-document file://ecs-tasks-trust.json --tags $TAG_KV --query Role.Arn --output text
aws iam attach-role-policy --role-name myappTaskExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam create-role --role-name myappTaskRole --assume-role-policy-document file://ecs-tasks-trust.json --tags $TAG_KV --query Role.Arn --output text
aws iam put-role-policy --role-name myappTaskRole --policy-name ecs-exec --policy-document '{
  "Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":[
  "ssmmessages:CreateControlChannel","ssmmessages:CreateDataChannel",
  "ssmmessages:OpenControlChannel","ssmmessages:OpenDataChannel"],"Resource":"*"}]}'
cat >> ~/hour4-aws.env <<EOF
export EXEC_ROLE_ARN=arn:aws:iam::${ACCOUNT_ID}:role/myappTaskExecutionRole
export TASK_ROLE_ARN=arn:aws:iam::${ACCOUNT_ID}:role/myappTaskRole
EOF

In production, add aws:SourceAccount / aws:SourceArn conditions to the trust policy to prevent the "confused deputy" problem (see the official IAM and ECS documentation).

Security group chain
source ~/hour4-aws.env
ALB_SG=$(aws ec2 create-security-group --group-name sg-myapp-alb --description "myapp ALB" --vpc-id $VPC_ID --query GroupId --output text)
TASK_SG=$(aws ec2 create-security-group --group-name sg-myapp-task --description "myapp tasks" --vpc-id $VPC_ID --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id $ALB_SG --protocol tcp --port 80 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id $TASK_SG --protocol tcp --port 5000 --source-group $ALB_SG
aws ec2 create-tags --resources $ALB_SG $TASK_SG --tags $TAG_KV
printf 'export ALB_SG=%s\nexport TASK_SG=%s\n' $ALB_SG $TASK_SG >> ~/hour4-aws.env
ALB, target group (ip), listener and a forwarding rule
source ~/hour4-aws.env
ALB_ARN=$(aws elbv2 create-load-balancer --name alb-myapp --type application --scheme internet-facing \
  --security-groups $ALB_SG --subnets $(echo $SUBNETS | tr ',' ' ') --tags $TAG_KV \
  --query 'LoadBalancers[0].LoadBalancerArn' --output text)
TG_BLUE=$(aws elbv2 create-target-group --name tg-myapp-blue --protocol HTTP --port 5000 \
  --vpc-id $VPC_ID --target-type ip --health-check-path /healthz --matcher HttpCode=200 \
  --health-check-interval-seconds 15 --healthy-threshold-count 2 --unhealthy-threshold-count 3 \
  --query 'TargetGroups[0].TargetGroupArn' --output text)
aws elbv2 modify-target-group-attributes --target-group-arn $TG_BLUE \
  --attributes Key=deregistration_delay.timeout_seconds,Value=30
LISTENER=$(aws elbv2 create-listener --load-balancer-arn $ALB_ARN --protocol HTTP --port 80 \
  --default-actions Type=fixed-response,FixedResponseConfig='{StatusCode=404,ContentType=text/plain,MessageBody=no-route}' \
  --query 'Listeners[0].ListenerArn' --output text)
PROD_RULE=$(aws elbv2 create-rule --listener-arn $LISTENER --priority 10 \
  --conditions Field=path-pattern,Values='/*' \
  --actions Type=forward,TargetGroupArn=$TG_BLUE --query 'Rules[0].RuleArn' --output text)
ALB_DNS=$(aws elbv2 describe-load-balancers --load-balancer-arns $ALB_ARN --query 'LoadBalancers[0].DNSName' --output text)
printf 'export ALB_ARN=%s\nexport TG_BLUE=%s\nexport LISTENER=%s\nexport PROD_RULE=%s\nexport ALB_DNS=%s\n' \
  $ALB_ARN $TG_BLUE $LISTENER $PROD_RULE $ALB_DNS >> ~/hour4-aws.env

Why use a "rule" instead of the listener's default action? ECS native blue/green deployment in Module 5 requires a production listener rule ARN (productionListenerRule), and ECS shifts traffic by changing the weights on this rule. In production, also add a 443 listener (ACM certificate) and redirect 80 to 443.

Log group and task definition
source ~/hour4-aws.env
aws logs create-log-group --log-group-name $LOG_GROUP --tags course=docker-hour4
aws logs put-retention-policy --log-group-name $LOG_GROUP --retention-in-days 7
cat > taskdef.json <<EOF
{
  "family": "${FAMILY}",
  "requiresCompatibilities": ["FARGATE"],
  "networkMode": "awsvpc",
  "cpu": "512",
  "memory": "1024",
  "runtimePlatform": { "cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX" },
  "executionRoleArn": "${EXEC_ROLE_ARN}",
  "taskRoleArn": "${TASK_ROLE_ARN}",
  "containerDefinitions": [
    {
      "name": "web",
      "image": "${ECR}/${REPO}:1.1",
      "essential": true,
      "portMappings": [ { "containerPort": 5000, "protocol": "tcp" } ],
      "environment": [ { "name": "APP_VERSION", "value": "1.1" } ],
      "linuxParameters": { "initProcessEnabled": true },
      "healthCheck": {
        "command": ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz', timeout=3)\" || exit 1"],
        "interval": 15, "timeout": 5, "retries": 3, "startPeriod": 20
      },
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "${LOG_GROUP}",
          "awslogs-region": "${AWS_REGION}",
          "awslogs-stream-prefix": "myapp"
        }
      }
    }
  ]
}
EOF
aws ecs register-task-definition --cli-input-json file://taskdef.json \
  --query 'taskDefinition.[family,revision,status]' --output text
myapp   1   ACTIVE

initProcessEnabled ensures child processes started by ECS Exec are properly reaped (recommended by AWS). Log stream names have the format myapp/web/<task-id>.

Create the service and wait for it to stabilize
aws ecs create-service --cluster $CLUSTER --service-name $SVC \
  --task-definition $FAMILY --desired-count 2 --launch-type FARGATE --platform-version LATEST \
  --network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$TASK_SG],assignPublicIp=ENABLED}" \
  --load-balancers "targetGroupArn=$TG_BLUE,containerName=web,containerPort=5000" \
  --health-check-grace-period-seconds 30 \
  --deployment-configuration "minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}" \
  --enable-execute-command --propagate-tags SERVICE --tags key=course,value=docker-hour4 \
  --query 'service.[serviceName,status,desiredCount]' --output text
time aws ecs wait services-stable --cluster $CLUSTER --services $SVC
aws elbv2 describe-target-health --target-group-arn $TG_BLUE \
  --query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State]' --output text
curl -s http://$ALB_DNS/; curl -s http://$ALB_DNS/healthz; echo
myapp   ACTIVE  2
real    2m31s
172.31.5.23     healthy
172.31.40.181   healthy
[1.1] Hello from ip-172-31-5-23.ca-central-1.compute.internal, hits=N/A (redis not connected)
ok

On Fargate, the hostname is usually the task's internal hostname (your actual output may differ). There is no Redis yet, so N/A is expected (fixed in Module 4).

Take a look at service events and logs
aws ecs describe-services --cluster $CLUSTER --services $SVC \
  --query 'services[0].[deployments[0].rolloutState, events[0].message]' --output text
aws logs tail $LOG_GROUP --since 10m | tail -5
COMPLETED   (service myapp) has reached a steady state.
… [INFO] Listening at: http://0.0.0.0:5000 (1)

Case 1: tasks "keep restarting" because the health check is too strict

A Java service takes 70 seconds to start. The target group health check had a 10-second interval and an unhealthy threshold of 2, and the service had no healthCheckGracePeriodSeconds. As a result, tasks were marked unhealthy and replaced before they finished starting, over and over. Fix: a 120-second grace period, startPeriod on the container healthCheck, and a health endpoint that checks only the service itself.

Case 2: a permissions incident

To "keep things simple", a team had all services share one task role with AdministratorAccess attached. One service had an SSRF vulnerability, and an attacker obtained temporary credentials through the task metadata endpoint. Improvements: a separate least-privilege task role per service; separate execution and task roles; IAM condition keys on ECS Exec to restrict who can get into production containers.

Case 3: public IPs vs. NAT

During the lab phase, tasks ran in public subnets with public IPs; the security team rejected this at the go-live review. Final design: tasks in private subnets with VPC endpoints for ECR (api/dkr), S3 (gateway), Logs and Secrets Manager, and NAT used only by the few services that need to call third-party APIs. Monthly NAT data processing charges dropped noticeably.

ClientException: Invalid 'cpu' setting for task / No Fargate configuration exists for given values

The CPU/memory values are not a valid combination (e.g. 256 + 4096). Check the combination table or use the validator on the "Animation" tab.

InvalidParameterException: The target group … does not have an associated load balancer

The target group isn't referenced by any listener or rule yet. Create the listener rule before creating the service.

InvalidParameterException: The provided target group … has target type instance, which is incompatible with the awsvpc network mode

Fargate requires a target group with --target-type ip. The target type can't be changed after creation; you have to recreate the target group.

AccessDeniedException … iam:PassRole

Registering a task definition or creating a service "passes" the execution role and task role to ECS. Your identity needs iam:PassRole permission on both roles.

wait services-stable: Waiter ServicesStable failed: Max attempts exceeded

The wait timed out (about 10 minutes). Check the events from describe-services, the Reason from describe-target-health, and the stoppedReason of stopped tasks (Module 6).

The ALB returns 502 / 504

502: the target refused the connection (the app listens only on 127.0.0.1, wrong port, or the container just exited). 504: no network path. Most commonly, the task security group doesn't allow port 5000 from the ALB security group.

or score ≥ 70% on the "Quiz"

Module 4 · Configuration, Secrets and Caching (ElastiCache Serverless · Valkey)

24:00 – 32:00 · Keep secrets in Secrets Manager / Parameter Store and only references in the task definition; hand state to a managed cache
8 minenvironment · secrets.valueFromElastiCache Serverless (Valkey) · TLS
Learning objectives
  • Distinguish the task definition's environment, environmentFiles and secrets, and when each takes effect.
  • Grant the task execution role least-privilege access to read specific secrets; know that a forced new deployment is required after a secret is updated.
  • Create an ElastiCache Serverless (Valkey) cache, configure an RBAC user group, TLS and security groups, and get the myapp counter working.

What: three sources of configuration

SourceTask definition syntaxWhere the value livesAfter a change
Plain environment variables"environment": [{"name":"APP_VERSION","value":"1.2"}]The task definition itself (plaintext, visible via describe-task-definition)You must register a new revision and update the service
Environment files"environmentFiles": [{"value":"arn:aws:s3:::bucket/app.env","type":"s3"}]An S3 objectRead at task startup; new tasks are needed after the file changes
Secrets"secrets": [{"name":"REDIS_PASSWORD","valueFrom":"<ARN>"}]Secrets Manager or SSM Parameter Store (SecureString/String)Injected only when the container starts; after an update or rotation, running containers do not pick up the new value automatically - run update-service --force-new-deployment

From the official docs: "If the secret is subsequently updated or rotated, the container will not receive the updated value automatically. You must either launch a new task or … use the Force new deployment option." Compare with Azure: an unversioned Key Vault reference is refreshed automatically within 30 minutes and the revision is restarted; ECS does not do this.

Why: valueFrom formats

TargetvalueFrom examplePlatform requirement
An entire Secrets Manager secretarn:aws:secretsmanager:ca-central-1:111122223333:secret:myapp/redis-AbCdEfFargate platform 1.3.0+
A specific key in a Secrets Manager JSON secret / a specific versionarn:…:secret:myapp/db-AbCdEf:password:: (format secret-arn:json-key:version-stage:version-id; omitted fields keep their colons)Fargate Linux platform 1.4.0+
SSM parameter (same Region)arn:aws:ssm:ca-central-1:111122223333:parameter/myapp/feature-flag (in the same Region, the name alone also works)-

Permissions the task execution role needs: secretsmanager:GetSecretValue (Secrets Manager), ssm:GetParameters (Parameter Store), plus kms:Decrypt when a customer managed KMS key is used. Set Resource to specific ARNs, not *.

Inside the container, a secret is still an environment variableThe application, logs and debugging tools can all see it. Don't print the environment in startup logs; wherever IAM works (for example, accessing S3 or DynamoDB), use the task role directly instead of handing out passwords.

How: where to put the cache

OptionDescriptionBest for
A redis sidecar in the same taskWith awsvpc, containers in the same task share localhost; but each task has its own copy of the data, so counts are not shared across tasks and are lost when a task is replacedOnly for demonstrating "why state must live outside the container"
ElastiCache Serverless (Valkey)No node sizing; scales automatically; encryption in transit is always on and cannot be disabled; primary endpoint on port 6379, reader endpoint on 6380 (same hostname); access control only through RBAC user groups; deployed in a VPC by default (a public endpoint connection type is also supported - check the official docs)This lesson's lab and small to medium production workloads
Self-designed ElastiCache cluster (node-based)Choose node types and shards; reserved nodes can lower costLarge, predictable workloads

When: what the application needs to do

  • Enable TLS: REDIS_SSL=true (the app.py from Module 2 already supports it).
  • Authentication: a Valkey user group can contain a user whose user name is default; when redis-py passes only password, it AUTHs as the default user, so app.py needs no changes.
  • Security groups: the cache's security group must allow 6379 and 6380 from sg-task - some clients connect to both ports every time, so allowing only 6379 can cause connection timeouts.
  • Cluster mode: to clients, Serverless appears as a cluster-mode-enabled endpoint; single-key commands (this lesson's INCR hits) generally work; multi-key cross-slot commands fail with CROSSSLOT, so a cluster-mode-aware client is recommended (check the official docs).
Secrets Managermyapp/redis-password SSM Parameter Store/myapp/banner Task execution roleGetSecretValue · GetParameters (ARNs) Task def myapp:2 → at task start ① Agent fetches secrets via exec role ② Injected as env vars into web environment: REDIS_HOST=myapp-cache-….cache.amazonaws.com REDIS_PORT=6379 · REDIS_SSL=true secrets: REDIS_PASSWORD ← Secrets Manager ARN secrets: BANNER ← SSM parameter ARN Later secret changes → running containers unchanged ElastiCache ServerlessValkey · TLS always on6379 primary / 6380 readRBAC user group myapp-ugsg-cache ← sg-task

Simulator: after a change, when do the containers in the two tasks see the new value?

CommandDescription
aws secretsmanager create-secret --name myapp/redis-password --secret-string "$PW"Create a secret (each secret is billed monthly)
aws secretsmanager put-secret-value --secret-id myapp/redis-password --secret-string "$NEW"Write a new version (AWSCURRENT points to the new value)
aws ssm put-parameter --name /myapp/banner --type String --value "hello"Parameter Store parameter (standard parameters are free)
aws iam put-role-policy --role-name myappTaskExecutionRole --policy-name read-myapp-secrets …Let the task execution role read specific secrets
aws ecs update-service --cluster $CLUSTER --service $SVC --force-new-deploymentStart new tasks with the same task definition so secrets are read again
aws elasticache create-user --user-id myapp-default --user-name default --engine VALKEY --passwords "$PW" --access-string "on ~* +@all"RBAC user
aws elasticache create-user-group --user-group-id myapp-ug --engine VALKEY --user-ids myapp-defaultUser group
aws elasticache create-serverless-cache --serverless-cache-name myapp-cache --engine valkey --user-group-id myapp-ug …Create a Serverless cache
aws elasticache describe-serverless-caches --serverless-cache-name myapp-cacheStatus (creating → available) and endpoints

Lab 4: Secrets Manager + SSM + ElastiCache Serverless (about 8 minutes; creating the cache takes a few minutes)

Cost and riskElastiCache Serverless bills hourly for data stored (with a minimum metered amount) and ECPUs, even when idle; Secrets Manager bills each secret monthly (prorated daily). The cache security group must allow only 6379–6380 from sg-task; never open it to 0.0.0.0/0. Requires secretsmanager:*, ssm:PutParameter, elasticache:* and iam:PutRolePolicy.
Write the secret and parameter, and authorize the task execution role (least privilege)
source ~/hour4-aws.env
PW=$(openssl rand -hex 24)
SECRET_ARN=$(aws secretsmanager create-secret --name myapp/redis-password --secret-string "$PW" \
  --tags $TAG_KV --query ARN --output text)
aws ssm put-parameter --name /myapp/banner --type String --value "hello-from-ssm" --tags $TAG_KV
PARAM_ARN=arn:aws:ssm:${AWS_REGION}:${ACCOUNT_ID}:parameter/myapp/banner
aws iam put-role-policy --role-name myappTaskExecutionRole --policy-name read-myapp-secrets --policy-document "{
  \"Version\":\"2012-10-17\",\"Statement\":[
   {\"Effect\":\"Allow\",\"Action\":\"secretsmanager:GetSecretValue\",\"Resource\":\"$SECRET_ARN\"},
   {\"Effect\":\"Allow\",\"Action\":\"ssm:GetParameters\",\"Resource\":\"$PARAM_ARN\"}]}"
printf 'export SECRET_ARN=%s\nexport PARAM_ARN=%s\n' $SECRET_ARN $PARAM_ARN >> ~/hour4-aws.env

Note that the permissions go on the task execution role, not the task role. Secrets Manager ARNs end with a random 6-character suffix, so use the ARN returned by the command instead of building it by hand.

Cache security group, RBAC user and user group
CACHE_SG=$(aws ec2 create-security-group --group-name sg-myapp-cache --description "myapp valkey" \
  --vpc-id $VPC_ID --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id $CACHE_SG \
  --ip-permissions "IpProtocol=tcp,FromPort=6379,ToPort=6380,UserIdGroupPairs=[{GroupId=$TASK_SG}]"
aws elasticache create-user --user-id myapp-default --user-name default --engine VALKEY \
  --passwords "$PW" --access-string "on ~* +@all"
aws elasticache create-user-group --user-group-id myapp-ug --engine VALKEY --user-ids myapp-default
echo "export CACHE_SG=$CACHE_SG" >> ~/hour4-aws.env

For simplicity, the lab grants all permissions (+@all); in production, tighten the access string as needed (for example, deny +@dangerous), or switch to IAM authentication (check the official docs).

Create ElastiCache Serverless (Valkey)
aws elasticache create-serverless-cache --serverless-cache-name myapp-cache --engine valkey \
  --user-group-id myapp-ug --security-group-ids $CACHE_SG \
  --subnet-ids $(echo $SUBNETS | tr ',' ' ') --tags $TAG_KV --query 'ServerlessCache.Status' --output text
until [ "$(aws elasticache describe-serverless-caches --serverless-cache-name myapp-cache \
  --query 'ServerlessCaches[0].Status' --output text)" = "available" ]; do echo waiting…; sleep 20; done
CACHE_HOST=$(aws elasticache describe-serverless-caches --serverless-cache-name myapp-cache \
  --query 'ServerlessCaches[0].Endpoint.Address' --output text)
echo "export CACHE_HOST=$CACHE_HOST" >> ~/hour4-aws.env; echo $CACHE_HOST
creating
waiting…
…
myapp-cache-abc123.serverless.cac1.cache.amazonaws.com
Register a new task definition revision: environment + secrets
source ~/hour4-aws.env
python3 - <<EOF
import json
d = json.load(open("taskdef.json"))
c = d["containerDefinitions"][0]
c["environment"] = [
  {"name": "APP_VERSION", "value": "1.1"},
  {"name": "REDIS_HOST",  "value": "$CACHE_HOST"},
  {"name": "REDIS_PORT",  "value": "6379"},
  {"name": "REDIS_SSL",   "value": "true"},
]
c["secrets"] = [
  {"name": "REDIS_PASSWORD", "valueFrom": "$SECRET_ARN"},
  {"name": "BANNER",         "valueFrom": "$PARAM_ARN"},
]
json.dump(d, open("taskdef.json", "w"), indent=2)
EOF
aws ecs register-task-definition --cli-input-json file://taskdef.json --query 'taskDefinition.revision'
aws ecs update-service --cluster $CLUSTER --service $SVC --task-definition $FAMILY --query 'service.taskDefinition' --output text
aws ecs wait services-stable --cluster $CLUSTER --services $SVC
for i in 1 2 3; do curl -s http://$ALB_DNS/; done
2
arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:2
[1.1] Hello from ip-172-31-5-90…, hits=1
[1.1] Hello from ip-172-31-41-7…, hits=2
[1.1] Hello from ip-172-31-5-90…, hits=3

--task-definition myapp (family only) means the latest ACTIVE revision is used. Both tasks share the same counter - state now lives outside the containers.

See for yourself that "secret updates don't take effect automatically"
aws ssm put-parameter --name /myapp/banner --type String --value "banner-v2" --overwrite
TASK=$(aws ecs list-tasks --cluster $CLUSTER --service-name $SVC --query 'taskArns[0]' --output text)
aws ecs execute-command --cluster $CLUSTER --task $TASK --container web --interactive --command "printenv BANNER"
aws ecs update-service --cluster $CLUSTER --service $SVC --force-new-deployment --query 'service.deployments[0].status' --output text
aws ecs wait services-stable --cluster $CLUSTER --services $SVC
TASK=$(aws ecs list-tasks --cluster $CLUSTER --service-name $SVC --query 'taskArns[0]' --output text)
aws ecs execute-command --cluster $CLUSTER --task $TASK --container web --interactive --command "printenv BANNER"
hello-from-ssm        ← old task still has the old value
PRIMARY
banner-v2             ← new task after the forced new deployment

execute-command requires the Session Manager plugin on your machine (Module 0); the output also includes prompt lines such as "Starting session…".

Case 1: Half of requests fail after a password rotation

The security team rotated the cache password in Secrets Manager and changed the cache user's password at the same time. Running tasks still held the old password, while new tasks (from scale-out or replacement) got the new one - so "half the tasks work, half return WRONGPASS". Fix: an ElastiCache RBAC user can have two passwords at once (check the official docs), so rotate in the order "add the new password → force a new deployment → remove the old password"; have the rotation Lambda trigger update-service --force-new-deployment when it finishes.

Case 2: A password shows up in describe-task-definition output

A developer put the database password in environment, so anyone with ecs:DescribeTaskDefinition permission could read it, and the CI logs printed the task definition too. Fix: move all sensitive values to secrets + valueFrom; in CI, use policy checks (such as cfn-lint or checkov rules) to block password-like key names in environment.

ResourceInitializationError: unable to pull secrets or registry auth: … AccessDeniedException … secretsmanager:GetSecretValue

The task execution role lacks permission to read the secret (or the ARN is wrong, the secret is in another Region, or the KMS key doesn't allow decryption). Check that the Resource in the execution role's policy exactly matches valueFrom.

ResourceInitializationError … unable to retrieve secret from asm: … context deadline exceeded / timeout

Network issue: the task is in a private subnet with no NAT or Secrets Manager interface VPC endpoint; or it's in a public subnet but assignPublicIp=DISABLED.

hits=N/A, and the logs show Timeout connecting to server

The cache security group doesn't allow 6379/6380 from sg-task; or the task and cache are in different VPCs; or REDIS_HOST is wrong.

hits=N/A, and the logs show Connection reset / SSL-related errors

Serverless requires TLS: REDIS_SSL=true.

WRONGPASS invalid username-password pair

The password in the secret doesn't match the RBAC user's password, or the secret was updated without a forced new deployment.

or score ≥ 70% on the Quiz

Module 5 · Release Strategies, Rollback and Scaling

32:00 – 40:00 · Rolling updates with circuit breaker auto-rollback, ECS native blue/green deployments, target tracking auto scaling
8 minROLLING · BLUE_GREEN · LINEAR · CANARYApplication Auto Scaling
Learning objectives
  • Work out how a rolling update proceeds from minimumHealthyPercent / maximumPercent; understand the two stages and the threshold of the deployment circuit breaker.
  • Configure an ECS native blue/green deployment (alternate target group, production listener rule, infrastructure role, bake time) and compare it with CodeDeploy blue/green.
  • Implement auto scaling with Application Auto Scaling target tracking (CPU or ALBRequestCountPerTarget) and observe it under a load test.

What: ECS deployment strategies (deploymentController = ECS)

strategyBehaviorKey parametersRollback
ROLLING (default)Starts new tasks and stops old tasks in batches by percentage; old and new tasks receive traffic at the same timeminimumHealthyPercent, maximumPercent, deploymentCircuitBreaker, alarmsCircuit breaker with rollback=true automatically returns to the most recent COMPLETED deployment
BLUE_GREENFirst scales green to 100% (no production traffic) → optional test traffic → production traffic shifts to green all at once → blue keeps running during bake time → blue is cleaned upbakeTimeInMinutes, advancedConfiguration (alternate target group, production/test listener rules, role), lifecycle hooks, alarmsIf a problem appears before bake time ends, traffic can be shifted back to blue (within seconds)
LINEAR / CANARYShifts traffic gradually in fixed steps / shifts a small portion first, then the rest after validationSame resources as blue/green + step size/percentage and their own bake timesSame as blue/green

Two other deployment controllers exist: CODE_DEPLOY (classic CodeDeploy blue/green, see the table below) and EXTERNAL (third-party controllers).

Why: the two rolling update percentages

  • minimumHealthyPercent: the minimum number of healthy tasks (RUNNING and passing health checks) kept during a deployment; lower bound = ceil(desired × min%).
  • maximumPercent: the maximum number of tasks (new + old, RUNNING or PENDING) allowed during a deployment; upper bound = floor(desired × max%).
  • desired=2, min=100%, max=200%: start 2 new tasks first (4 in total) → stop the 2 old tasks once the new ones are healthy. Zero downtime, but temporarily needs double the capacity.
  • desired=4, min=50%, max=100%: stop 2 old tasks first → start 2 new tasks → then replace the remaining 2. No extra capacity needed, but capacity is halved during the deployment.

How: the deployment circuit breaker (official mechanism)

  • Stage 1: monitors whether tasks reach RUNNING. By default (resetOnHealthyTask=true) only consecutive failures are counted.
  • Stage 2: once at least one task is RUNNING, it checks ELB health checks, Cloud Map health checks and the container healthCheck; tasks replaced because of failed health checks count toward the failure count.
  • Threshold: by default BOUNDED_PERCENT with value 50: threshold = ceil(0.5 × desired), clamped between 3 and 200 (with desired=2 the threshold is 3). You can also use UNBOUNDED_PERCENT or a fixed COUNT.
  • On failure the deployment becomes FAILED; with rollback enabled it rolls back to the most recent COMPLETED deployment. rolloutState / rolloutStateReason in describe-services and the EventBridge event SERVICE_DEPLOYMENT_FAILED can be used for alerting.
  • The circuit breaker applies only to rolling updates that use the ECS deployment controller.

When: ECS native blue/green vs CodeDeploy blue/green

ECS native blue/green (strategy=BLUE_GREEN)CodeDeploy blue/green (deploymentController=CODE_DEPLOY)
Where it is configuredThe ECS service itself (update-service)A separate CodeDeploy application, deployment group and AppSpec
Traffic shiftingECS changes the weights of the two target groups in the ALB production listener rule (requires the rule ARN); blue/green shifts everything at once, linear/canary shift graduallyCodeDeploy switches the listener; supports canary/linear configurations
ValidationTest listener rule + lifecycle hooks (Lambda or pause hooks, resumed with ContinueServiceDeployment)AppSpec hooks (Lambda)
Load balancing/connectivityALB, NLB, Service Connect, VPC Lattice; also works for "headless" services without a load balancer (but traffic shifting is not managed)ALB, NLB
PermissionsInfrastructure role (e.g. managed policy AmazonECSInfrastructureRolePolicyForLoadBalancers), specified in advancedConfiguration.roleArnCodeDeploy service role

ECS native blue/green was launched in 2025 (see AWS What's New for the exact release date). Per the official docs: each lifecycle stage can last up to 24 hours; pause hook timeouts can be up to 14 days; a whole deployment can last up to 30 days; with an NLB, the test/production traffic shift stages take about 10 extra minutes.

Scaling: Application Auto Scaling

  • Scalable target: --service-namespace ecs --scalable-dimension ecs:service:DesiredCount --resource-id service/<cluster>/<service>.
  • Predefined target tracking metrics: ECSServiceAverageCPUUtilization, ECSServiceAverageMemoryUtilization, ALBRequestCountPerTarget (requires ResourceLabel = app/<lb-name>/<id>/targetgroup/<tg-name>/<id>).
  • Note: blue/green deployments switch between two target groups, so an ALBRequestCountPerTarget policy based on a single target group may point at the idle target group after a switch. This lesson's lab uses CPU target tracking (check the official docs for whether this is now handled automatically).
  • Unlike ACA, ECS services do not "wake from 0 automatically when a request arrives"; user-facing services should run a minimum of ≥ 2 tasks (across two Availability Zones).
ECS native blue/green: main lifecycle stages (ALB) SCALE_UPgreen to 100%in alternate TG TEST_TRAFFICtest rule → green(optional, Lambda hook) PRODUCTION_TRAFFICset prod rule weightsblue 0% / green 100% BAKE_TIMEblue still runningalarm → rollback CLEAN_UPblue scaled to 0 ALB prod listener ruleforward: tg-blue w=0tg-green w=100 tg-myapp-blue (main) tg-myapp-green (alt) Infra role (roleArn) lets ECS edit rules Rolling uses one TG: old and new tasks register together; traffic splits by count

Rolling vs blue/green traffic shift simulator

Old version v1.1 (blue)New version v1.2 (green)PENDING / startingFailed
CommandDescription
aws ecs update-service … --task-definition myapp:3Release a new revision (deployed using the service's current strategy)
--deployment-configuration "minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}"Rolling update + circuit breaker auto-rollback
aws ecs describe-services … --query 'services[0].deployments[].[status,rolloutState,rolloutStateReason,taskDefinition]'Check deployment status
--deployment-configuration "strategy=BLUE_GREEN,maximumPercent=200,minimumHealthyPercent=100,bakeTimeInMinutes=5"Native blue/green
--load-balancers "targetGroupArn=…,containerName=web,containerPort=5000,advancedConfiguration={alternateTargetGroupArn=…,productionListenerRule=…,roleArn=…}"Advanced load balancer configuration required for blue/green
aws ecs list-service-deployments --cluster $CLUSTER --service $SVC / describe-service-deploymentsService deployment history and lifecycle stages
aws ecs stop-service-deployment --service-deployment-arn … --stop-type ROLLBACKManually roll back an in-progress deployment (check the CLI reference for parameters)
aws application-autoscaling register-scalable-target --service-namespace ecs --scalable-dimension ecs:service:DesiredCount --resource-id service/$CLUSTER/$SVC --min-capacity 2 --max-capacity 6Register a scalable target
aws application-autoscaling put-scaling-policy --policy-type TargetTrackingScaling …Target tracking policy
aws application-autoscaling describe-scaling-activities --service-namespace ecsScaling activity history

Lab 5: rolling release, circuit breaker rollback, blue/green, load-test scale-out (about 8 minutes)

Rolling release of 1.2
source ~/hour4-aws.env
cd ~/myapp && docker buildx build --platform linux/amd64 -t $ECR/$REPO:1.2 --push .
newrev(){  # usage: newrev IMAGE_TAG APP_VERSION - registers a new revision based on taskdef.json
python3 - "$1" "$2" <<'EOF'
import json, sys, os
d = json.load(open("taskdef.json")); c = d["containerDefinitions"][0]
c["image"] = f'{os.environ["ECR"]}/{os.environ["REPO"]}:{sys.argv[1]}'
for e in c["environment"]:
    if e["name"] == "APP_VERSION": e["value"] = sys.argv[2]
json.dump(d, open("taskdef.json", "w"), indent=2)
EOF
aws ecs register-task-definition --cli-input-json file://taskdef.json --query 'taskDefinition.taskDefinitionArn' --output text; }
newrev 1.2 1.2
aws ecs update-service --cluster $CLUSTER --service $SVC --task-definition $FAMILY --query 'service.status' --output text
watch -n5 "aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].deployments[].[status,taskDefinition,runningCount,pendingCount,rolloutState]' --output table"

Watch the two deployments, PRIMARY (new) and ACTIVE (old): first 4 tasks run side by side, then the old tasks are stopped once the new ones pass health checks (press Ctrl+C to exit watch). Meanwhile curl returns both [1.1] and [1.2].

Circuit breaker drill: release an image tag that does not exist
cp taskdef.json taskdef.good.json
newrev 9.9 9.9 && cp taskdef.good.json taskdef.json
aws ecs update-service --cluster $CLUSTER --service $SVC --task-definition $FAMILY --query 'service.taskDefinition' --output text
sleep 240
aws ecs describe-services --cluster $CLUSTER --services $SVC \
  --query 'services[0].deployments[].[status,rolloutState,rolloutStateReason]' --output text
aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].events[:4].message' --output text
PRIMARY  IN_PROGRESS  ECS deployment circuit breaker: rolling back to deploymentId ecs-svc/…
ACTIVE   FAILED       ECS deployment circuit breaker: tasks failed to start.
(service myapp) rolling back to deployment ecs-svc/…
(service myapp) deployment ecs-svc/… deployment failed: tasks failed to start.

With desired=2 the threshold is 3 (the minimum), so 3 consecutive task launch failures trigger it; the old tasks keep serving throughout the rollback, so users notice nothing. The exact event text may differ in your output. After the rollback the service uses the old revision, but the most recently registered revision (9.9) is still ACTIVE - deregister it with aws ecs deregister-task-definition so that a later --task-definition myapp doesn't pick it up by mistake.

Switch to ECS native blue/green deployments (launched in 2025)
source ~/hour4-aws.env
BADREV=$(aws ecs describe-task-definition --task-definition $FAMILY --query taskDefinition.revision --output text)
aws ecs deregister-task-definition --task-definition $FAMILY:$BADREV --query 'taskDefinition.status' --output text   # deregister the 9.9 revision
TG_GREEN=$(aws elbv2 create-target-group --name tg-myapp-green --protocol HTTP --port 5000 --vpc-id $VPC_ID \
  --target-type ip --health-check-path /healthz --matcher HttpCode=200 --health-check-interval-seconds 15 \
  --healthy-threshold-count 2 --query 'TargetGroups[0].TargetGroupArn' --output text)
# Attach the alternate target group to the same production rule (weight 0); ECS then shifts traffic by changing the weights
aws elbv2 modify-rule --rule-arn $PROD_RULE --actions \
  "Type=forward,ForwardConfig={TargetGroups=[{TargetGroupArn=$TG_BLUE,Weight=100},{TargetGroupArn=$TG_GREEN,Weight=0}]}"
cat > ecs-trust.json <<'EOF'
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ecs.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
EOF
aws iam create-role --role-name myappEcsInfraRole --assume-role-policy-document file://ecs-trust.json --tags $TAG_KV --query Role.Arn --output text
aws iam attach-role-policy --role-name myappEcsInfraRole \
  --policy-arn arn:aws:iam::aws:policy/AmazonECSInfrastructureRolePolicyForLoadBalancers
INFRA_ROLE=arn:aws:iam::${ACCOUNT_ID}:role/myappEcsInfraRole
printf 'export TG_GREEN=%s\nexport INFRA_ROLE=%s\n' $TG_GREEN $INFRA_ROLE >> ~/hour4-aws.env
sleep 15   # wait for the role to propagate
cd ~/myapp && sed -i 's/Hello from/Hi from/' app.py && docker buildx build --platform linux/amd64 -t $ECR/$REPO:1.3 --push . && sed -i 's/Hi from/Hello from/' app.py
newrev 1.3 1.3
aws ecs update-service --cluster $CLUSTER --service $SVC --task-definition $FAMILY \
  --deployment-configuration "strategy=BLUE_GREEN,maximumPercent=200,minimumHealthyPercent=100,bakeTimeInMinutes=5" \
  --load-balancers "targetGroupArn=$TG_BLUE,containerName=web,containerPort=5000,advancedConfiguration={alternateTargetGroupArn=$TG_GREEN,productionListenerRule=$PROD_RULE,roleArn=$INFRA_ROLE}" \
  --query 'service.deploymentConfiguration.strategy' --output text
aws ecs list-service-deployments --cluster $CLUSTER --service $SVC --query 'serviceDeployments[0].[status,serviceDeploymentArn]' --output text
while true; do curl -s http://$ALB_DNS/ | cut -c1-30; sleep 3; done     # watch the one-time switch from [1.2] Hello to [1.3] Hi; Ctrl+C to exit

For the managed policy name and whether modify-rule is a required step, refer to "Application Load Balancer resources for blue/green, linear, and canary deployments" and the IAM documentation. During the bake time (5 minutes) the blue tasks keep running: if you find a problem, shift traffic back to blue with aws ecs stop-service-deployment --service-deployment-arn <ARN> --stop-type ROLLBACK.

Target tracking auto scaling + load test
aws application-autoscaling register-scalable-target --service-namespace ecs \
  --scalable-dimension ecs:service:DesiredCount --resource-id service/$CLUSTER/$SVC \
  --min-capacity 2 --max-capacity 6
cat > tt.json <<'EOF'
{ "TargetValue": 50.0,
  "PredefinedMetricSpecification": { "PredefinedMetricType": "ECSServiceAverageCPUUtilization" },
  "ScaleOutCooldown": 60, "ScaleInCooldown": 120 }
EOF
aws application-autoscaling put-scaling-policy --service-namespace ecs \
  --scalable-dimension ecs:service:DesiredCount --resource-id service/$CLUSTER/$SVC \
  --policy-name cpu50 --policy-type TargetTrackingScaling \
  --target-tracking-scaling-policy-configuration file://tt.json --query 'Alarms[].AlarmName'
seq 30000 | xargs -P 60 -I{} curl -s -o /dev/null http://$ALB_DNS/ &
sleep 300; aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].[desiredCount,runningCount]'
aws application-autoscaling describe-scaling-activities --service-namespace ecs --query 'ScalingActivities[:3].Description'
wait

Target tracking automatically creates two CloudWatch alarms (scale-out/scale-in); do not modify them manually. Scaling out needs at least a few minutes of CloudWatch metric data points, so be patient; after the load test ends the service gradually scales back to 2 over about 15 minutes (scale-in is more conservative than scale-out). To scale on request count, use ALBRequestCountPerTarget with a ResourceLabel instead (mind the blue/green target group switching issue).

Case 1: the circuit breaker turned a "3 a.m. incident" into a notification

One release was missing a required environment variable, and the new tasks exited immediately after starting. The deployment circuit breaker marked the deployment FAILED after the 3rd task failure and rolled back; an EventBridge rule matching SERVICE_DEPLOYMENT_FAILED sent it to Slack. The on-call engineer saw the notification in the morning, fixed the issue and redeployed; users never noticed. Before the circuit breaker, the same mistake would leave the service "deploying" indefinitely, launching failing tasks over and over.

Case 2: migrating from CodeDeploy to native blue/green

The team used to maintain a CodeDeploy application, deployment group and AppSpec for every service, which made the pipeline complex. After migrating to ECS native blue/green, the deployment configuration lives in the service definition again; smoke tests run in a Lambda hook at POST_TEST_TRAFFIC_SHIFT, and CloudWatch alarms (5xx rate, P95 latency) trigger automatic rollback during bake time.

Anti-pattern: max=100%, min=100%

Someone set both percentages to 100, thinking it was "the safest". As a result the deployment could neither start extra tasks nor stop old tasks first, and it got stuck. At least one percentage must leave room (commonly min=100/max=200, or min=50/max=100 when capacity is constrained).

Deployment stays IN_PROGRESS and no new tasks start

The min/max percentages leave no room; or the account's Fargate vCPU quota is insufficient (check in Service Quotas); or the subnet has run out of IP addresses (each task uses one ENI).

The circuit breaker didn't trigger, yet the bad version keeps replacing tasks

The circuit breaker is not enabled (enable=false), or the deployment controller is not ECS; or the new tasks can reach RUNNING but no health check is configured, so they are considered successful.

InvalidParameterException (when switching to BLUE_GREEN) … listener rule / alternate target group

productionListenerRule must be a listener rule ARN (not a listener ARN); the alternate target group must be in the same VPC as the primary target group with target type ip; the roleArn role must trust ecs.amazonaws.com and have permissions to manage ELB.

Task count doesn't increase during the load test

CPU doesn't reach the target value (the app is I/O-bound) → use ALBRequestCountPerTarget instead; max-capacity is too small; a cooldown period is in effect; or ResourceLabel points to a different target group.

or score ≥ 70% in the "Quiz" tab

Module 6 · Troubleshooting in Practice: 4 Local Failures + 6 Cloud Failures

40:00 – 50:00 · Check service events and stoppedReason first, then logs, and only then get into the container
10 mindescribe-tasks · CloudWatch Logs Insights · ECS Exec
Learning objectives
  • Locally: use the four-step "ps -a → logs → inspect → exec" method to pinpoint OOM kills, wrong listen addresses, restart loops, and network isolation.
  • In the cloud: use service events, task stoppedReason / exit codes, target health reasons, CloudWatch Logs and Logs Insights, and ECS Exec to pinpoint six common failure types.

Local tools vs. ECS tools

LocalAmazon ECSWhat to look at
docker ps -aaws ecs list-tasks --desired-status STOPPED + describe-taskslastStatus, stopCode, stoppedReason, and each container's exitCode / reason
docker eventsaws ecs describe-services … --query 'services[0].events'Service events: scheduling, deployments, target registration, circuit breaker
docker logsaws logs tail /ecs/myapp --follow (awslogs driver)Application stdout/stderr
—aws elbv2 describe-target-healthTarget state and reason code (e.g. Target.ResponseCodeMismatch, Target.Timeout)
docker inspectaws ecs describe-task-definition / describe-servicesThe effective configuration
docker execaws ecs execute-command --interactive --command "/bin/sh"Get a shell in a running container
—CloudWatch Logs InsightsCross-task queries, aggregation, alarms
Stopped tasks are only kept for a whileSTOPPED tasks remain visible in describe-tasks for only a short time (about 1 hour; see the official documentation). For long-term retention, use EventBridge to capture "ECS Task State Change" events and write them to logs.

Six cloud failure types at a glance

stoppedReason / symptom (example)Common root cause
CannotPullContainerError: … not foundTag doesn't exist; wrong repository, Region, or account
CannotPullContainerError: … i/o timeout or … AccessDeniedPrivate subnet with neither NAT nor ECR (api, dkr) + S3 gateway endpoints; public subnet without a public IP assigned; execution role missing ECR permissions
ResourceInitializationError: unable to pull secrets or registry auth …Execution role can't read Secrets Manager/SSM, KMS doesn't allow decryption, or no network path to Secrets Manager/SSM
Essential container in task exited (exit code 1/3, etc.)Application startup error or wrong command - check the logs
Task failed ELB health checks in (target-group …)Wrong health check path/port, slow startup with no grace period, or task security group doesn't allow the ALB
OutOfMemoryError: Container killed due to memory usage, exit code 137Not enough task/container memory, or a memory leak
exec … exec format error in the logsImage architecture doesn't match runtimePlatform.cpuArchitecture

The messages in the table are typical examples; exact wording varies by platform version, so go by the actual output. The official "Amazon ECS stopped task error messages" page has the full list.

CloudWatch Logs Insights examples

fields @timestamp, @logStream, @message
| filter @message like /Traceback|ERROR|WRONGPASS/
| sort @timestamp desc
| limit 20
filter @message like /ERROR/
| stats count(*) as errors by bin(5m)
QID=$(aws logs start-query --log-group-name $LOG_GROUP \
  --start-time $(date -d '-30 min' +%s) --end-time $(date +%s) \
  --query-string 'fields @timestamp, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 20' \
  --query queryId --output text)
sleep 5; aws logs get-query-results --query-id $QID --query 'results[][?field==`@message`].value' --output text
Service eventsdescribe-servicesevents[:10] Never reached RUNNING→ stoppedReason: pull / secret / net Exits after RUNNING→ exitCode + CloudWatch logs RUNNING but replaced / 5xx→ describe-target-health reason Exec role perms · NAT/VPC endpoints · assignPublicIpTag/Region/account · Secrets ARN · KMS 137 → OOM (add memory/find leak) · exec format → arch1/3 → app error (logs tail / Logs Insights) HC path/port · grace period · sg-task allows sg-albDependency reachability → test via ECS Exec

Cloud failure drills (6 scenarios)

Read the "evidence", identify the root cause, then see the fix.

CommandDescription
aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].events[:10].[createdAt,message]' --output textService events
aws ecs list-tasks --cluster $CLUSTER --service-name $SVC --desired-status STOPPEDRecently stopped tasks
aws ecs describe-tasks --cluster $CLUSTER --tasks $T --query 'tasks[].stoppedReason'Stop reason
aws ecs describe-tasks … --query 'tasks[].containers[].[name,exitCode,reason]'Container exit codes and reasons
aws logs tail $LOG_GROUP --follow --since 15mLive logs
aws logs start-query … / get-query-resultsLogs Insights queries
aws elbv2 describe-target-health --target-group-arn $TG_BLUETarget health reason codes
aws ecs execute-command --cluster $CLUSTER --task $T --container web --interactive --command "/bin/sh"ECS Exec (requires the plugin + ssmmessages on the task role + enableExecuteCommand on the service)
aws ecs describe-tasks … --query 'tasks[].containers[].managedAgents'Confirm ExecuteCommandAgent is RUNNING
docker buildx imagetools inspect $ECR/myapp:TAGConfirm the image platform
aws iam simulate-principal-policy --policy-source-arn $EXEC_ROLE_ARN --action-names secretsmanager:GetSecretValue --resource-arns $SECRET_ARNSimulate the execution role's permissions

Lab 6A: Four local failures (about 4 minutes)

OOM
docker run --name oom --memory 20m --memory-swap 20m python:3.13-slim python -c "a = ' ' * 200_000_000"
docker inspect oom --format 'ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}'; docker rm oom
ExitCode=137 OOMKilled=true
Port is mapped but unreachable
docker build -q -t myapp:local ~/myapp
docker run -d --name bad -p 5001:5000 myapp:local gunicorn -b 127.0.0.1:5000 app:app
curl -s localhost:5001 || echo "Connection failed: the app only listens on 127.0.0.1"; docker rm -f bad
Restart loop: check the logs first
docker run -d --name loop --restart unless-stopped myapp:local gunicorn -b 0.0.0.0:5000 wrong:app
sleep 5; docker ps --filter name=loop --format '{{.Status}}'
docker logs loop 2>&1 | grep -m1 ModuleNotFoundError; docker rm -f loop
Restarting (3) 1 second ago
ModuleNotFoundError: No module named 'wrong'
Containers on different networks
docker network create net1; docker network create net2
docker run -d --name redis --network net1 redis:7-alpine
docker run -d --name web --network net2 -p 5000:5000 -e REDIS_HOST=redis myapp:local
sleep 2; curl -s localhost:5000                   # hits=N/A
docker network connect net1 web; curl -s localhost:5000   # hits=1
docker rm -f web redis; docker network rm net1 net2

Lab 6B: Break and fix things on ECS (about 6 minutes)

Use run-task to launch standalone tasks that reproduce each failure without affecting the live myapp service.

Setup: common parameters for standalone tasks
source ~/hour4-aws.env
NET="awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$TASK_SG],assignPublicIp=ENABLED}"
runt(){ aws ecs run-task --cluster $CLUSTER --launch-type FARGATE --network-configuration "$NET" \
  --task-definition $FAMILY "$@" --query 'tasks[0].taskArn' --output text; }
why(){ aws ecs wait tasks-stopped --cluster $CLUSTER --tasks $1; aws ecs describe-tasks --cluster $CLUSTER --tasks $1 \
  --query 'tasks[0].[stopCode,stoppedReason,containers[0].exitCode,containers[0].reason]' --output text; }
Essential container exited (wrong command)
T=$(runt --overrides '{"containerOverrides":[{"name":"web","command":["gunicorn","-b","0.0.0.0:5000","wrong:app"]}]}')
why $T
aws logs tail $LOG_GROUP --since 5m --log-stream-name-prefix myapp/web/${T##*/} | grep -m1 ModuleNotFoundError
EssentialContainerExited   Essential container in task exited   3   None
… ModuleNotFoundError: No module named 'wrong'
OOM (exit code 137)
T=$(runt --overrides '{"containerOverrides":[{"name":"web","command":["python","-c","a = \" \" * 3_000_000_000"]}]}')
why $T
EssentialContainerExited   …   137   OutOfMemoryError: Container killed due to memory usage

The task has 1024 MiB of memory, so allocating a 3 GB string is guaranteed to OOM. In production, check the memory graph in CloudWatch Container Insights first, then decide whether to add memory or fix a leak.

CannotPullContainerError (nonexistent tag) and exec format error (architecture mismatch)
docker buildx build --platform linux/arm64 -t $ECR/$REPO:arm-only --push ~/myapp
for TAG in 9.9 arm-only; do
  sed "s#$ECR/$REPO:[^\"]*#$ECR/$REPO:$TAG#" taskdef.json | sed 's/"family": "myapp"/"family": "myapp-drill"/' > drill.json
  aws ecs register-task-definition --cli-input-json file://drill.json --query 'taskDefinition.revision' --output text
  T=$(aws ecs run-task --cluster $CLUSTER --launch-type FARGATE --network-configuration "$NET" --task-definition myapp-drill --query 'tasks[0].taskArn' --output text)
  why $T
done
aws logs tail $LOG_GROUP --since 10m | grep -m1 "exec format error"
TaskFailedToStart   CannotPullContainerError: … myapp:9.9: not found   None   None
EssentialContainerExited   Essential container in task exited   255   None
… exec /usr/local/bin/gunicorn: exec format error

Building arm64 on an amd64 machine requires QEMU installed as in Lesson 2. Fix: build an amd64 or multi-platform image, or change the task definition to "cpuArchitecture": "ARM64" and use an arm64 image.

ResourceInitializationError (execution role can't read a secret)
aws secretsmanager create-secret --name myapp/not-allowed --secret-string x --query ARN --output text > /tmp/na
python3 - <<EOF
import json
d = json.load(open("taskdef.json")); d["family"] = "myapp-drill"
d["containerDefinitions"][0]["secrets"].append({"name": "OTHER", "valueFrom": open("/tmp/na").read().strip()})
json.dump(d, open("drill.json", "w"))
EOF
aws ecs register-task-definition --cli-input-json file://drill.json --query 'taskDefinition.revision' --output text
T=$(aws ecs run-task --cluster $CLUSTER --launch-type FARGATE --network-configuration "$NET" --task-definition myapp-drill --query 'tasks[0].taskArn' --output text)
why $T
aws secretsmanager delete-secret --secret-id myapp/not-allowed --force-delete-without-recovery >/dev/null
TaskFailedToStart   ResourceInitializationError: unable to pull secrets or registry auth: … AccessDeniedException … secretsmanager:GetSecretValue …
Failed ALB health checks cause repeated task replacement
for TG in $TG_BLUE $TG_GREEN; do aws elbv2 modify-target-group --target-group-arn $TG --health-check-path /health >/dev/null; done
sleep 60
aws elbv2 describe-target-health --target-group-arn $TG_BLUE --query 'TargetHealthDescriptions[].TargetHealth.[State,Reason,Description]' --output text
aws elbv2 describe-target-health --target-group-arn $TG_GREEN --query 'TargetHealthDescriptions[].TargetHealth.[State,Reason,Description]' --output text
aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].events[:3].message' --output text
for TG in $TG_BLUE $TG_GREEN; do aws elbv2 modify-target-group --target-group-arn $TG --health-check-path /healthz >/dev/null; done
unhealthy   Target.ResponseCodeMismatch   Health checks failed with these codes: [404]
(service myapp) has started 2 tasks: …
(service myapp) deregistered 1 targets in (target-group …)

After a blue/green deployment, production traffic may be on the green target group, so change and check both. Switch back to /healthz quickly, or the service will keep replacing tasks.

Use ECS Exec to test dependencies from inside the container
T=$(aws ecs list-tasks --cluster $CLUSTER --service-name $SVC --query 'taskArns[0]' --output text)
aws ecs execute-command --cluster $CLUSTER --task $T --container web --interactive \
  --command "python -c \"import os,redis;r=redis.Redis(host=os.environ['REDIS_HOST'],port=6379,password=os.environ['REDIS_PASSWORD'],ssl=True);print(r.ping())\""
Starting session with SessionId: ecs-execute-command-…
True

ECS Exec sessions time out after 20 minutes of inactivity (not configurable), and readonlyRootFilesystem is not supported. In production, use IAM condition keys to restrict who can run commands on which clusters/containers, and send session logs to CloudWatch or S3 for auditing.

Case: after moving to private subnets, no new task would start

To meet a security baseline, the team moved the service from public to private subnets and deleted the NAT gateway to "save costs". Every new task failed with CannotPullContainerError … i/o timeout. After adding the ECR interface endpoints, the error became "layer … timeout": image layers are stored in S3, so an S3 gateway endpoint was still missing. Next came ResourceInitializationError (missing Secrets Manager endpoint), and then logs couldn't be written (missing CloudWatch Logs endpoint). Lesson learned: before migrating, list every service endpoint the task startup path depends on, and verify each one with a standalone task (run-task).

Case: Logs Insights uncovers "invisible" OOM kills

Users occasionally hit 502 errors, yet the service always appeared to have 2 tasks. Querying stopped-task events revealed that a dozen or more tasks per hour were being replaced due to OutOfMemoryError. The team used EventBridge to log task state changes and set up alarms, raised memory from 1 GB to 2 GB, and fixed an unbounded in-process cache.

SymptomCheck firstCommon causes
TaskFailedToStart: CannotPullContainerErrorFull stoppedReason textTag doesn't exist; private subnet without NAT/endpoints; public subnet without a public IP; execution role missing permissions
TaskFailedToStart: ResourceInitializationErrorstoppedReason + execution role policyCan't read secrets/parameters; KMS; network; log group doesn't exist
Essential container exited, exit code 1/3CloudWatch logsApplication error, wrong command, missing environment variable
Exit code 137 + OutOfMemoryErrorMemory settings, Container InsightsOOM
exec format errorLogs, imagetoolsArchitecture mismatch
Task failed ELB health checksdescribe-target-health reason codePath/port, grace period, security groups
execute-command returns TargetNotConnectedExceptionmanagedAgents statusenableExecuteCommand not enabled on the service (requires new tasks), task role missing ssmmessages, ssmmessages endpoint unreachable, plugin not installed locally
or score ≥ 70% on the "Quiz"

Module 7 · Moving to Kubernetes: Amazon EKS (eksctl · EKS Auto Mode)

50:00 – 57:00 · Same ECR image, a different orchestrator
7 mineksctl ≥ 0.195.0 · --enable-auto-modeControl plane billed hourly
Learning objectives
  • Map Compose / ECS task definition concepts to Deployment, Service, ConfigMap, Secret, Probe, and Resources.
  • Understand what EKS Auto Mode manages for you, and create a cluster with a single eksctl command.
  • Understand how EKS nodes pull images from same-account ECR without credentials (node role + AmazonEC2ContainerRegistryPullOnly).

Concept mapping

Docker / ComposeAmazon ECSKubernetes (EKS)
ContainerContainer definition in a task definitionContainer in a Pod
Compose serviceService + task definitionDeployment + Service
Image tag / new versionTask definition revision myapp:NReplicaSet (one per Deployment version)
environmentenvironmentConfigMap / env
secretssecrets.valueFrom (Secrets Manager/SSM)Secret (or Secrets Store CSI Driver + AWS provider / External Secrets)
healthcheckContainer healthCheck + ALB health checkstartup / readiness / liveness Probe
--memory / --cpusTask-level cpu/memory (valid combinations)resources.requests / limits
portsALB + target group (ip)Service (ClusterIP/LoadBalancer) + Ingress / Gateway (AWS Load Balancer Controller or Auto Mode built-in load balancing)
--scaledesiredCount + Application Auto Scalingreplicas / HPA; nodes scaled by Karpenter / Auto Mode
—Task roleEKS Pod Identity / IRSA (ServiceAccount bound to an IAM role)
—Execution role (pulls images)Node IAM role (kubelet pulls images)

Why: EKS Auto Mode

EKS Auto Mode (launched at re:Invent 2024) lets AWS manage node selection, scaling, patching, and lifecycle, plus core components for compute, storage (EBS CSI), load balancing, and networking; you only write Kubernetes manifests. AWS recommends using the default node pools (general-purpose, system) the first time and letting eksctl create the node IAM role automatically. eksctl must be version 0.195.0 or later.

How: how nodes pull ECR images

The Auto Mode node IAM role has AmazonEKSWorkerNodeMinimalPolicy and AmazonEC2ContainerRegistryPullOnly attached (the two managed policies listed in the official manual setup steps). The kubelet uses the node role to obtain an ECR token, so same-account ECR images need no imagePullSecrets. Compare with Azure: AKS uses --attach-acr to grant AcrPull to the kubelet identity.

When: moving from ECS to EKS

When you need the Kubernetes API ecosystem (Operators, CRDs, Helm charts, GitOps tooling), multi-cloud consistency, or your platform team already has Kubernetes skills. The ECS groundwork carries over directly: images, health endpoints, resource settings, non-root users, and externalized secrets. To learn Kubernetes systematically, continue with the 6-hour interactive Kubernetes course in the same repository.

EKS cluster eks-lab (Auto Mode) · AWS-managed control plane (billed hourly) Service myappport 80 → 5000 Deployment myapp (replicas: 2) ReplicaSet 1.2Pod · Pod ReplicaSet 1.3Rolling out image: <account>.dkr.ecr.ca-central-1.amazonaws.com/myapp:1.3 envFrom ConfigMap · Secret · probes /healthz · requests/limits Auto Mode nodesNode role: PullOnly→ ECR token → pull image Service redisDeployment redis (lab)

ECS task definition / Compose → Kubernetes mapper

Click a field on the left to see the matching Kubernetes configuration on the right.

CommandDescription
eksctl versionConfirm ≥ 0.195.0
eksctl create cluster --name=eks-lab --region=$AWS_REGION --enable-auto-modeCreate an Auto Mode cluster (about 15–20 minutes; eksctl uses CloudFormation to create the VPC and other resources)
eksctl create cluster -f cluster.yamlYAML approach (autoModeConfig.enabled: true)
aws eks update-kubeconfig --name eks-labWrite kubeconfig (eksctl already does this for you)
kubectl get nodesWith Auto Mode there may be 0 nodes when no workloads exist; nodes are created on demand once Pods are deployed
kubectl apply -f k8s.yaml / kubectl rollout status deploy/myappDeploy and wait
kubectl describe pod <pod> / kubectl logs deploy/myapp --previousEvents and logs from the previous crash
kubectl set image deploy/myapp web=$ECR/myapp:1.3 / kubectl rollout undo deploy/myappRolling update / rollback
eksctl delete cluster --name=eks-lab --region=$AWS_REGIONDelete the cluster (also deletes the CloudFormation stacks eksctl created)

Lab 7 (optional, billed hourly): deploy myapp on EKS Auto Mode

Cost and riskThe EKS control plane is billed hourly (about USD 0.10 per cluster per hour during standard support; check the EKS pricing page). Auto Mode nodes are billed as EC2 instances plus an Auto Mode management fee. eksctl also creates a VPC and a NAT gateway (NAT is billed hourly too). Delete everything as soon as you finish. Required permissions: administrative access to EKS, EC2, IAM, and CloudFormation. To avoid charges, do the same manifest exercises locally with the kind lab from Lesson 3.
Install eksctl and kubectl, create the cluster
# eksctl: download from GitHub Releases (follow the official eksctl install instructions)
curl -sLO "https://github.com/eksctl-io/eksctl/releases/latest/download/eksctl_Linux_amd64.tar.gz"
tar -xzf eksctl_Linux_amd64.tar.gz -C /tmp && sudo mv /tmp/eksctl /usr/local/bin/
eksctl version                                   # ≥ 0.195.0
# kubectl: install a version matching the cluster version per the EKS doc "Set up kubectl and eksctl"
source ~/hour4-aws.env
eksctl create cluster --name=eks-lab --region=$AWS_REGION --enable-auto-mode
kubectl get nodes; kubectl get nodepools
Write k8s.yaml (image from ECR)
apiVersion: v1
kind: ConfigMap
metadata: { name: myapp-config }
data:
  REDIS_HOST: redis
  APP_VERSION: "1.3"
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: redis }
spec:
  replicas: 1
  selector: { matchLabels: { app: redis } }
  template:
    metadata: { labels: { app: redis } }
    spec:
      containers:
        - name: redis
          image: public.ecr.aws/docker/library/redis:7-alpine
          args: ["--requirepass", "$(REDIS_PASSWORD)"]
          env:
            - name: REDIS_PASSWORD
              valueFrom: { secretKeyRef: { name: myapp-secret, key: REDIS_PASSWORD } }
          ports: [{ containerPort: 6379 }]
---
apiVersion: v1
kind: Service
metadata: { name: redis }
spec:
  selector: { app: redis }
  ports: [{ port: 6379 }]
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: myapp }
spec:
  replicas: 2
  selector: { matchLabels: { app: myapp } }
  template:
    metadata: { labels: { app: myapp } }
    spec:
      securityContext: { runAsNonRoot: true, runAsUser: 10001 }
      containers:
        - name: web
          image: ECR_URI/myapp:1.3
          ports: [{ containerPort: 5000 }]
          envFrom:
            - configMapRef: { name: myapp-config }
            - secretRef: { name: myapp-secret }
          resources:
            requests: { cpu: 250m, memory: 256Mi }
            limits:   { memory: 512Mi }
          readinessProbe: { httpGet: { path: /healthz, port: 5000 }, initialDelaySeconds: 3, periodSeconds: 5 }
          livenessProbe:  { httpGet: { path: /healthz, port: 5000 }, initialDelaySeconds: 10, periodSeconds: 10 }
          securityContext:
            allowPrivilegeEscalation: false
            capabilities: { drop: ["ALL"] }
---
apiVersion: v1
kind: Service
metadata: { name: myapp }
spec:
  selector: { app: myapp }
  ports: [{ port: 80, targetPort: 5000 }]
cat > k8s.yaml      # paste the content above, then Ctrl+D
kubectl create secret generic myapp-secret --from-literal=REDIS_PASSWORD=$(openssl rand -hex 16)
sed "s#ECR_URI#$ECR#" k8s.yaml | kubectl apply -f -
kubectl rollout status deploy/myapp --timeout=5m
kubectl port-forward svc/myapp 8080:80 & sleep 2
curl -s localhost:8080; curl -s localhost:8080
[1.3] Hi from myapp-6d9f8c7b5-x2k4p, hits=1
[1.3] Hi from myapp-6d9f8c7b5-q7m2n, hits=2

No imagePullSecrets at all: the node role pulls myapp:1.3 directly from same-account ECR. Redis uses the Docker Official Image on ECR Public to avoid Docker Hub rate limits. runAsUser: 10001 fixes the case where runAsNonRoot cannot be verified because the image USER is a name (same as Lesson 3). This lesson's ElastiCache is in the default VPC, while eksctl created a new VPC, so we use an in-cluster Redis here; in production, reach ElastiCache through VPC peering or by building the cluster in the same VPC.

Rolling update and rollback
kubectl set image deploy/myapp web=$ECR/myapp:1.2 && kubectl rollout status deploy/myapp
curl -s localhost:8080
kubectl rollout undo deploy/myapp && kubectl rollout status deploy/myapp
kubectl rollout history deploy/myapp
(For reference) Exposing the service externally

Auto Mode has built-in load balancing: a Service of type: LoadBalancer must specify the Auto Mode load balancer class (for example loadBalancerClass: eks.amazonaws.com/nlb), and an Ingress needs an IngressClass/IngressClassParams pointing to the Auto Mode ALB controller. Follow the official EKS Auto Mode documentation for the exact syntax. Load balancers are also billed hourly.

Clean up immediately
kill %1 2>/dev/null
kubectl delete -f <(sed "s#ECR_URI#$ECR#" k8s.yaml) --ignore-not-found
eksctl delete cluster --name=eks-lab --region=$AWS_REGION --wait

First delete the Kubernetes objects that created AWS resources (LoadBalancer Services, Ingresses, PVCs), then delete the cluster, so no load balancers or EBS volumes are left behind.

Case: a platform running ECS and EKS side by side

A company keeps most of its APIs on ECS Fargate (the team knows it well and it is simple to operate). Only the data platform components, which depend on the Kafka Operator and Spark on Kubernetes, run on EKS Auto Mode. Both sides share the same ECR repositories, the same image standards (non-root, /healthz, multi-arch, immutable tags), and the same CI pipeline; only the deploy step differs (aws ecs update-service vs. GitOps-synced manifests).

Anti-pattern: a forgotten LoadBalancer Service

A student ran eksctl delete cluster directly, but the NLB created by the LoadBalancer Service was managed by the controller. Deletion hit a dependency error, the VPC could not be deleted, and the CloudFormation stack got stuck in DELETE_FAILED. Lesson learned: delete Services/Ingresses first, then the cluster.

ErrImagePull … 403 Forbidden (ECR)

The node role lacks ECR pull permissions (common with custom node roles), or the image is in another account (the repository policy must grant access to that account).

Pod stays Pending and kubectl get nodes is empty

Auto Mode creates nodes on demand, which usually takes a minute or two. If Pods stay Pending for long, run kubectl describe pod to check events (resource requests too large, node pool disabled, and so on).

CreateContainerConfigError: container has runAsNonRoot and image has non-numeric user

The image USER is a name. Set runAsUser in the Pod, or use a numeric UID in the image.

error: You must be logged in to the server (Unauthorized)

The IAM identity used by kubeconfig has no cluster access entry (EKS access entries / aws-auth). The identity that created the cluster is an administrator by default; others must be granted access with aws eks create-access-entry.

or score ≥ 70% on the Quiz

Module 8 · Cost, cleanup, and self-check

57:00 – 60:00 · AWS has no "delete resource group"; clean up in dependency order
3 minCost
Learning objectives
  • Know how each resource in this lesson is billed and where the main costs come from (especially resources that charge even when idle).
  • Clean up completely in dependency order, and use tags to find anything left over.
ResourceBilling (summary)Reducing cost
FargateTask vCPU and GB of memory billed per second (1-minute minimum on Linux); ARM64 is cheaper than X86_64; Fargate Spot is cheaper but can be interruptedRight-size, use Graviton, Spot for non-critical tasks, scale in overnight
ALBHourly + LCU (the highest of new connections, active connections, processed bytes, and rule evaluations)Share one ALB across services (host/path rules); Express Mode shares automatically
NAT gatewayHourly + per GB processedUse VPC endpoints (S3 gateway endpoints are free); use public subnets for labs
Interface VPC endpointHourly × Availability Zones + per GBCreate only what you need; centralize and share across VPCs
ElastiCache ServerlessData stored (GB-hours, with a minimum) + ECPUsDelete right after the lab; for steady heavy load consider node-based + reserved
EKSControl plane hourly (higher in extended support) + nodes (Auto Mode adds a management fee)Delete right after the lab; in production, upgrade on time to avoid extended support
CloudWatch LogsIngestion + storage; Logs Insights by data scannedSet retention (7 days in this lesson), control log levels
ECR / Secrets Manager / InspectorStorage GB-month / per secret per month + API calls / per image scannedLifecycle policies; combine secrets into JSON; enable enhanced scanning only where needed

Prices vary by Region and over time; check the official pricing pages for ca-central-1 and the AWS Pricing Calculator. This lesson does not list specific prices (the USD 0.10/hour EKS control plane fee is the published standard support price; still confirm on the pricing page).

Cleanup order (dependencies)

  1. Auto Scaling scalable target → scale service to 0 → delete service (wait for INACTIVE so the ENIs are released)
  2. Deregister and delete task definition revisions → delete cluster
  3. Delete the ALB (this also deletes its listeners and rules) → wait for deletion to finish → delete target groups (ResourceInUse if still referenced by a listener)
  4. Delete ElastiCache Serverless → user group → user
  5. Delete ECR repositories (--force deletes images too) and pull through cache rules
  6. Delete secrets (--force-delete-without-recovery deletes immediately; otherwise there is a recovery window by default) and SSM parameters
  7. Delete log groups
  8. IAM: detach managed policies, delete inline policies → delete roles
  9. Security groups (only after the ENIs using them are released: tasks, ALB, cache)
  10. VPC: keep the default VPC; if you created a new VPC, delete NAT gateways and endpoints and release Elastic IPs first, then delete the VPC
EKS / NAT / ElastiCacheHourly even idle: delete first ALB / Fargate tasksAccrue hourly / per second Logs / ECR / secretsUsage-based, small but ongoing Find leftovers by tagcourse=docker-hour4

Cleanup order drill

Click delete in the correct dependency order. If the order is wrong, you will see the typical error AWS returns.

aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=docker-hour4 \
  --query 'ResourceTagMappingList[].ResourceARN' --output text      # run it both before and after deleting
aws ecs list-services --cluster $CLUSTER
aws elbv2 describe-load-balancers --query 'LoadBalancers[].LoadBalancerName'
aws elasticache describe-serverless-caches --query 'ServerlessCaches[].ServerlessCacheName'
aws ec2 describe-nat-gateways --filter Name=state,Values=available --query 'NatGateways[].NatGatewayId'
aws eks list-clusters

The tagging API only finds resources that support tags and have been tagged (check IAM roles and similar separately). It may also list some recently deleted resources; trust the actual resource state.

Lab 8: full cleanup script

IrreversibleThe commands below permanently delete images, secrets, and logs. Before running them, confirm that ~/hour4-aws.env points to your lab account. If you plan to take Lesson 5, keep the ECR repository and ECS service, or rebuild them with the minimal steps in Lesson 5's setup.
#!/usr/bin/env bash
set -u
source ~/hour4-aws.env
echo "Account: $(aws sts get-caller-identity --query Account --output text)  Region: $AWS_REGION"

# 0) Optional EKS
eksctl delete cluster --name=eks-lab --region=$AWS_REGION --wait 2>/dev/null

# 1) Auto scaling → service
aws application-autoscaling deregister-scalable-target --service-namespace ecs \
  --scalable-dimension ecs:service:DesiredCount --resource-id service/$CLUSTER/$SVC 2>/dev/null
aws ecs update-service --cluster $CLUSTER --service $SVC --desired-count 0 >/dev/null 2>&1
aws ecs delete-service --cluster $CLUSTER --service $SVC --force >/dev/null 2>&1
aws ecs wait services-inactive --cluster $CLUSTER --services $SVC 2>/dev/null

# 2) Task definitions → cluster
for fam in $FAMILY myapp-drill; do
  for td in $(aws ecs list-task-definitions --family-prefix $fam --query 'taskDefinitionArns[]' --output text); do
    aws ecs deregister-task-definition --task-definition $td >/dev/null
    aws ecs delete-task-definitions --task-definitions $td >/dev/null 2>&1
  done
done
aws ecs delete-cluster --cluster $CLUSTER >/dev/null

# 3) ALB → target groups
aws elbv2 delete-load-balancer --load-balancer-arn $ALB_ARN
aws elbv2 wait load-balancers-deleted --load-balancer-arns $ALB_ARN
for tg in ${TG_BLUE:-} ${TG_GREEN:-}; do aws elbv2 delete-target-group --target-group-arn $tg; done

# 4) ElastiCache Serverless → user group → user
aws elasticache delete-serverless-cache --serverless-cache-name myapp-cache >/dev/null 2>&1
while aws elasticache describe-serverless-caches --serverless-cache-name myapp-cache >/dev/null 2>&1; do sleep 20; done
aws elasticache delete-user-group --user-group-id myapp-ug >/dev/null 2>&1; sleep 30
aws elasticache delete-user --user-id myapp-default >/dev/null 2>&1

# 5) ECR
aws ecr delete-repository --repository-name $REPO --force >/dev/null
aws ecr delete-pull-through-cache-rule --ecr-repository-prefix docker-hub >/dev/null 2>&1
aws ecr delete-repository --repository-name docker-hub/library/python --force >/dev/null 2>&1

# 6) Secrets and parameters
for s in myapp/redis-password ecr-pullthroughcache/docker-hub; do
  aws secretsmanager delete-secret --secret-id $s --force-delete-without-recovery >/dev/null 2>&1; done
aws ssm delete-parameter --name /myapp/banner 2>/dev/null

# 7) Logs
aws logs delete-log-group --log-group-name $LOG_GROUP

# 8) IAM roles
aws iam detach-role-policy --role-name myappTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam delete-role-policy --role-name myappTaskExecutionRole --policy-name read-myapp-secrets 2>/dev/null
aws iam delete-role --role-name myappTaskExecutionRole
aws iam delete-role-policy --role-name myappTaskRole --policy-name ecs-exec
aws iam delete-role --role-name myappTaskRole
aws iam detach-role-policy --role-name myappEcsInfraRole --policy-arn arn:aws:iam::aws:policy/AmazonECSInfrastructureRolePolicyForLoadBalancers 2>/dev/null
aws iam delete-role --role-name myappEcsInfraRole 2>/dev/null

# 9) Security groups (ENI release can take a few minutes; if this fails, rerun this section later)
for sg in ${CACHE_SG:-} $TASK_SG $ALB_SG; do
  for i in 1 2 3 4 5 6; do aws ec2 delete-security-group --group-id $sg 2>/dev/null && break; sleep 30; done
done

# 10) Check for leftovers
aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=docker-hour4 \
  --query 'ResourceTagMappingList[].ResourceARN' --output text
echo "Cleanup complete. The default VPC is kept; you can delete ~/hour4-aws.env manually."
bash cleanup-hour4-aws.sh

delete-task-definitions can only delete revisions that have been deregistered (INACTIVE). If you changed the registry-level scanning configuration to ENHANCED, revert it with aws ecr put-registry-scanning-configuration --scan-type BASIC and deactivate ECR scanning in Inspector.

Case: a weekend NAT gateway bill

During a training, students built a new VPC with a NAT gateway to mimic a "production topology". Load testing sent heavy traffic through the NAT, and the VPC was not deleted after the course. A month later, the NAT gateway hourly and data processing charges on the bill far exceeded Fargate itself. Improvements: set AWS Budgets alerts on lab accounts; tag all lab resources with course/expires and have a scheduled Lambda clean up expired resources; keep traffic that can use S3 gateway endpoints off the NAT.

DependencyViolation: resource sg-… has a dependent object

ENIs are still using the security group (tasks, ALB, or cache not yet fully deleted). Wait a few minutes and retry; use aws ec2 describe-network-interfaces --filters Name=group-id,Values=$TASK_SG to see what is using it.

ResourceInUse: Target group … is currently in use by a listener or a rule

Delete the ALB (or the listener/rule) first, wait for load-balancers-deleted, then delete the target group.

ClusterContainsServicesException / ClusterContainsTasksException

The cluster still has services or tasks (including standalone tasks started with run-task). Use delete-service --force and wait for INACTIVE, or stop-task.

Recreating a secret with the same name fails: You can't create this secret because a secret with this name is already scheduled for deletion

Deletion has a recovery window by default. Restore it with restore-secret, or add --force-delete-without-recovery when deleting.

DeleteConflict: Cannot delete entity, must detach all policies first

The IAM role still has attached managed policies or inline policies: list them with list-attached-role-policies / list-role-policies and remove each one.

or score ≥ 70% on the Quiz

Command Cheat Sheet (Hour 4 · AWS)

AWS CLI v2 · ECR · ECS · Task definitions · ALB · Secrets · Logs · ECS Exec · EKS

Setup

aws configure sso                       # profile docker-lab
aws sso login --profile docker-lab
source ~/hour4-aws.env
aws sts get-caller-identity
aws ecs create-cluster --cluster-name $CLUSTER

ECR

aws ecr create-repository --repository-name myapp --image-tag-mutability IMMUTABLE
aws ecr get-login-password | docker login --username AWS --password-stdin $ECR   # 12 hours
docker buildx build --platform linux/amd64,linux/arm64 -t $ECR/myapp:1.1 --push .
aws ecr put-registry-scanning-configuration --scan-type BASIC \
  --rules '[{"repositoryFilters":[{"filter":"*","filterType":"WILDCARD"}],"scanFrequency":"SCAN_ON_PUSH"}]'
aws ecr describe-image-scan-findings --repository-name myapp --image-id imageTag=1.1
aws ecr put-lifecycle-policy --repository-name myapp --lifecycle-policy-text file://lifecycle.json
aws ecr create-pull-through-cache-rule --ecr-repository-prefix docker-hub \
  --upstream-registry-url registry-1.docker.io --credential-arn <ecr-pullthroughcache/… ARN>

Task definition · Service

aws ecs register-task-definition --cli-input-json file://taskdef.json
aws ecs create-service --cluster $CLUSTER --service-name myapp --task-definition myapp \
  --desired-count 2 --launch-type FARGATE \
  --network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$TASK_SG],assignPublicIp=ENABLED}" \
  --load-balancers "targetGroupArn=$TG_BLUE,containerName=web,containerPort=5000" \
  --health-check-grace-period-seconds 30 --enable-execute-command \
  --deployment-configuration "minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}"
aws ecs wait services-stable --cluster $CLUSTER --services myapp
aws ecs update-service --cluster $CLUSTER --service myapp --task-definition myapp:3
aws ecs update-service --cluster $CLUSTER --service myapp --force-new-deployment

ALB · Security groups

aws ec2 authorize-security-group-ingress --group-id $ALB_SG --protocol tcp --port 80 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id $TASK_SG --protocol tcp --port 5000 --source-group $ALB_SG
aws elbv2 create-target-group --name tg-myapp-blue --protocol HTTP --port 5000 --vpc-id $VPC_ID \
  --target-type ip --health-check-path /healthz
aws elbv2 create-rule --listener-arn $LISTENER --priority 10 --conditions Field=path-pattern,Values='/*' \
  --actions Type=forward,TargetGroupArn=$TG_BLUE
aws elbv2 describe-target-health --target-group-arn $TG_BLUE

Secrets · Cache

aws secretsmanager create-secret --name myapp/redis-password --secret-string "$PW"
aws ssm put-parameter --name /myapp/banner --type String --value hello
# Task definition: "secrets":[{"name":"REDIS_PASSWORD","valueFrom":"<secret ARN>"}]
# Grant permissions on the execution role: secretsmanager:GetSecretValue / ssm:GetParameters
aws elasticache create-user --user-id myapp-default --user-name default --engine VALKEY --passwords "$PW" --access-string "on ~* +@all"
aws elasticache create-user-group --user-group-id myapp-ug --engine VALKEY --user-ids myapp-default
aws elasticache create-serverless-cache --serverless-cache-name myapp-cache --engine valkey --user-group-id myapp-ug

Deployments · Scaling

aws ecs describe-services --cluster $CLUSTER --services myapp \
  --query 'services[0].deployments[].[status,rolloutState,rolloutStateReason]'
aws ecs update-service … --deployment-configuration "strategy=BLUE_GREEN,maximumPercent=200,minimumHealthyPercent=100,bakeTimeInMinutes=5" \
  --load-balancers "targetGroupArn=$TG_BLUE,containerName=web,containerPort=5000,advancedConfiguration={alternateTargetGroupArn=$TG_GREEN,productionListenerRule=$PROD_RULE,roleArn=$INFRA_ROLE}"
aws ecs list-service-deployments --cluster $CLUSTER --service myapp
aws application-autoscaling register-scalable-target --service-namespace ecs \
  --scalable-dimension ecs:service:DesiredCount --resource-id service/$CLUSTER/myapp --min-capacity 2 --max-capacity 6
aws application-autoscaling put-scaling-policy … --policy-type TargetTrackingScaling --target-tracking-scaling-policy-configuration file://tt.json

Logs · Troubleshooting · ECS Exec

aws ecs describe-services --cluster $CLUSTER --services myapp --query 'services[0].events[:10].message'
aws ecs list-tasks --cluster $CLUSTER --service-name myapp --desired-status STOPPED
aws ecs describe-tasks --cluster $CLUSTER --tasks $T --query 'tasks[].[stoppedReason,containers[].exitCode]'
aws logs tail /ecs/myapp --follow
aws logs start-query --log-group-name /ecs/myapp --start-time $(date -d '-30 min' +%s) --end-time $(date +%s) \
  --query-string 'fields @timestamp,@message | filter @message like /ERROR/ | limit 20'
aws ecs execute-command --cluster $CLUSTER --task $T --container web --interactive --command "/bin/sh"

EKS

eksctl create cluster --name=eks-lab --region=$AWS_REGION --enable-auto-mode
kubectl apply -f k8s.yaml; kubectl get pods -o wide; kubectl describe pod <pod>
kubectl logs deploy/myapp --previous; kubectl port-forward svc/myapp 8080:80
kubectl set image deploy/myapp web=$ECR/myapp:1.3; kubectl rollout undo deploy/myapp
eksctl delete cluster --name=eks-lab --region=$AWS_REGION --wait

Cleanup (in order)

aws ecs update-service --cluster $CLUSTER --service myapp --desired-count 0
aws ecs delete-service --cluster $CLUSTER --service myapp --force
aws ecs delete-cluster --cluster $CLUSTER
aws elbv2 delete-load-balancer --load-balancer-arn $ALB_ARN; aws elbv2 delete-target-group --target-group-arn $TG_BLUE
aws elasticache delete-serverless-cache --serverless-cache-name myapp-cache
aws ecr delete-repository --repository-name myapp --force
aws secretsmanager delete-secret --secret-id myapp/redis-password --force-delete-without-recovery
aws logs delete-log-group --log-group-name /ecs/myapp
# Then: IAM roles → security groups; check for leftovers: resourcegroupstaggingapi get-resources

Capstone Lab + Final Quiz

Complete an end-to-end AWS cloud release from scratch
After class ≈ 45 minIncurs small charges
TaskIn ca-central-1 of your lab account, using only the CLI, complete the following:
Create an IMMUTABLE ECR repository with scan on push enabled; build and push myapp:2.0 (amd64 + arm64) with buildx and read the scan results; configure a lifecycle policy that cleans up only sha-* and untagged images.
Create the execution role, the task role (with ECS Exec permissions), the security group chain (ALB:80 ← 0.0.0.0/0; task:5000 ← ALB SG), the ALB, the target group (ip, /healthz), the listener, and the production rule.
Store the Redis password in Secrets Manager and create ElastiCache Serverless (Valkey, RBAC user group); the execution role can read only that secret.
Register a task definition (512/1024, ARM64, password injected via secrets, container healthCheck, awslogs), create a 2-task service (circuit breaker + rollback, ECS Exec enabled), access it through the ALB, and see the counter increment.
Circuit breaker rollback drill: deploy myapp:2.1-bad, which exits immediately on start, watch rolloutState change to FAILED and the automatic rollback; then deploy myapp:2.1 normally.
Configure CPU 50% target tracking (2–6 tasks), run a load test, and record the scale-out activity; use Logs Insights to count request log entries per 5 minutes over the past 30 minutes.
Run the cleanup script and use the tagging API to confirm no resources are left behind.
Acceptance checklist

Open-ended self-check

1. Who uses the task execution role, and who uses the task role?

The execution role is for the ECS/Fargate agent: pulling ECR images, writing logs, and retrieving secrets. The task role is for the application code in the container to call AWS APIs (and for the ssmmessages channel used by ECS Exec).

2. Why must the target group for Fargate be of type ip?

Fargate tasks use the awsvpc network mode: each task has its own ENI and private IP, and there is no EC2 instance to register.

3. After a password in Secrets Manager is rotated, why does the app still use the old value? What should you do?

ECS injects secrets only when a container starts; use update-service --force-new-deployment to start new tasks. Cache password rotation should use a dual-password transition.

4. How does a rolling update with desired=2, min=100%, max=200% proceed?

It first starts 2 new tasks (4 in total), then stops the 2 old tasks once the new ones are healthy; at least 2 healthy tasks are running throughout.

5. What is the biggest difference between ECS native blue/green and rolling updates?

Blue/green first scales green up fully without production traffic; after validation, it shifts all traffic at once by changing the production listener rule, and keeps blue during the bake time for rollback in seconds. In a rolling update, old and new tasks serve traffic at the same time.

6. A task stopped with stoppedReason CannotPullContainerError … i/o timeout, and the task is in a private subnet. What might be missing?

A NAT gateway, or ECR api/dkr interface endpoints + an S3 gateway endpoint (image layers are stored in S3).

7. Can App Runner still be used for new projects?

No. It has not accepted new customers since 2026-04-30 (existing customers can keep using it, with no new features). AWS recommends ECS Express Mode.

Final Quiz (12 questions)

Sources and version notes

Verified on: 2026-11-15 (all official pages below were read on that date)
TopicVerified findingSource (date read)
App Runner statusNo longer accepts new customers as of 2026-04-30; existing customers can keep using it (including creating new services); AWS continues to invest in security and availability but plans no new features; recommended migration path is ECS Express Mode (shift traffic gradually with Route 53 weighted routing)AWS App Runner availability change (2026-11-15)
ECS Express ModeRequires an image, a task execution role and an infrastructure role; creates a Fargate service, an ALB with TLS (can be shared), auto scaling, logging and networking; no additional charge; CLI: aws ecs create-express-gateway-service (default 1 vCPU/2 GB)Express Mode overview, CLI getting started (2026-11-15)
ECR authenticationGetAuthorizationToken tokens are valid for 12 hours and carry the same permissions as the IAM principal that obtained them; the username is AWSPrivate registry authentication (2026-11-15)
ECR tag mutabilityWith IMMUTABLE, pushing a duplicate tag returns ImageTagAlreadyExistsException; IMMUTABLE_WITH_EXCLUSION / MUTABLE_WITH_EXCLUSION filters are also available; MUTABLE is recommended for pull through cache repositoriesImage tag mutability (2026-11-15)
ECR scanningBasic scanning (AWS native technology, OS CVEs, on push/manual, results via DescribeImageScanFindings) and enhanced scanning (Inspector, OS + language packages, on push/continuous); registry-level configuration is recommendedImage scanning, Enhanced scanning (2026-11-15)
ECR lifecyclerulePriority/selection/action; countType includes imageCountMoreThan, sinceImagePushed, sinceImagePulled, sinceImageTransitioned; action expire / transition (archive)Lifecycle policy examples (2026-11-15)
Pull through cacheThe Docker Hub upstream registry-1.docker.io requires credentials; secret name prefix ecr-pullthroughcache/, same account and same RegionCreating a pull through cache rule (2026-11-15)
Fargate sizesCPU/memory combination table (256 → 32768); 8/16/32 vCPU require Linux platform version 1.4.0+; Fargate always uses awsvpc; supports X86_64 and ARM64Fargate task definition differences (2026-11-15)
Secret injectionInjected at container start, so updates require new tasks/a forced new deployment; whole secrets need platform version 1.3.0+, JSON keys/versions need 1.4.0+; the execution role needs GetSecretValue / ssm:GetParameters / kms:DecryptSecrets Manager env vars, Task execution role (2026-11-15)
Deployment circuit breakerTwo-stage detection; resetOnHealthyTask; thresholdConfiguration: BOUNDED_PERCENT (default 50, limits 3–200) / UNBOUNDED_PERCENT / COUNT; rolls back to the most recent COMPLETED deployment; ECS deployment controller onlyDeployment circuit breaker (2026-11-15)
ECS native blue/greenstrategy=BLUE_GREEN, bakeTimeInMinutes; advancedConfiguration: alternateTargetGroupArn, productionListenerRule, testListenerRule (optional), roleArn; lifecycle stages and hooks; production traffic shifts all at once; each stage up to 24 hours, pause hooks up to 14 days, 30 days overall; LINEAR and CANARY are also availableBlue/green deployments, Workflow, ALB resources (2026-11-15)
ECS Exec--enable-execute-command; four ssmmessages permissions on the task role; requires the Session Manager plugin; not supported with a read-only root file system; sessions time out after 20 minutes idle; initProcessEnabled recommendedECS Exec, Task IAM role (2026-11-15)
ElastiCache Serverless (Valkey)create-serverless-cache --engine valkey; VPC (default) or public connection type; Serverless supports RBAC only; VALKEY users/user groups; encryption in transit always on; 6379 primary / 6380 readerCreate a Valkey serverless cache in a VPC, RBAC, Troubleshooting (2026-11-15)
EKS Auto Modeeksctl create cluster --name=… --enable-auto-mode, eksctl ≥ 0.195.0; default node pools general-purpose and system; node role policies AmazonEKSWorkerNodeMinimalPolicy + AmazonEC2ContainerRegistryPullOnlyAuto Mode with eksctl, Auto Mode with AWS CLI (2026-11-15)

Mapping to Lesson 3 (Azure)

Modules map one to one to Lesson 3: ACA → ECS Fargate, ACR → ECR, Key Vault → Secrets Manager / SSM, Azure Managed Redis → ElastiCache Serverless (Valkey), revisions/traffic splitting → rolling + circuit breaker / native blue/green, Log Analytics/KQL → CloudWatch Logs/Logs Insights, AKS → EKS. app.py is the same as in Lesson 3 (REDIS_HOST/PORT/PASSWORD/SSL environment variables + /healthz), so the same image runs on both clouds. This lesson's variables file is ~/hour4-aws.env, which doesn't interfere with Lesson 5's ~/hour5.env.

Video verification notes

All video links were verified for title and channel on 2026-11-15 via YouTube oEmbed (oEmbed doesn't return dates or durations, so those are marked "unverified"). Verified: AWS Events (re:Invent 2023 CON405, CON318; re:Invent 2024 SVS330, KUB204-NEW; re:Invent 2025 CNS342, CNS416, CNS354), AWS Developers (Fargate modern application stack Tech Talk, complete guide to ECS blue/green, EKS Auto Mode, ElastiCache for Valkey), Amazon Web Services (ECR Explained, ElastiCache Serverless, Container Insights, CloudWatch natural language queries), Containers from the Couch (pull through cache, Circuit Breakers, ECS Exec, Fargate cost optimization), Be A Better Dev, Bret Fisher, TechWorld with Nana. No verified video dedicated to ECS secret injection was found, nor an official video directly comparing ECS/EKS/App Runner/Lambda.

Known limitations

  • The lab commands were written from the official documentation and the AWS CLI reference and have not been run one by one in a real account; expected outputs (including stoppedReason and service event text) are examples, so rely on your actual output.
  • This lesson doesn't list specific unit prices (except the EKS control plane at 0.10 USD/hour); for costs, refer to the official ca-central-1 pricing pages and the AWS Pricing Calculator.
  • The following details are marked "refer to the official documentation": whether switching from ROLLING to BLUE_GREEN requires first adding the alternate target group to the production rule (modify-rule), how an ALBRequestCountPerTarget scaling policy follows target group switches in blue/green mode, the exact release date of ECS native blue/green, ElastiCache Serverless compatibility details for non-cluster clients and RBAC dual-password rotation, the load balancer class syntax for EKS Auto Mode, how long STOPPED tasks are retained, Inspector free trial terms, and the JSON field names of the pull through cache secret.
  • ECS native blue/green, linear and canary deployments and Express Mode are all relatively new features whose CLI parameters may keep evolving, so use the latest AWS CLI v2.