# 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.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 11. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/11-containers

## What you will learn

- Explain what ECR, an ECS task definition, a task and a service each do.
- Run a small container on Fargate without managing EC2 hosts.
- Choose between ECS, Fargate, ECS on EC2 and EKS.
- Apply least privilege and private networking to container workloads.

## 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:

| Service                              | The question it answers                     | Think 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 |
| **Fargate**                          | Which 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.

> **Figure.** Amazon ECS Clusters page with the Create cluster control highlighted
>
> (1) ECS starts with a cluster boundary. A production cluster usually has services; this lesson runs one short task for inspection.

## 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.

```sh
# 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:

```json
{
  "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:

| Role               | Who uses it                          | Typical permissions                                                       |
| ------------------ | ------------------------------------ | ------------------------------------------------------------------------- |
| **Execution role** | ECS itself, before your code starts  | Pull the image from ECR, write logs to CloudWatch, read secrets to inject |
| **Task role**      | Your application code, while it runs | Whatever 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.

| Use                   | When                                                                                  |
| --------------------- | ------------------------------------------------------------------------------------- |
| A standalone **task** | Short jobs that finish: a database migration, a nightly report, this lesson's mission |
| A **service**         | Anything 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.

| Question                                                                                        | Lean to ECS                           | Lean to EKS                                                |
| ----------------------------------------------------------------------------------------------- | ------------------------------------- | ---------------------------------------------------------- |
| Does the team already know Kubernetes?                                                          | No                                    | Yes                                                        |
| Do you need Kubernetes tools (Helm charts, operators) or to run the same setup on other clouds? | No                                    | Yes                                                        |
| How much platform work can you take on?                                                         | Little: you want to ship apps         | Enough to own cluster upgrades, add-ons and their policies |
| What's running?                                                                                 | A handful of web services and workers | A 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.

> **Video.** [ECS and EKS: What Works Best for Your Project? | AWS ECS vs EKS | KodeKloud](https://www.youtube.com/watch?v=o73kDW0xqlg&t=1151s) (KodeKloud)

## 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 provider                           | What it is                                                                  | Good for                                                                               |
| ------------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `FARGATE`                                   | AWS-managed capacity, billed per task                                       | Most services: nothing to patch or scale                                               |
| `FARGATE_SPOT`                              | The same, but much cheaper; AWS can stop the task with a two-minute warning | Work that can be retried: batch jobs, queue workers, test environments                 |
| An **EC2** provider (an Auto Scaling group) | Your own instances that ECS places tasks on                                 | GPUs, 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.

```json
"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.

> **Figure.** ECS academy-ecs cluster overview with two services and four running tasks highlighted
>
> The cluster is active. It has two active services. Four tasks are running. The api and web services are listed.

> **Video.** [Amazon ECS: ECS Capacity Provider Overview | Amazon Web Services](https://www.youtube.com/watch?v=mVRhgze0gGU) (Amazon Web Services)

## Task definitions: the runtime contract

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

```json
{
  "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.

> **Figure.** ECS academy-web task definition showing execution role, awsvpc networking, CPU and memory
>
> 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.

> **Figure.** ECS academy-api task definition showing the task role, execution role, awsvpc and task size
>
> (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.

> **Video.** [Amazon ECS: Task and Task Definition Overview | Amazon Web Services](https://www.youtube.com/watch?v=5uJUmGWjRZY) (Amazon Web Services)

## 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:

```json
"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.

> **Figure.** The web task holds the web app and a Service Connect proxy added by ECS. 1: the app sends GET http://api:80/. 2: AWS Cloud Map keeps the proxy's list of healthy api tasks current. 3: the proxy forwards the request to the next api task in turn, task A. 4: if that fails, it retries on another task, task B. Each api task also has its own proxy in front of the api container.
>
> The app only knows the name api. Its own proxy finds a healthy task, balances requests and retries.

### 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:

```json
"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`:

```json
"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 tasks        | DNS lookup in your app                        | Local proxy, no DNS lookup             |
| Retries, avoiding bad tasks       | Your code                                     | Built in                               |
| Traffic metrics between services  | None                                          | Built in, in CloudWatch                |
| Extra resources per task          | None                                          | A proxy container (see below)          |
| Callers outside ECS (Lambda, EC2) | Yes, anything in the VPC can resolve the name | No, 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.

> **Video.** [Connect Multiple ECS Services Without Extra Infrastructure | Service Connect #aws #docker](https://www.youtube.com/watch?v=-ja4_D7eOz4) (Prograamer (A Programmer))

## 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:

```text
$ 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"}
```

> **Video.** [Amazon ECS Load Balancing | ALB Integration with Fargate Launch Type | Hands-On AWS Tutorial | #09](https://www.youtube.com/watch?v=3b1--mUhUhI) (Learn It Right Way)

## 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:

```json
"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:

```text
(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.

> **Video.** [Circuit Breakers for Amazon ECS](https://www.youtube.com/watch?v=Y2Ez9M7A95Y&t=1055s) (Containers from the Couch)

## 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.

> **Figure.** ECS api service health page showing two running tasks and a completed deployment
>
> 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.

> **Figure.** ECS web service health page with its deployment and task state
>
> 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.

> **Video.** [Amazon ECS: ECS Auto Scaling Overview | Amazon Web Services](https://www.youtube.com/watch?v=YDbqnZ32NdM) (Amazon Web Services)

## 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.

- You need: AWS CLI credentials allowed to create and delete temporary ECR and ECS resources
- You'll have: A RUNNING task followed by confirmed deletion of the task, cluster, repository and temporary execution role

```sh
$ 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
```

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

- Open Amazon ECR and inspect a repository and its scan-on-push setting.
- Open ECS and compare a task definition with a running task.
- Run the mission with a temporary public image, then verify the task stops.
- Open the EKS create-cluster page and identify the extra IAM and networking choices.

## Quiz

1. What does an ECR repository store?
   - **Container images and their tags** (answer)
   - Running virtual machines
   - Kubernetes API objects
   Why: ECR is a private image registry. ECS and EKS pull images from registries such as ECR.

2. What is the main benefit of Fargate?
   - **It removes the need to manage container hosts** (answer)
   - It provides SQL joins
   - It replaces an image registry
   Why: Fargate runs the task infrastructure for you. You still own the task definition, image, network and permissions.

3. What is a task definition?
   - **A versioned description of containers and their runtime settings** (answer)
   - A DNS zone
   - A database backup
   Why: CPU, memory, image, ports, environment and IAM roles are declared in the task definition.

4. When is an ECS service useful?
   - **To keep a desired number of tasks running** (answer)
   - To scan source code
   - To create an IAM user
   Why: A service replaces failed tasks and manages steady-state deployment of a long-running workload.

5. Which control is essential before a production task can access AWS APIs?
   - **A task role with only the required permissions** (answer)
   - AdministratorAccess on every task
   - Credentials in the image
   Why: A task role provides temporary credentials. Baking keys into an image creates a serious leak risk.

6. What does the ECS deployment circuit breaker do when rollback is enabled?
   - **Returns to the last completed deployment when the new task set cannot become healthy** (answer)
   - Encrypts the image
   - Creates an EKS cluster
   Why: The breaker detects a failed rollout and restores the last known-good service deployment.

7. When is Service Connect a better fit than raw Cloud Map discovery?
   - **When ECS services need named client aliases and managed connectivity between tasks** (answer)
   - When no service communicates with another
   - When a database needs a snapshot
   Why: Cloud Map is a registry. Service Connect adds a consistent ECS service-to-service connection model.

## Resources

- [Amazon ECR User Guide](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) (AWS Docs)
- [Amazon ECS Developer Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) (AWS Docs)
- [Amazon ECS task definitions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html) (AWS Docs)
- [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) (AWS Docs)
- [Amazon EKS User Guide](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) (AWS Docs)
