Docker Labs · Lab 5 of 6
Run a Container on AWS: ECR and ECS Fargate
Push the hello-api image to Amazon ECR and run it on ECS Fargate with the AWS CLI: repository, execution role, log group, task definition, service with a public IP, then a complete clean-up.
- Environment
- AWS
- Level
- Intermediate
- Time
- About 45 min
- Cost
- Under $0.05 if you clean up within an hour
You will build
The hello-api container running on AWS without any servers to manage, its logs in CloudWatch, and a clean account afterwards.
Before you start
- Lab: Small, Fast Images with Multi-Stage Builds
An AWS account you may create resources in
AWS CLI v2, signed in (
aws sts get-caller-identityworks)
The image build and tag steps show real output. The AWS steps show what to check instead of output: account IDs, ARNs and IPs are different for everyone. Every AWS command in this lab was checked for valid syntax and parameters with the AWS CLI.
The files use the placeholder account 123456789012 and region eu-west-1; a step below replaces them with
yours.
Cost: Fargate at 0.25 vCPU / 0.5 GB plus a public IPv4 address comes to under $0.05 if you clean up within an hour.
Project structure
hello-api/
├── main.go
├── go.mod
├── Dockerfile
├── .dockerignore
└── aws/
├── trust-policy.json # lets ECS tasks use the execution role
└── task-definition.json # CPU, memory, image, port, logs
Steps
-
1Set your account and region
Run export AWS_REGION=eu-west-1 export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) export REPO=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/hello-api echo $REPOCheck:echo $REPOprints your 12-digit account ID, not an error. -
2Build for the platform Fargate runs
Fargate runs
linux/amd64by default. On an Apple Silicon Mac,--platformis what stops an "exec format error" in the cloud. Then tag the image with the ECR address.Run docker build --platform linux/amd64 -t hello-api:1.0.0 . docker tag hello-api:1.0.0 $REPO:1.0.0 docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.ID}}' | grep -E "REPOSITORY|hello-api" docker image inspect $REPO:1.0.0 --format '{{.Os}}/{{.Architecture}}'Expected output
REPOSITORY TAG IMAGE ID 123456789012.dkr.ecr.eu-west-1.amazonaws.com/hello-api 1.0.0 50e17efba9fb hello-api 1.0.0 50e17efba9fb linux/amd64
Check:Both names share one image ID, and the platform is
linux/amd64. -
3Create the repository and push
IMMUTABLEtags mean1.0.0can never be overwritten — what you tested is what runs.scanOnPushgives you a free basic vulnerability scan.Run aws ecr create-repository --repository-name hello-api --image-scanning-configuration scanOnPush=true --image-tag-mutability IMMUTABLE aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com docker push $REPO:1.0.0Check:docker loginprintsLogin Succeededand the push ends with a1.0.0: digest: sha256:…line. -
4Create the execution role and log group
ECS uses the execution role to pull your image and write logs. Logs are kept seven days, so they don't grow forever.
Run aws iam create-role --role-name helloApiTaskExecutionRole --assume-role-policy-document file://aws/trust-policy.json aws iam attach-role-policy --role-name helloApiTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy aws logs create-log-group --log-group-name /ecs/hello-api aws logs put-retention-policy --log-group-name /ecs/hello-api --retention-in-days 7Check:create-rolereturns JSON with anArnending inrole/helloApiTaskExecutionRole. -
5The role's trust policy
aws/trust-policy.json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ecs-tasks.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } -
6Describe the task
The task definition is the container's contract with ECS: size (0.25 vCPU, 512 MB), image, port and log destination.
aws/task-definition.json { "family": "hello-api", "networkMode": "awsvpc", "requiresCompatibilities": ["FARGATE"], "cpu": "256", "memory": "512", "runtimePlatform": { "cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX" }, "executionRoleArn": "arn:aws:iam::123456789012:role/helloApiTaskExecutionRole", "containerDefinitions": [ { "name": "hello-api", "image": "123456789012.dkr.ecr.eu-west-1.amazonaws.com/hello-api:1.0.0", "essential": true, "portMappings": [{ "containerPort": 8080, "protocol": "tcp" }], "environment": [{ "name": "PORT", "value": "8080" }], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/hello-api", "awslogs-region": "eu-west-1", "awslogs-stream-prefix": "web" } } } ] } -
7Register it with your account and region
Run sed -e "s/123456789012/$AWS_ACCOUNT_ID/g" -e "s/eu-west-1/$AWS_REGION/g" aws/task-definition.json > /tmp/task-definition.json aws ecs create-cluster --cluster-name labs aws ecs register-task-definition --cli-input-json file:///tmp/task-definition.jsonCheck:register-task-definitionreturns"revision": 1and"status": "ACTIVE". -
8Open the network for your IP only
Use the default VPC's public subnets and a security group that allows port 8080 from your own IP address — not from the whole internet.
Run VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true --query "Vpcs[0].VpcId" --output text) SUBNETS=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID Name=default-for-az,Values=true --query "Subnets[].SubnetId" --output text | tr '\t' ',') SG_ID=$(aws ec2 create-security-group --group-name hello-api-sg --description "hello-api lab" --vpc-id $VPC_ID --query GroupId --output text) MY_IP=$(curl -s https://checkip.amazonaws.com) aws ec2 authorize-security-group-ingress --group-id $SG_ID --protocol tcp --port 8080 --cidr $MY_IP/32 echo $VPC_ID $SUBNETS $SG_IDCheck:The echo prints a
vpc-…ID, comma-separatedsubnet-…IDs and ansg-…ID.Hint
No default VPC? Create one with
aws ec2 create-default-vpc, or use any VPC with public subnets. -
9Start the service
A service keeps the desired number of tasks running and replaces any that fail.
Run aws ecs create-service --cluster labs --service-name hello-api --task-definition hello-api --desired-count 1 --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$SG_ID],assignPublicIp=ENABLED}" aws ecs wait services-stable --cluster labs --services hello-apiCheck:wait services-stablereturns without error (it can take two or three minutes). -
10Find the public IP and call it
Run TASK=$(aws ecs list-tasks --cluster labs --service-name hello-api --query "taskArns[0]" --output text) ENI=$(aws ecs describe-tasks --cluster labs --tasks $TASK --query "tasks[0].attachments[0].details[?name=='networkInterfaceId'].value" --output text) IP=$(aws ec2 describe-network-interfaces --network-interface-ids $ENI --query "NetworkInterfaces[0].Association.PublicIp" --output text) curl -s http://$IP:8080/ aws logs tail /ecs/hello-api --since 10mCheck:curlprints{"message":"hello from a container","version":"1.0.0"}and the log tail showslistening on :8080.
Clean up
Run these in order (each depends on the previous one). Nothing in this lab costs money after they finish.
aws ecs update-service --cluster labs --service hello-api --desired-count 0
aws ecs delete-service --cluster labs --service hello-api --force
aws ecs wait services-inactive --cluster labs --services hello-api
aws ecs delete-cluster --cluster labs
aws ecs deregister-task-definition --task-definition hello-api:1
aws ecr delete-repository --repository-name hello-api --force
aws logs delete-log-group --log-group-name /ecs/hello-api
aws ec2 delete-security-group --group-id $SG_ID
aws iam detach-role-policy --role-name helloApiTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam delete-role --role-name helloApiTaskExecutionRole
docker image rm $REPO:1.0.0 hello-api:1.0.0
Check: the ECS console shows no labs cluster, and aws ecr describe-repositories doesn't list hello-api.
In production
You now have a container on AWS, but a production service needs more around it. The building blocks are the same; production adds a load balancer, private networking, automation and guard rails.
What changes
| In this lab | In production |
|---|---|
| Commands typed into a terminal | Infrastructure as code (Terraform or CloudFormation) reviewed in pull requests |
| Task with a public IP | Tasks in private subnets behind an Application Load Balancer with HTTPS (ACM certificate) |
| Security group open to your IP on 8080 | ALB security group open on 443; task security group open only to the ALB |
| One task | At least two tasks across availability zones, with auto scaling on CPU or request count |
docker push from a laptop |
CI builds, scans and pushes with short-lived credentials (GitHub OIDC to an IAM role) |
| Execution role only | Also a task role with least-privilege access to the AWS services the app calls |
| Logs kept 7 days | Retention set by policy, metrics and alarms on errors, latency and task restarts |
create-service once |
Rolling or blue/green deployments with health checks and automatic rollback (deployment circuit breaker) |
Two roles, two jobs
The execution role is used by ECS itself (pull the image, write logs, read secrets for injection). The task role is used by your code. Keeping them separate means the app can't read secrets meant only for start-up, and each role grants only what its user needs.
Production checklist
- Repository uses immutable tags and scan on push; lifecycle rules delete old images
- Tasks run in private subnets behind an HTTPS load balancer; no public IPs on tasks
- At least two tasks in different availability zones; auto scaling configured
- Deployment circuit breaker with rollback is enabled
- Secrets come from Secrets Manager or Parameter Store, injected through the task definition
- Execution role and task role are separate and least-privilege
- Log retention, alarms and dashboards exist before launch
- Everything is defined as code; the console is for reading
Learn the concepts
- Tags, Digests and Registries · Docker Tutorial
- Multi-Stage Builds · Docker Tutorial
- Docker from Basics to Production · Course