
Amazon ECR and ECS Explained: Run Containers on AWS Fargate with the Console and CLI
Learn how Amazon ECR stores your container images and how Amazon ECS runs them. Build a complete example step by step, from a Dockerfile to a running Fargate service, using both the AWS Management Console and the AWS CLI. Covers image scanning, lifecycle policies, rolling deployments, rollbacks, best practices, and troubleshooting.
What are Amazon ECR and Amazon ECS?
Containers let you package an application and everything it needs into a single image that runs the same way on your laptop, in testing, and in production. Once you have a container image, you need two things: a place to store it, and a way to run it reliably. Amazon ECR and Amazon ECS are the AWS services built for those two jobs.
- Amazon ECR (Elastic Container Registry) is a fully managed container registry. You push your Docker images to it, and AWS stores, encrypts, scans, and serves them securely.
- Amazon ECS (Elastic Container Service) is a fully managed container orchestration service. You tell it which image to run and how many copies you want, and it starts the containers, replaces failed ones, and rolls out new versions.
In this article you will learn the core concepts of both services and how they work together. Then you will build a working example, from a Dockerfile to a running service, with the AWS Management Console and with the AWS CLI.
ECR vs ECS at a glance
- Purpose: ECR stores and distributes container images. ECS runs and manages containers.
- Unit of work: ECR works with repositories and images. ECS works with clusters, task definitions, tasks, and services.
- Analogy: ECR is the warehouse where your packaged applications are kept. ECS is the team that takes them out and keeps them running.
- Together: you push an image to ECR, then an ECS task definition points to that image, and ECS pulls and runs it.
Core ECR concepts
- Repository: a collection of related images, usually one repository per application or service.
- Image: the packaged application. Each image in a repository is identified by a tag and a digest.
- Tag: a human-friendly label such as
v1or1.4.2.
- Digest: a unique SHA-256 hash of the image contents. A digest never changes, so it identifies an exact image.
- Tag immutability: when enabled, a tag can never be overwritten by a new push. This prevents someone from silently replacing
v1with different code.
- Image scanning: ECR can scan images for known software vulnerabilities, either when you push (scan on push) or continuously with enhanced scanning through Amazon Inspector.
- Lifecycle policy: rules that automatically delete old or untagged images so your storage cost does not grow forever.
- Authentication: Docker logs in to ECR using a temporary token from
aws ecr get-login-password. The token is valid for 12 hours.
- Encryption: images are encrypted at rest by default. You can use an AWS KMS key instead.
- Private and public repositories: private repositories need IAM permissions to pull. Public repositories (ECR Public) can be pulled by anyone.
Core ECS concepts
- Cluster: a logical grouping of tasks and services. It is the top-level container for your workloads.
- Task definition: the blueprint for your application. It lists the container image, CPU and memory, ports, environment variables, logging, and IAM roles. Each change creates a new numbered revision.
- Task: one running instance of a task definition, like a single running copy of your application.
- Service: keeps a desired number of tasks running, replaces tasks that fail, and handles rolling deployments of new versions. It can also register tasks with a load balancer.
- Launch type (compute): where your tasks run. AWS Fargate is serverless, so AWS manages the servers and you only choose CPU and memory. EC2 means you manage a fleet of instances yourself.
- Task execution role: the IAM role that ECS itself uses to pull your image from ECR and write logs to CloudWatch.
- Task role: the IAM role your application code uses to call AWS services such as S3 or DynamoDB.
- awsvpc networking: each task gets its own network interface and private IP address inside your VPC. It is required for Fargate.
- Container definition: the settings for one container inside a task definition. A task can contain more than one container.
Execution role versus task role is a common source of confusion. The execution role is for ECS (pull the image, write logs). The task role is for your code (access your own AWS resources).
How ECR and ECS work together
- You build a container image on your machine or in a CI/CD pipeline.
- You push the image to an ECR repository.
- You create an ECS task definition that references the image in ECR.
- You create an ECS service that tells ECS to keep a number of tasks running from that task definition.
- For each task, ECS uses the task execution role to pull the image from ECR, starts the container, and sends logs to CloudWatch Logs.
- When you release a new version, you push a new image tag, register a new task definition revision, and update the service. ECS replaces the old tasks with new ones gradually.
What you will build
- A small web application packaged as a Docker image based on nginx
- A private ECR repository named
demo-web-appwith scan on push and tag immutability enabled
- An ECS cluster named
demo-clusterthat uses AWS Fargate
- A task definition named
demo-web-taskwith CloudWatch logging
- An ECS service named
demo-web-servicethat runs one task with a public IP
- A new version rollout and a cleanup of everything
Prerequisites
- An AWS account and permissions to manage ECR, ECS, IAM, EC2 networking, and CloudWatch Logs
- Docker installed and running on your computer
- AWS CLI v2 configured with
aws configure
- A VPC with at least one public subnet (the default VPC works)
- A Region of your choice (the examples use
us-east-1)
Cost warning: Fargate bills per second for the CPU and memory your tasks use, and a public IPv4 address is billed per hour. A single small task costs very little, but only if you delete it when you are done. See the cleanup step.
Step 0: Create the sample application
Both the console and CLI paths use the same image, so create it first. Make a new folder and create two files.
Create a file named
index.html :<!DOCTYPE html><html> <head><title>Demo App</title></head> <body> <h1>Hello from Amazon ECS on AWS Fargate</h1> <p>Version 1</p> </body></html>Create a file named
Dockerfile (no file extension):FROM nginx:alpineCOPY index.html /usr/share/nginx/html/index.htmlEXPOSE 80Build the image:
docker build --platform linux/amd64 -t demo-web-app:v1 .The
--platform linux/amd64 flag matters if you use an Apple Silicon Mac. Without it, you build an ARM image, and the task definition below (which uses X86_64) will fail with an exec format error .You can test it locally before pushing:
docker run --rm -p 8080:80 demo-web-app:v1Open
http://localhost:8080 in your browser, then press Ctrl+C to stop it.Implementation with the AWS Management Console
Step 1: Create the ECR repository
- Open the Amazon ECR console and choose Create repository.
- Set Visibility settings to Private.
- Set Repository name to
demo-web-app.
- Set Tag immutability to Enabled.
- Enable Scan on push (under image scanning settings, if shown).
- Leave Encryption at its default and choose Create repository.
Step 2: Push the image
- Open the repository
demo-web-appand choose View push commands.
- Copy and run the commands for your operating system in the folder that contains your Dockerfile. They log in to ECR, build, tag, and push the image.
- When tagging, use the tag
v1instead oflatest, because tag immutability is on.
- After the push finishes, refresh the repository page. You should see an image tagged
v1.
- Open the image to see its digest, size, and scan results.
Step 3: Add a lifecycle policy (optional)
- In the ECR console, open Private registry, then Lifecycle policy for your repository (or use the Lifecycle Policy section of the repository).
- Choose Create rule. Set Image status to Any, Match criteria to Image count more than, and the value to
10. The action is expire.
- Save the rule.
This keeps only the 10 most recent images.
Step 4: Create the ECS cluster
- Open the Amazon ECS console, choose Clusters, then Create cluster.
- Set Cluster name to
demo-cluster.
- Under Infrastructure, leave AWS Fargate (serverless) selected.
- Choose Create.
Step 5: Create the task definition
- In the ECS console, choose Task definitions, then Create new task definition.
- Set Task definition family to
demo-web-task.
- Set Launch type to AWS Fargate, Operating system/Architecture to Linux/X86_64.
- Set CPU to .25 vCPU and Memory to .5 GB.
- For Task execution role, choose Create new role (or select
ecsTaskExecutionRoleif it already exists). Leave Task role empty because this demo does not call other AWS services.
- Under Container - 1, set Name to
web.
- For Image URI, paste your image URI, for example
123456789012.dkr.ecr.us-east-1.amazonaws.com/demo-web-app:v1. You can copy it from the ECR console.
- Set Container port to
80and Protocol to TCP.
- Under Logging, keep Use log collection enabled (the
awslogsdriver). Choose Create at the bottom of the page.
Step 6: Create the service
- Open the cluster
demo-cluster, go to the Services tab, and choose Create.
- Under Compute options, choose Launch type and set it to FARGATE.
- Under Deployment configuration, set Family to
demo-web-task, Revision to LATEST, Service name todemo-web-service, and Desired tasks to1.
- Expand Networking. Select your VPC (the default VPC is fine) and at least one public subnet.
- For Security group, choose Create a new security group. Add an inbound rule with Type
HTTPand SourceAnywhere.
- Set Public IP to Turned on.
- Expand Deployment options and make sure Use the Amazon ECS deployment circuit breaker and Rollback on failures are enabled.
- Choose Create.
Step 7: Test the application
- Open the service and wait until the task shows Running and the service is Active.
- Open the Tasks tab and select the running task.
- In Configuration, copy the Public IP.
- Open
http://<public-ip>in your browser. You should see "Hello from Amazon ECS on AWS Fargate".
Step 8: View logs
- Open the task and choose the Logs tab to see the container's output.
- Or open CloudWatch, go to Log groups, and open the log group for
demo-web-task.
Step 9: Deploy a new version
- Edit
index.htmland change "Version 1" to "Version 2".
- Build and push the image again with the tag
v2(see the CLI push commands below for the exact commands).
- In the ECS console, open Task definitions, select
demo-web-task, and choose Create new revision.
- Change the image URI tag from
v1tov2and choose Create.
- Open your service, choose Update service, set Revision to the new revision, and choose Update.
- Watch the Deployments tab. ECS starts a new task, waits for it to run, and then stops the old one.
- Open the new task's public IP. The page should now say "Version 2". The public IP changes because it is a new task.
Step 10: Clean up
- In the cluster, select
demo-web-serviceand choose Delete service. Check Force delete if asked.
- After the service is gone, select the cluster and choose Delete cluster.
- In Task definitions, select each revision of
demo-web-taskand choose Deregister.
- In ECR, select the repository
demo-web-appand choose Delete.
- In CloudWatch, delete the log group for
demo-web-task.
- In EC2, open Security groups and delete the security group the console created for the service (after the tasks have stopped).
Implementation with the AWS CLI
ECR commands live under
aws ecr , and ECS commands live under aws ecs . Set the variables first:export AWS_REGION=us-east-1export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)export REPO_NAME=demo-web-appexport ECR_URI=$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO_NAMEStep 1: Create the ECR repository
aws ecr create-repository \ --repository-name $REPO_NAME \ --image-scanning-configuration scanOnPush=true \ --image-tag-mutability IMMUTABLE \ --region $AWS_REGIONStep 2: Log in, tag, and push the image
aws ecr get-login-password --region $AWS_REGION | \ docker login --username AWS --password-stdin $ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
docker tag demo-web-app:v1 $ECR_URI:v1
docker push $ECR_URI:v1Verify the image is in the repository:
aws ecr describe-images \ --repository-name $REPO_NAME \ --query 'imageDetails[].[imageTags[0],imageDigest,imageSizeInBytes]' \ --output tableCheck the scan results once the scan completes:
aws ecr describe-image-scan-findings \ --repository-name $REPO_NAME \ --image-id imageTag=v1 \ --query 'imageScanFindings.findingSeverityCounts'Step 3: Add a lifecycle policy (optional)
cat > lifecycle-policy.json <<'EOF'{ "rules": [ { "rulePriority": 1, "description": "Keep only the 10 most recent images", "selection": { "tagStatus": "any", "countType": "imageCountMoreThan", "countNumber": 10 }, "action": { "type": "expire" } } ]}EOF
aws ecr put-lifecycle-policy \ --repository-name $REPO_NAME \ --lifecycle-policy-text file://lifecycle-policy.jsonStep 4: Create the task execution role
This role lets ECS pull images from ECR and write logs. If
ecsTaskExecutionRole already exists in your account (the console creates it), skip this step.cat > ecs-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 ecsTaskExecutionRole \ --assume-role-policy-document file://ecs-trust.json
aws iam attach-role-policy \ --role-name ecsTaskExecutionRole \ --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicyStep 5: Create the cluster and the log group
aws ecs create-cluster --cluster-name demo-cluster
aws logs create-log-group --log-group-name /ecs/demo-web-task
aws logs put-retention-policy \ --log-group-name /ecs/demo-web-task \ --retention-in-days 7Creating the log group yourself matters, because the managed execution role policy does not allow ECS to create log groups. Setting a retention period keeps log storage costs under control.
Step 6: Register the task definition
cat > taskdef.json <<EOF{ "family": "demo-web-task", "networkMode": "awsvpc", "requiresCompatibilities": ["FARGATE"], "cpu": "256", "memory": "512", "executionRoleArn": "arn:aws:iam::$ACCOUNT_ID:role/ecsTaskExecutionRole", "runtimePlatform": { "cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX" }, "containerDefinitions": [ { "name": "web", "image": "$ECR_URI:v1", "essential": true, "portMappings": [ { "containerPort": 80, "protocol": "tcp" } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/demo-web-task", "awslogs-region": "$AWS_REGION", "awslogs-stream-prefix": "web" } } } ]}EOF
aws ecs register-task-definition --cli-input-json file://taskdef.jsonThe output shows the new revision number. Fargate only accepts specific CPU and memory combinations. 256 CPU units (0.25 vCPU) with 512 MiB of memory is the smallest valid one.
Step 7: Find networking details
VPC_ID=$(aws ec2 describe-vpcs \ --filters Name=isDefault,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[0:2].SubnetId' --output text | tr '\t' ',')
echo $VPC_ID $SUBNETSCreate a security group that allows web traffic:
SG_ID=$(aws ec2 create-security-group \ --group-name demo-ecs-sg \ --description "Allow HTTP to ECS demo" \ --vpc-id $VPC_ID \ --query GroupId --output text)
aws ec2 authorize-security-group-ingress \ --group-id $SG_ID --protocol tcp --port 80 --cidr 0.0.0.0/0Step 8: Create the service
aws ecs create-service \ --cluster demo-cluster \ --service-name demo-web-service \ --task-definition demo-web-task \ --desired-count 1 \ --launch-type FARGATE \ --network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$SG_ID],assignPublicIp=ENABLED}" \ --deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true}"The deployment circuit breaker stops a failing deployment and rolls back to the last working version automatically.
Step 9: Wait for the service and find the public IP
aws ecs wait services-stable \ --cluster demo-cluster \ --services demo-web-service
TASK_ARN=$(aws ecs list-tasks \ --cluster demo-cluster \ --service-name demo-web-service \ --query 'taskArns[0]' --output text)
ENI_ID=$(aws ecs describe-tasks \ --cluster demo-cluster \ --tasks $TASK_ARN \ --query "tasks[0].attachments[0].details[?name=='networkInterfaceId'].value" \ --output text)
PUBLIC_IP=$(aws ec2 describe-network-interfaces \ --network-interface-ids $ENI_ID \ --query 'NetworkInterfaces[0].Association.PublicIp' --output text)
echo http://$PUBLIC_IPcurl http://$PUBLIC_IPYou should see the HTML for "Hello from Amazon ECS on AWS Fargate".
Step 10: View logs and service status
aws logs tail /ecs/demo-web-task --follow
aws ecs describe-services \ --cluster demo-cluster \ --services demo-web-service \ --query 'services[0].[status,runningCount,desiredCount]' \ --output tablePress Ctrl+C to stop following the logs.
Step 11: Deploy a new version
Change "Version 1" to "Version 2" in
index.html , then build, tag, and push v2 :docker build --platform linux/amd64 -t demo-web-app:v2 .docker tag demo-web-app:v2 $ECR_URI:v2docker push $ECR_URI:v2Update the task definition to use the new tag and register it as a new revision:
sed -i.bak "s#$ECR_URI:v1#$ECR_URI:v2#" taskdef.json
aws ecs register-task-definition --cli-input-json file://taskdef.jsonUpdate the service. Passing only the family name uses the latest active revision:
aws ecs update-service \ --cluster demo-cluster \ --service demo-web-service \ --task-definition demo-web-task
aws ecs wait services-stable \ --cluster demo-cluster \ --services demo-web-serviceFind the new task's public IP with the commands from Step 9 and confirm the page says "Version 2".
Step 12: Roll back or scale
To roll back, point the service to an earlier revision. Replace
1 with the revision you want:aws ecs update-service \ --cluster demo-cluster \ --service demo-web-service \ --task-definition demo-web-task:1To run two copies of the application:
aws ecs update-service \ --cluster demo-cluster \ --service demo-web-service \ --desired-count 2Step 13: Clean up
aws ecs delete-service \ --cluster demo-cluster \ --service demo-web-service \ --force
aws ecs wait services-inactive \ --cluster demo-cluster \ --services demo-web-service
aws ecs delete-cluster --cluster demo-cluster
aws ecs deregister-task-definition --task-definition demo-web-task:1aws ecs deregister-task-definition --task-definition demo-web-task:2
aws logs delete-log-group --log-group-name /ecs/demo-web-task
aws ecr delete-repository --repository-name $REPO_NAME --force
aws ec2 delete-security-group --group-id $SG_IDIf deleting the security group fails, wait a minute for the task's network interface to be released and try again. The
ecsTaskExecutionRole is shared by many ECS workloads, so keep it unless you are sure nothing else uses it.Console or CLI: which should you use?
- Console: best for learning. It can create the execution role and security group for you, and it shows task status, stopped reasons, and logs in one place.
- CLI: best for repeatable setup and scripting. You must create the roles, log groups, and networking pieces yourself and wire the IDs together.
For production, define your repositories, task definitions, and services in AWS CloudFormation, AWS CDK, or Terraform, and deploy new versions from a CI/CD pipeline instead of by hand.
Best practices
- Use immutable, specific tags. Enable tag immutability and deploy tags like
1.4.2or a Git commit hash. Avoidlatestin production because you cannot tell which code is running.
- Scan your images. Turn on scan on push, or enhanced scanning, and fix critical vulnerabilities before deploying.
- Add lifecycle policies. Expire untagged and old images so ECR storage costs stay low.
- Keep images small and clean. Use slim or alpine base images, and never bake secrets into an image.
- Separate the execution role from the task role. Give the task role only the permissions your application needs.
- Store secrets properly. Reference AWS Secrets Manager or Systems Manager Parameter Store from the task definition instead of using plain environment variables.
- Put tasks in private subnets for real workloads. Place an Application Load Balancer in public subnets and keep tasks private. Use a NAT gateway or VPC endpoints (ECR API, ECR Docker, S3, and CloudWatch Logs) so private tasks can still pull images and write logs.
- Use a load balancer for web services. A load balancer gives you a stable address, health checks, and zero-downtime deployments. A task's public IP changes every time the task is replaced.
- Define health checks. Add a container health check and a load balancer health check so ECS replaces unhealthy tasks.
- Enable the deployment circuit breaker. It stops bad releases and rolls back automatically.
- Set log retention. CloudWatch logs are kept forever by default, so choose a retention period.
- Use auto scaling. Scale the service on CPU, memory, or request count instead of running a fixed number of tasks.
- Save cost where possible. Use Fargate Spot for fault-tolerant or development workloads, and consider ARM64 (Graviton) for lower cost if your image supports it.
- Tag your resources. Consistent tags make cost tracking and cleanup much easier.
- Monitor with CloudWatch. Watch CPU and memory utilization, running task count, and set alarms for failed deployments.
Troubleshooting
-
CannotPullContainerErrororResourceInitializationErrorwhen the task starts: the task cannot pull the image. Check that the image tag exists, the execution role has theAmazonECSTaskExecutionRolePolicy, and the task has a route to ECR (public IP enabled in a public subnet, or a NAT gateway or VPC endpoints in a private subnet).
- Task stops immediately with
exec format errorin the logs: the image architecture does not match the task definition. Rebuild with--platform linux/amd64, or set the task definition to ARM64 and build an ARM image.
- Task keeps stopping and restarting: open the stopped task and read the Stopped reason, then check the container logs. A crashing application or a failing health check is the usual cause.
- Cannot open the public IP in the browser: check that the service uses a public subnet, that Public IP is on, that the security group allows inbound port 80, and that the subnet route table has a route to an internet gateway.
- No logs appear: check that the log group exists, the name in the task definition matches it exactly, and the execution role can write logs.
-
docker pushfails withno basic auth credentials: your ECR login token has expired (12 hours) or you logged in to the wrong Region or account. Run thedocker logincommand again.
-
docker pushfails because the tag already exists: tag immutability is on. Push a new tag such asv2.
- Service shows no running tasks and events mention capacity or ENI errors: check that the subnets have free IP addresses and that your account has not reached its Fargate or network interface limits.
- Invalid CPU or memory combination: Fargate only allows specific pairs. For example, 256 CPU units supports 512, 1024, or 2048 MiB of memory.
- Cannot delete the security group or VPC resources: the task's network interface is still attached. Wait for the tasks to stop and try again.
- Deployment never finishes: the new tasks are failing to start or to pass health checks. With the circuit breaker on, ECS rolls back automatically. Read the service events for the cause.
Conclusion
Amazon ECR and Amazon ECS give you a complete, managed path for running containers on AWS. ECR keeps your images safe, versioned, and scanned. ECS, running on Fargate, starts and supervises your containers without any servers to manage. Start with a small image, push it with an immutable tag, run it as a Fargate service, and practice a full deploy and rollback. Then add a load balancer, private subnets, auto scaling, and a CI/CD pipeline to move toward a production-ready setup.
Console labels, quotas, and pricing change over time, so confirm current details in the Amazon ECR and Amazon ECS documentation before building.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article