DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

AWS for DevOpsLesson 11 of 17
Your progress · 0%
On this page
  1. Three layers, three responsibilities
  2. ECR: the image boundary
  3. ECS task definitions
  4. Fargate task and service
  5. ECS or EKS?
  6. ECS capacity providers
  7. Task definitions: the runtime contract
  8. Service discovery and Service Connect
  9. Put a service behind an ALB
  10. Deployments and automatic rollback
  11. Scale, inspect and choose the platform
↖ Course roadmap
Lesson 11 · Containers

Containers on AWS: ECR, ECS and EKS

Store an image in ECR, run a Fargate task on ECS, and choose EKS only when Kubernetes is a real requirement.

30 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 4 complete

Three layers, three responsibilities

Before managed container services, running a containerised app on AWS looked like this. You launched a few EC2 servers, installed Docker on each one, copied the image over and ran docker run. Then the real work started. A container crashed at 2 a.m. and nobody restarted it. Traffic doubled and someone had to launch another server by hand. A security patch meant logging in to every server, one by one. The team spent more time looking after servers than shipping the app.

AWS splits that job into three services, each doing one thing:

ServiceThe question it answersThink of it as
ECR (Elastic Container Registry)Where do my images live?A private Docker Hub inside your AWS account
ECS (Elastic Container Service)How many copies run, and who restarts them?The manager that keeps the right number of containers running
FargateWhich machine do they run on?Servers you never see, patch or scale

Here is how they work together. You push an image to ECR. You tell ECS "run two copies of this image with 0.25 vCPU each". ECS asks Fargate for capacity, starts the containers, and keeps watching them. If one dies, ECS starts a replacement. You never log in to a server.

Because they are separate services, you secure and monitor each one separately: who can push images (ECR), who can change what runs (ECS), and what the running app can access (the task's IAM role, covered below).

In this lesson you'll store an image, describe how it should run, run it on Fargate, connect two services, put them behind a load balancer and watch a bad deployment roll itself back.

(1) ECS starts with a cluster boundary. A production cluster usually has services; this lesson runs one short task for inspection.© Screenshot: DevOps Academy

(1) ECS starts with a cluster boundary. A production cluster usually has services; this lesson runs one short task for inspection.© Screenshot: DevOps Academy

ECR: the image boundary

The problem it solves. Your servers need to download your image from somewhere. Docker Hub is public by default and rate-limited, and you don't want your company's images there. You need a private registry that your AWS services can pull from quickly and securely.

What it is. ECR is that private registry. Each repository holds the versions of one image, for example web or api.

How you use it. From your laptop or a CI pipeline, the flow is always: log in, tag, push.

# 1. Create a repository once. Immutable tags and scanning are explained below.
aws ecr create-repository --repository-name web \
  --image-tag-mutability IMMUTABLE \
  --image-scanning-configuration scanOnPush=true

# 2. Log Docker in to your registry (the token lasts 12 hours).
aws ecr get-login-password --region ap-south-1 |
  docker login --username AWS --password-stdin 123456789012.dkr.ecr.ap-south-1.amazonaws.com

# 3. Tag the local image with the repository address, then push it.
docker tag web:1.4.0 123456789012.dkr.ecr.ap-south-1.amazonaws.com/web:1.4.0
docker push 123456789012.dkr.ecr.ap-south-1.amazonaws.com/web:1.4.0

Three settings are worth turning on from day one:

  • Immutable tags. Once web:1.4.0 is pushed, nobody can push a different image under the same tag. Without this, "1.4.0" could mean two different things on two different days.
  • Scan on push. ECR checks each new image for known vulnerabilities in its packages.
  • A lifecycle policy. Every push adds an image, and you pay for storage. A rule like "delete untagged images older than 14 days" keeps the repository tidy:
{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Remove untagged images after 14 days",
      "selection": {
        "tagStatus": "untagged",
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 14
      },
      "action": { "type": "expire" }
    }
  ]
}

Tag or digest? A tag like 1.4.0 is a name that points at an image. A digest like sha256:3f1a… is the image's fingerprint and can never point anywhere else. Deploy by digest (or by an immutable tag) so the image you tested is exactly the image that runs.

Common mistake: deploying :latest. When a task restarts next week, it may pull a different image than the one you tested, and you won't know which version is running.

The mission in this lesson uses the public nginx image, so you don't need to build or push anything. In a real pipeline, CI pushes to ECR and the deployment points at that exact image.

ECS task definitions

A task definition is the recipe for running your container. It says which image to use, how much CPU and memory to give it, which port it listens on, where its logs go and which IAM roles it gets. ECS reads the recipe every time it starts a copy.

Two things about it trip people up:

  1. It's versioned. You never edit a task definition in place. Each change creates a new revision (academy-web:1, academy-web:2, …), and a service is pointed at one revision. That's what makes rolling back possible: point the service back at the previous revision.
  2. It has two different roles, and they're for different callers:
RoleWho uses itTypical permissions
Execution roleECS itself, before your code startsPull the image from ECR, write logs to CloudWatch, read secrets to inject
Task roleYour application code, while it runsWhatever the app needs: read an S3 bucket, write to a DynamoDB table

If your app gets "AccessDenied" calling S3, check the task role. If the task never starts because the image can't be pulled, check the execution role. Keep both as small as possible. The full set of fields is explained in "Task definitions: the runtime contract" below.

Fargate task and service

A task is one running copy of a task definition: one or more containers started together, sharing the same network and lifetime. If a task stops, it stays stopped.

A service is what keeps tasks running. You tell it a desired count, for example 2, and it works like a thermostat: it keeps checking how many healthy tasks exist and starts or stops tasks until the number matches. If a task crashes, the service notices and starts a new one. A service also handles deployments, registers tasks with a load balancer and scales the count up and down.

UseWhen
A standalone taskShort jobs that finish: a database migration, a nightly report, this lesson's mission
A serviceAnything that must stay up: a website, an API, a queue worker

The mission runs one standalone task with no service, so you can watch a single task start, run and stop. A real web app runs as a service behind a load balancer. Put its tasks in private subnets, and allow inbound traffic only from the load balancer's security group, so nothing on the internet can reach a task directly.

A public IP is for this short exercise only

The mission assigns a public IP so a task in a practice subnet can pull its public image. It exposes no application port to the internet. Production workloads should normally pull through private networking and keep tasks in private subnets with controlled egress.

ECS or EKS?

AWS has two ways to run containers at scale, and teams often pick the wrong one.

  • ECS is AWS's own scheduler. You describe tasks and services in AWS terms, and AWS runs the control plane for free. There is no cluster software to upgrade.
  • EKS is managed Kubernetes. AWS runs the Kubernetes control plane for you (for an hourly fee), and you use standard Kubernetes tools: kubectl, Helm charts, operators.
QuestionLean to ECSLean to EKS
Does the team already know Kubernetes?NoYes
Do you need Kubernetes tools (Helm charts, operators) or to run the same setup on other clouds?NoYes
How much platform work can you take on?Little: you want to ship appsEnough to own cluster upgrades, add-ons and their policies
What's running?A handful of web services and workersA large platform shared by many teams

A good rule: start with ECS on Fargate unless you have a concrete reason for Kubernetes. "We use containers" is not that reason. ECS runs containers perfectly well. EKS is worth its extra moving parts (version upgrades every few months, node management, Kubernetes RBAC mapped to IAM) when you'll actually use what Kubernetes adds.

Production controls

Pin image digests, scan and sign images, use task roles instead of keys, send logs to CloudWatch, set CPU and memory limits, define health checks, restrict security groups, encrypt secrets, and deploy through a service with a rollback strategy.

ECS and EKS: What Works Best for Your Project? | AWS ECS vs EKS | KodeKloudKodeKloud · Watch on YouTube ↗

ECS capacity providers

The problem it solves. Every task needs CPU and memory somewhere. ECS has to decide where each task runs, and the right answer depends on the workload: a payment API must never be interrupted, but a batch job that resizes images can be restarted and should be as cheap as possible.

What it is. A capacity provider is a pool of compute that ECS can place tasks on:

Capacity providerWhat it isGood for
FARGATEAWS-managed capacity, billed per taskMost services: nothing to patch or scale
FARGATE_SPOTThe same, but much cheaper; AWS can stop the task with a two-minute warningWork that can be retried: batch jobs, queue workers, test environments
An EC2 provider (an Auto Scaling group)Your own instances that ECS places tasks onGPUs, special instance types, or very steady load where reserved instances are cheaper

How you use it. A service gets a capacity provider strategy: how to split its tasks between providers. base is how many tasks always go to that provider first; weight splits the rest.

"capacityProviderStrategy": [
  { "capacityProvider": "FARGATE", "base": 1, "weight": 1 },
  { "capacityProvider": "FARGATE_SPOT", "weight": 3 }
]

With a desired count of 9, the first task goes to FARGATE (the base). The other 8 are split 1:3, so 2 more on FARGATE and 6 on FARGATE_SPOT. If Spot capacity is taken back, you still have 3 tasks on regular Fargate while the service replaces the rest.

Common mistake: putting a latency-sensitive or stateful service entirely on Spot. Keep a base on regular capacity, and keep Spot for work that tolerates interruption.

The cluster is active. It has two active services. Four tasks are running. The api and web services are listed.© Screenshot: DevOps Academy

The cluster is active. It has two active services. Four tasks are running. The api and web services are listed.© Screenshot: DevOps Academy
Amazon ECS: ECS Capacity Provider Overview | Amazon Web ServicesAmazon Web Services · Watch on YouTube ↗

Task definitions: the runtime contract

Here is a small but complete task definition for the api service, with the important lines explained below it:

{
  "family": "academy-api",
  "requiresCompatibilities": ["FARGATE"],
  "networkMode": "awsvpc",
  "cpu": "256",
  "memory": "512",
  "executionRoleArn": "arn:aws:iam::123456789012:role/academy-ecs-exec-role",
  "taskRoleArn": "arn:aws:iam::123456789012:role/academy-ecs-task-role",
  "containerDefinitions": [
    {
      "name": "api",
      "image": "123456789012.dkr.ecr.ap-south-1.amazonaws.com/api:1.4.0",
      "essential": true,
      "portMappings": [
        { "name": "api", "containerPort": 80, "protocol": "tcp", "appProtocol": "http" }
      ],
      "healthCheck": {
        "command": ["CMD-SHELL", "curl -f http://localhost/ || exit 1"],
        "interval": 15,
        "retries": 3
      },
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/academy-api",
          "awslogs-region": "ap-south-1",
          "awslogs-stream-prefix": "api"
        }
      }
    }
  ]
}
  • family names the recipe. Each registration adds a revision: academy-api:1, :2, …
  • networkMode: awsvpc gives every task its own network card (an ENI) with its own private IP and its own security group, just like a small EC2 instance. Fargate always uses it.
  • cpu and memory are for the whole task. 256 CPU units is a quarter of a vCPU; 512 is 512 MiB. Fargate only accepts certain pairs, so check the size table when you change one.
  • portMappings says the container listens on port 80. The name (api) is how a load balancer or Service Connect refers to this port, as you'll see in the next sections.
  • healthCheck runs inside the container, so the tool it calls (curl here) must exist in the image. A process can be alive but stuck; if the check fails three times in a row, ECS marks the task unhealthy and the service replaces it.
  • logConfiguration with awslogs sends everything the container prints to CloudWatch Logs. (FireLens is the alternative when logs must be filtered or sent somewhere else, like OpenSearch.)
  • Secrets (database passwords, API keys) go in a secrets list that points at Secrets Manager or SSM Parameter Store. ECS injects them as environment variables when the task starts. Never bake them into the image or write them in plain environment values.

The two role lines are the ones from the table above. In the practice setup, the web task only needs the execution role. The api task also has academy-ecs-task-role, because ECS Exec (a shell into the running task, covered at the end) runs as the task's identity.

The execution role is visible. The network mode is awsvpc. The task uses 0.25 vCPU and 0.5 GiB. The container definition is web. The task memory graph shows the reservation.© Screenshot: DevOps Academy

The execution role is visible. The network mode is awsvpc. The task uses 0.25 vCPU and 0.5 GiB. The container definition is web. The task memory graph shows the reservation.© Screenshot: DevOps Academy

(1) The api task has an application task role. (2) The execution role is separate. (3) awsvpc supplies task networking. (4) CPU and memory are explicit. (5) The container is the api service.© Screenshot: DevOps Academy

(1) The api task has an application task role. (2) The execution role is separate. (3) awsvpc supplies task networking. (4) CPU and memory are explicit. (5) The container is the api service.© Screenshot: DevOps Academy
Amazon ECS: Task and Task Definition Overview | Amazon Web ServicesAmazon Web Services · Watch on YouTube ↗

Service discovery and Service Connect

The problem. The web service needs to call the api service. Easy on your laptop: you call http://localhost:8080. On ECS it's harder, because every api task gets a new private IP whenever it starts. Deployments, scaling and crash replacements all change the IPs. If you write an IP into the web app's config, it breaks on the next deployment.

You need a way for web to say "send this to api" and have it reach a healthy api task, whatever its IP is today. ECS gives you two ways to do that, built on AWS Cloud Map, a registry (think of it as a phone book) of service names and the IPs currently behind them.

Option 1: service discovery (DNS names)

With service discovery, ECS writes each api task's IP into Cloud Map as the task starts, and removes it when the task stops or fails its health check. Cloud Map publishes those IPs as DNS records in a private hosted zone, which only your VPC can see.

What happens when web calls the api:

  1. Web looks up api.academy.local, the service name plus the namespace name.
  2. DNS answers with the private IPs of the healthy api tasks (up to eight of them).
  3. Web connects to one of those IPs directly.

You switch it on with serviceRegistries in the ECS service, pointing at a Cloud Map service:

"serviceRegistries": [
  { "registryArn": "arn:aws:servicediscovery:ap-south-1:123456789012:service/srv-EXAMPLE" }
]

It's simple, and any program that can do a DNS lookup can use it. But your application does all the remaining work. It has to pick an IP, retry when a task has just died, and cope with DNS caching: many runtimes keep an old answer for minutes or even hours, so they keep calling a task that's already gone. And you get no metrics about the calls between services.

Option 2: Service Connect (a managed proxy)

Service Connect also uses a Cloud Map namespace, but your app no longer does the lookup itself. ECS adds a small proxy container to every task in the service. It's called a sidecar because it rides along next to your app. It isn't in your task definition; ECS adds and manages it.

What happens when web calls http://api:80/:

  1. The web app sends the request to the short name api. It doesn't know any IPs.
  2. The Service Connect proxy inside the same web task catches the request.
  3. The proxy already holds the current list of healthy api tasks. It reads Cloud Map's API directly, not DNS, so there's no stale cache.
  4. It picks the next api task in turn (round-robin) and forwards the request.
  5. If that attempt fails, it retries, up to 2 times, each time on a different api task.
  6. If one api task keeps failing (5 failures in 30 seconds), the proxy stops sending to it for 30 to 300 seconds, so one bad task doesn't hurt every caller.
  7. Both proxies record request counts, errors and latency, which you can see in CloudWatch.

The web code stays exactly the same: it calls http://api:80/, and Service Connect makes that name work.

The app only knows the name api. Its own proxy finds a healthy task, balances requests and retries.© Diagram: DevOps Academy

The app only knows the name api. Its own proxy finds a healthy task, balances requests and retries.© Diagram: DevOps Academy

How to set up Service Connect

You need three pieces. The names have to match, which is the most common source of mistakes.

1. Name the port in the api task definition. You already saw this above: "portMappings": [{ "name": "api", "containerPort": 80, "appProtocol": "http" }]. Setting appProtocol to http also gives you HTTP metrics, such as counts of 5xx errors.

2. Make the api service a "client-server" service. It joins the namespace and publishes the named port under a short name:

"serviceConnectConfiguration": {
  "enabled": true,
  "namespace": "academy",
  "services": [
    {
      "portName": "api",
      "discoveryName": "api",
      "clientAliases": [{ "port": 80, "dnsName": "api" }]
    }
  ]
}
  • portName must match the name in the task definition's port mapping.
  • discoveryName is the service's name in Cloud Map.
  • clientAliases is the name and port that callers use: http://api:80.

3. Make the web service a "client" service. It only needs to join the same namespace, so its proxy learns about api:

"serviceConnectConfiguration": { "enabled": true, "namespace": "academy" }

The academy namespace can be set as the cluster's default, so new services pick it up automatically.

Which one should you use?

Service discovery (DNS)Service Connect
How the caller finds tasksDNS lookup in your appLocal proxy, no DNS lookup
Retries, avoiding bad tasksYour codeBuilt in
Traffic metrics between servicesNoneBuilt in, in CloudWatch
Extra resources per taskNoneA proxy container (see below)
Callers outside ECS (Lambda, EC2)Yes, anything in the VPC can resolve the nameNo, only ECS services in the namespace

Use Service Connect for ECS services that call each other. It's the better default. Use plain service discovery when something outside ECS, such as an EC2 instance or a Lambda function, must find your tasks by name.

Mistakes to watch for

  • The client still can't resolve api. A running task only learns about endpoints that existed when it started. After you add Service Connect to api, redeploy web too.
  • portName doesn't match. The service config's portName must equal the port mapping's name exactly.
  • No room for the proxy. The proxy shares the task's CPU and memory. AWS recommends adding 256 CPU units and at least 64 MiB to each task that uses Service Connect.
  • A security group blocks it. The api tasks' security group must allow the container port (80 here) from the web tasks.
  • Unsupported deployment types. Service Connect doesn't work with CodeDeploy blue/green deployments or with standalone tasks, only with services.
Connect Multiple ECS Services Without Extra Infrastructure | Service Connect #aws #dockerPrograamer (A Programmer) · Watch on YouTube ↗

Put a service behind an ALB

The problem. Users on the internet need to reach your web tasks, but those tasks have private IPs that change on every deployment, and there are several of them. You need one stable address that spreads traffic across whichever tasks are healthy right now.

What it is. An Application Load Balancer (ALB) is that stable address. It has a DNS name (academy-ecs-alb-….elb.amazonaws.com) and sends each request to a healthy task in a target group, a list of task IPs.

How ECS and the ALB work together:

  1. The ECS service is linked to a target group, using the container name and port from the task definition.
  2. When the service starts a task, ECS registers the task's IP in the target group.
  3. The ALB health-checks it (for example GET / every 30 seconds). Only tasks that pass get traffic.
  4. When a task is stopped, ECS first deregisters it, so requests already in flight finish before the task goes away.

You don't register targets by hand; the service does it. Listener rules can route by path: here / goes to the web service and /api/* goes to the api service, both behind one ALB.

Security groups, the part people get wrong: use two of them.

  • The ALB's security group allows ports 80 and 443 from the internet.
  • The tasks' security group allows the container port only from the ALB's security group, not from 0.0.0.0/0.

That way the only way in is through the load balancer, which also gives you one place for HTTPS certificates and a web application firewall later.

The live practice ALB returned real responses from both services:

$ curl http://academy-ecs-alb-981205580.ap-south-1.elb.amazonaws.com/
web ok from ip-172-31-8-246.ap-south-1.compute.internal
$ curl http://academy-ecs-alb-981205580.ap-south-1.elb.amazonaws.com/api/
{"service":"api","version":"v1","host":"ip-172-31-13-164.ap-south-1.compute.internal"}
curl http://academy-ecs-alb-981205580.ap-south-1.elb.amazonaws.com/
  • curlmake an HTTP request
Amazon ECS Load Balancing | ALB Integration with Fargate Launch Type | Hands-On AWS Tutorial | #09Learn It Right Way · Watch on YouTube ↗

Deployments and automatic rollback

The problem. You deploy a new version and something is wrong with it. Maybe the image tag doesn't exist, or the app crashes on start. Without protection, ECS keeps trying to start the broken tasks, sometimes for hours, while you wonder why the deploy is stuck.

How a rolling deployment works. When you point a service at a new task definition revision, ECS replaces old tasks with new ones in steps. Two settings control the pace:

  • minimumHealthyPercent is how many tasks must stay healthy during the deploy. With 4 tasks and 100, ECS never goes below 4 healthy tasks, so it starts new ones before stopping old ones.
  • maximumPercent is how many tasks may run at once. With 4 tasks and 200, ECS can briefly run up to 8, old and new together.

The deployment circuit breaker watches the new tasks. If they keep failing to start or to pass health checks, it marks the deployment as failed. With rollback enabled, ECS automatically returns the service to the last revision that worked:

"deploymentConfiguration": {
  "minimumHealthyPercent": 100,
  "maximumPercent": 200,
  "deploymentCircuitBreaker": { "enable": true, "rollback": true }
}

To test this, the practice service was pointed at an image tag that doesn't exist. ECS recorded the real pull failure below. Repeated failures like this one are exactly what the circuit breaker counts before it rolls the service back:

(service api) was unable to place a task. Reason: CannotPullContainerError: pull image manifest has been retried 7 time(s): failed to resolve ref public.ecr.aws/nginx/nginx:does-not-exist: not found.

Rolling or blue/green? A rolling deploy replaces tasks gradually, so for a short time some users hit the old version and some the new. Blue/green (with CodeDeploy) starts a complete new set of tasks, then moves traffic over all at once or in steps, such as 10% first. You can test the new set before any user sees it, and switching back is instant. It needs a second target group and more setup. Use it when a brief mix of versions isn't acceptable, or when you want to shift traffic in controlled steps.

Circuit Breakers for Amazon ECSContainers from the Couch · Watch on YouTube ↗

Scale, inspect and choose the platform

Target tracking keeps a service metric near a target. The practice web service used ECS average CPU at 50 percent, with two to four tasks. Choose a target that protects latency and downstream capacity; scaling is not a substitute for backpressure.

ECS Exec opens a shell through Systems Manager without exposing SSH. It needs the task role's ssmmessages actions, the Session Manager plugin and a task launched with execute-command enabled. App Runner is a simpler managed web deployment when you bring a source repository or image and do not need ECS's task and network controls. EKS is the right boundary when Kubernetes APIs and ecosystem compatibility are requirements; it is not a default for every container.

The desired count is two and both tasks are running. The active task definition is shown. The health and deployment tabs are available for operations. The service reports completed tasks.© Screenshot: DevOps Academy

The desired count is two and both tasks are running. The active task definition is shown. The health and deployment tabs are available for operations. The service reports completed tasks.© Screenshot: DevOps Academy

The web service is the ALB-facing service. Its running task count is visible. Deployment controls are available. Health and events are separate operational views.© Screenshot: DevOps Academy

The web service is the ALB-facing service. Its running task count is visible. Deployment controls are available. Health and events are separate operational views.© Screenshot: DevOps Academy
Amazon ECS: ECS Auto Scaling Overview | Amazon Web ServicesAmazon Web Services · Watch on YouTube ↗
⌘
Mini mission

Run one disposable Fargate task

Create an ECR repository, define a small nginx task, run it on Fargate, inspect its state, then delete every temporary resource. No image is pushed in this mission; the task pulls a public image.

Input: AWS CLI credentials allowed to create and delete temporary ECR and ECS resourcesOutput: A RUNNING task followed by confirmed deletion of the task, cluster, repository and temporary execution role
Reveal one safe solution
$ export AWS_REGION=ap-south-1
$ export REPO="academy-containers-$RANDOM"
$ export CLUSTER="academy-fargate-$RANDOM"
$ export FAMILY="academy-nginx-$RANDOM"
$ export ROLE="academy-ecs-exec-$RANDOM"
$ export VPC=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true --query 'Vpcs[0].VpcId' --output text)
$ export SUBNET=$(aws ec2 describe-subnets --filters Name=vpc-id,Values="$VPC" --query 'Subnets[?DefaultForAz==`true`].SubnetId | [0]' --output text)
$ export SG=$(aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" --query 'SecurityGroups[?GroupName==`default`].GroupId | [0]' --output text)
$ aws ecr create-repository --repository-name "$REPO" --image-scanning-configuration scanOnPush=true
$ aws ecs create-cluster --cluster-name "$CLUSTER" --capacity-providers FARGATE
$ cat > trust.json <<'JSON'
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ecs-tasks.amazonaws.com"},"Action":"sts:AssumeRole"}]}
JSON
$ aws iam create-role --role-name "$ROLE" --assume-role-policy-document file://trust.json
$ aws iam attach-role-policy --role-name "$ROLE" --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
$ aws ecs register-task-definition --family "$FAMILY" --network-mode awsvpc --requires-compatibilities FARGATE --cpu 256 --memory 512 --execution-role-arn "arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/$ROLE" --container-definitions '[{"name":"web","image":"public.ecr.aws/docker/library/nginx:alpine","essential":true,"portMappings":[{"containerPort":80,"protocol":"tcp"}]}]'
$ TASK=$(aws ecs run-task --cluster "$CLUSTER" --task-definition "$FAMILY" --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[$SUBNET],securityGroups=[$SG],assignPublicIp=ENABLED}" --query 'tasks[0].taskArn' --output text)
$ aws ecs wait tasks-running --cluster "$CLUSTER" --tasks "$TASK"
$ aws ecs describe-tasks --cluster "$CLUSTER" --tasks "$TASK" --query 'tasks[0].{Status:lastStatus,Definition:taskDefinition,Started:startedAt}' --output table
-----------------------------------------------
|              DescribeTasks                    |
+----------+----------------------------------+
| Status   | RUNNING                          |
| Definition | ...:task-definition/academy-nginx |
+----------+----------------------------------+
$ aws ecs stop-task --cluster "$CLUSTER" --task "$TASK"
$ aws ecs wait tasks-stopped --cluster "$CLUSTER" --tasks "$TASK"
$ aws ecs deregister-task-definition --task-definition "$FAMILY":1
$ aws ecs delete-cluster --cluster "$CLUSTER"
$ aws ecr delete-repository --repository-name "$REPO" --force
$ aws iam detach-role-policy --role-name "$ROLE" --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
$ aws iam delete-role --role-name "$ROLE"
$ aws ecs describe-clusters --clusters "$CLUSTER" --query 'clusters' --output json
[]
$ aws ecr describe-repositories --repository-names "$REPO"
An error occurred (RepositoryNotFoundException) when calling the DescribeRepositories operation
aws ecr create-repository --repository-name "$REPO" --image-scanning-configuration scanOnPush=true
  • awsthe AWS command line
cat > trust.json <<'JSON'
  • catprint a file
  • >write output to a file, replacing it
aws ecs describe-tasks --cluster "$CLUSTER" --tasks "$TASK" --query 'tasks[0].{Status:lastStatus,Definition:taskDefinition,Started:startedAt}' --output table
  • --querypick fields from the JSON response
  • --outputoutput format

The output shape above is from the real practice-account run; account-specific identifiers are intentionally omitted. If a command fails, stop and inspect before repeating it. Confirm the task is STOPPED before deleting its cluster, and confirm both the repository and role are gone.

Try it yourself

0 of 4 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 7

What does an ECR repository store?

Go deeper

Official reading for this lesson

  • DocsAmazon ECR User GuideAWS Docs ↗
  • DocsAmazon ECS Developer GuideAWS Docs ↗
  • GuideAmazon ECS task definitionsAWS Docs ↗
  • DocsAWS FargateAWS Docs ↗
  • DocsAmazon EKS User GuideAWS Docs ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousManaged databases: RDS, DynamoDB, ElastiCacheNext lesson →Lambda: code without servers