AWS Learning Journey

Containers on AWS Without the Confusion: Docker, ECR, and ECS Explained

Images, registries, task definitions, services, task roles vs. execution roles, Fargate vs. EC2, and deployments — everything you need before you ship your first container to AWS.

9 min read · 1722 words
AWSDockerContainersAmazon ECSDevOps
Containers on AWS Without the Confusion: Docker, ECR, and ECS Explained cover image

AWS from Zero to Production — Phase 4, Part 3 of 6 · See the full series roadmap


“It works on my machine.”

Every engineer has said it. Every engineer has heard it. Containers exist to make it go away: you package the app with its runtime, libraries, and configuration, and it runs the same way on your laptop, in CI, and in production.

The confusing part isn’t Docker. It’s what happens next on AWS: ECR, ECS, Fargate, clusters, tasks, services, task definitions, two different IAM roles, capacity providers, and deployment settings.

This article untangles all of it. By the end, you’ll know exactly what each piece does — and you’ll be ready for Part 6, where you deploy a containerized API for real.

What you’ll walk away with


Container fundamentals

A container is a lightweight, isolated process that runs an app with everything it needs. Unlike a virtual machine, it shares the host’s operating system kernel, so it starts in seconds and uses little overhead.

Dockerfiles

A Dockerfile is the recipe for an image:

FROM public.ecr.aws/docker/library/python:3.12-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

USER 1000
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "app:app"]

Each instruction creates a layer. Layers are cached and shared, so ordering matters: copy dependency files and install them before copying your code, and rebuilds stay fast.

Image best practices

Mac users: Apple silicon builds arm64 images by default. If your ECS task runs on x86, build with docker build --platform linux/amd64, or run the task on Arm. Mismatches cause the cryptic exec format error.


Amazon Elastic Container Registry (ECR)

Amazon ECR is a managed container registry, integrated with IAM.

aws ecr get-login-password --region us-east-1 \
  | docker login --username AWS --password-stdin \
    111122223333.dkr.ecr.us-east-1.amazonaws.com

docker tag orders-api:1.0.0 \
  111122223333.dkr.ecr.us-east-1.amazonaws.com/orders-api:1.0.0

docker push 111122223333.dkr.ecr.us-east-1.amazonaws.com/orders-api:1.0.0

Image scanning

ECR can scan images for known vulnerabilities (CVEs):

Phase 7 turns scan results into a security gate in your pipeline.


Amazon Elastic Container Service (ECS)

Amazon ECS is AWS’s container orchestrator. It decides where containers run, keeps the right number running, replaces failed ones, and integrates with load balancers, IAM, and CloudWatch.

The four core concepts

Cluster           a logical group of capacity and services
  |
  +-- Service     keeps N copies of a task running, behind a load balancer
        |
        +-- Task          a running copy of a task definition
              |
              +-- Task definition   the blueprint (image, CPU, memory,
                                    ports, roles, logging, env vars)

A minimal task definition:

{
  "family": "orders-api",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::111122223333:role/orders-api-task",
  "containerDefinitions": [
    {
      "name": "orders-api",
      "image": "111122223333.dkr.ecr.us-east-1.amazonaws.com/orders-api:1.0.0",
      "portMappings": [{ "containerPort": 8080 }],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/orders-api",
          "awslogs-region": "us-east-1",
          "awslogs-stream-prefix": "app"
        }
      }
    }
  ]
}

With the awsvpc network mode, every task gets its own network interface, private IP, and security group — just like an EC2 instance.


Task role vs. execution role

This is the part almost everyone gets wrong at least once. ECS uses two IAM roles, for two different jobs:

Execution role — used by ECS, before your app starts

Task role — used by your application code, while it runs

"CannotPullContainerError" or missing logs     -> check the EXECUTION role
"AccessDenied" when your code calls S3         -> check the TASK role

Engineer’s note: Never give the task role the execution role’s permissions “to be safe,” and vice versa. Each has a clear, separate job — keep them least privilege.


ECS on EC2 vs. AWS Fargate

ECS needs compute capacity to run tasks. You have two main options:

ECS on EC2

AWS Fargate

Capacity providers let a service mix them — for example, a baseline on Fargate and extra tasks on Fargate Spot.

Default choice: Start with Fargate. Move to EC2 when you have a specific reason: GPUs, very large steady workloads, or special host requirements.


Service discovery

Services need to find each other. Hard-coding IPs doesn’t work, because tasks come and go.


Deployment strategies

When you update a service to a new task definition revision, ECS can deploy it in several ways:

The deployment circuit breaker

Turn this on for rolling updates. If new tasks keep failing to start or pass health checks, ECS stops the deployment and, with rollback enabled, returns to the last working revision automatically.

--deployment-configuration \
  "deploymentCircuitBreaker={enable=true,rollback=true},minimumHealthyPercent=100,maximumPercent=200"

ECS Exec: a shell in a running container

ECS Exec opens an interactive shell — or runs a single command — in a running container, through Systems Manager. No SSH, no open ports.

aws ecs execute-command \
  --cluster prod \
  --task 0123456789abcdef0 \
  --container orders-api \
  --interactive \
  --command "/bin/sh"

It requires enableExecuteCommand on the service and SSM permissions on the task role. Sessions can be logged for auditing.


Container logging

Containers should write logs to stdout and stderr. Then:

Cost tip: Set a retention period on every log group. The default is to keep logs forever.


Common mistakes


Key takeaways


Quick self-check

Test yourself before moving on:

  1. A task fails with CannotPullContainerError. Which role do you check?
  2. Your app gets AccessDenied writing to S3. Which role do you check?
  3. What happens when the deployment circuit breaker detects failure with rollback enabled?
  4. Why should you avoid the latest tag in production?

Answers

  1. The execution role — and the network path to ECR.
  2. The task role.
  3. ECS stops the deployment and rolls back to the last working revision.
  4. It’s mutable, so you can’t tell which code is running, and rollbacks are unreliable.

What’s next

In Part 4, we look at the other big container option: Kubernetes on AWS with Amazon EKS — pods, deployments, node groups, Fargate profiles, Pod Identity, and the AWS Load Balancer Controller.

ECS or Kubernetes — which does your team use, and why? Tell me in the comments.


Share this article

LinkedIn post draft