Cloud and deployment · Intermediate · 27 min
Run a container on Amazon ECS with Fargate
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4 · Amazon ECS on Fargate
You will run two copies of a container image from Amazon ECR as an ECS service on Fargate, with its own execution and task roles, CloudWatch logs and a secret from Secrets Manager, roll out a new revision without downtime, and then scale it to zero and delete it.
On this page
Amazon ECS (Elastic Container Service) runs containers for you, and Fargate is the mode where AWS also owns the servers underneath. You do not patch hosts or size a cluster of instances. You describe one copy of your app in a task definition: the image, how much CPU and memory it gets, which ports it opens, where its logs go and which secrets it needs. A service then keeps a set number of those tasks running, replaces any that stop, and rolls out new revisions one batch at a time.
In this tutorial you push the hello-node image to a private ECR repository and run it as a service of two tasks in the default VPC's public subnets. Along the way you build the two roles every Fargate task deals with, which are easy to mix up: the execution role that ECS uses to start the task, and the task role your code runs as. You add a secret from AWS Secrets Manager, ship a second revision with a health check while the old tasks keep serving, then scale to zero and delete everything.
Cost. Fargate has no free tier: its pricing page lists none, and you pay per second, with a one-minute minimum, from the moment a task starts pulling its image until it stops. Checked on 26 November 2026, Linux/x86 tasks in US East (N. Virginia) cost 0.04048 USD per vCPU-hour and 0.004445 USD per GB-hour. Two tasks of 0.25 vCPU and 0.5 GB come to about 0.59 USD a day. Each task also gets a public IPv4 address at 0.005 USD an hour, another 0.24 USD a day for two, so the service costs roughly 0.83 USD a day, or about 25 USD a month if you forget it. The secret is 0.40 USD a month, charged pro rata. ECR also bills for the storage the image takes up, at a rate listed on its pricing page. Prices differ by Region. Newer accounts get Free Tier credits that may cover some of this; check the Billing console rather than assuming. The last step deletes everything.
Files live in ~/fargate-demo and AWS names start with hello-node, so nothing collides with what your account already has.
Step 1 · Set up the project and find your network
Install jq, which you use to write the second task definition later, and make the project folder:
sudo apt update
sudo apt install -y jq
mkdir -p ~/fargate-demo
cd ~/fargate-demoKeep the Region, account and names in variables. Replace eu-west-2 with the Region you want the service in. If you would rather run an image you already have in ECR, set REPO and TAG to its repository and tag and PORT to the port it listens on, and skip the build and push in the next step. For users in southern Africa, Cape Town (af-south-1) cuts the round trip, but it is an opt-in Region you enable in the account settings first, and the image must be in ECR there too:
export AWS_DEFAULT_REGION=eu-west-2 # replace with your Region
REGION="$AWS_DEFAULT_REGION"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
REPO=hello-node # replace with your ECR repository
TAG=1 # the image tag to run
PORT=3000 # the port your app listens on
FAMILY=hello-node
CLUSTER=hello-node
SERVICE=hello-node-web
LOG_GROUP=/ecs/hello-node
echo "$ACCOUNT_ID $REGION"Fargate tasks need subnets and a security group. Use the default VPC: its subnets are public, meaning they route to an internet gateway, so a task with a public IP can pull from ECR and you can reach it from your laptop. Take two subnets, in two Availability Zones, so one zone failing leaves a task running:
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}" \
--query 'Subnets[:2].SubnetId' --output text | tr '\t' ',')
echo "$VPC_ID $SUBNETS"Check it worked
The first echo prints your 12-digit account ID and the Region. The last line shows a VPC ID such as vpc-0a1b2c3d and two subnet IDs separated by a comma. If the VPC ID is None, the Region has no default VPC: pick another VPC with public subnets and set VPC_ID by hand.
Step 2 · Push the hello-node image to ECR
Fargate pulls images from a registry, not from your laptop, so the image needs a home in ECR. Create a private repository called hello-node in the same Region and read back its address:
aws ecr create-repository --repository-name "$REPO" --query 'repository.repositoryName' --output text
REPO_URI=$(aws ecr describe-repositories --repository-names "$REPO" \
--query 'repositories[0].repositoryUri' --output text)
IMAGE="${REPO_URI}:${TAG}"
echo "$IMAGE"Now rebuild the image for x86 servers, log Docker in to your registry and push. aws ecr get-login-password prints a registry token valid for 12 hours, and piping it into --password-stdin keeps it out of your shell history; the username is always AWS. Run this from the folder that holds the hello-node app and its Dockerfile:
cd ~/hello-node # the app folder from the Dockerfile tutorial
docker build --platform linux/amd64 -t hello-node:1 .
aws ecr get-login-password | docker login --username AWS --password-stdin "${REPO_URI%%/*}"
docker tag hello-node:1 "$IMAGE"
docker push "$IMAGE"
cd ~/fargate-demo--platform linux/amd64 matters on Apple Silicon and other ARM machines, which would otherwise build an ARM64 image that x86 Fargate tasks cannot start. The build runs under emulation there and takes longer. If you build ARM64 on purpose, set cpuArchitecture to ARM64 in the task definition later. On a slow or prepaid connection, note that the push uploads the whole image, a few hundred megabytes for this one, the first time; later pushes send only changed layers.
Check it worked
echo "$IMAGE" prints something like 123456789012.dkr.ecr.eu-west-2.amazonaws.com/hello-node:1, and docker push ends with a line containing digest: sha256:. Confirm ECR holds the tag:
aws ecr describe-images --repository-name "$REPO" --image-ids imageTag="$TAG" \
--query 'imageDetails[0].imageTags' --output textIt prints 1. ImageNotFoundException means the push did not finish or went to another Region.
Step 3 · Open a security group to your own address
Each Fargate task gets its own network interface, and a security group decides what may reach it. This one allows port 3000 from your current public IP only, rather than from the whole internet. Look your address up first:
MY_IP=$(curl -fsS https://checkip.amazonaws.com)
echo "$MY_IP"Then create the group in the default VPC and add the rule:
SG_ID=$(aws ec2 create-security-group --group-name hello-node-tasks \
--description "hello-node Fargate tasks" --vpc-id "$VPC_ID" \
--query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id "$SG_ID" \
--protocol tcp --port "$PORT" --cidr "${MY_IP}/32"
echo "$SG_ID"Outbound traffic is allowed by default, which the task needs to pull the image and read the secret. A public service would sit behind an Application Load Balancer instead, with this group allowing traffic from the load balancer's group alone.
On mobile data your public IP can change between sessions, because many networks share one address across lots of users and hand out a new one when you reconnect. If curl to a task times out later, look the address up again and add another rule.
Check it worked
aws ec2 describe-security-groups --group-ids "$SG_ID" \
--query 'SecurityGroups[0].IpPermissions[0].[FromPort,IpRanges[0].CidrIp]' --output textIt prints 3000 and your address followed by /32.
Step 4 · Store the API token in Secrets Manager
Pretend the app calls a partner API with a token. The token must not sit in the task definition, where anyone who can read ECS settings would see it. Store it in Secrets Manager and let ECS hand it to the container at start-up.
Type the token at a prompt so it never appears in your shell history or the process list, and write it to a file that only you can read:
printf 'API token: '
read -rs API_TOKEN
echo
( umask 077; printf '%s' "$API_TOKEN" > token.txt )
unset API_TOKENCreate the secret from the file, then delete the file:
SECRET_ARN=$(aws secretsmanager create-secret --name hello-node/api-token \
--description "Partner API token for hello-node" \
--secret-string file://token.txt --query ARN --output text)
rm -f token.txt
echo "$SECRET_ARN"file:// makes the CLI read the value from the file, so the token is not an argument on the command line.
Check it worked
The ARN looks like arn:aws:secretsmanager:eu-west-2:123456789012:secret:hello-node/api-token-AbCdEf; Secrets Manager adds the six random characters at the end. ls ~/fargate-demo no longer lists token.txt.
Step 5 · Create the execution role and the task role
Two roles, two jobs:
- The execution role is used by ECS itself, before and around your code: to pull the image from ECR, to create the log stream and send log lines, and to fetch the secret. Your app never gets these permissions.
- The task role is what your code runs as. If the app read from an S3 bucket, that permission would go here. hello-node calls no AWS APIs, so its task role has no policies at all. That is deliberate: if someone takes over the container, AWS credentials from it can do nothing.
Both trust the same service, ecs-tasks.amazonaws.com, but with different trust policies. The task role's policy adds an aws:SourceAccount condition, which AWS documents for task roles, so ECS acting for another account cannot use it. The execution role uses the plain trust policy from the AWS execution-role guide, without that condition:
cat > execution-trust.json <<JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ecs-tasks.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
JSON
cat > task-trust.json <<JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ecs-tasks.amazonaws.com" },
"Action": "sts:AssumeRole",
"Condition": { "StringEquals": { "aws:SourceAccount": "${ACCOUNT_ID}" } }
}
]
}
JSON
EXEC_ROLE_ARN=$(aws iam create-role --role-name hello-node-execution \
--assume-role-policy-document file://execution-trust.json --query Role.Arn --output text)
TASK_ROLE_ARN=$(aws iam create-role --role-name hello-node-task \
--assume-role-policy-document file://task-trust.json --query Role.Arn --output text)Create the log group, with a retention period so old logs do not pile up and bill for ever:
aws logs create-log-group --log-group-name "$LOG_GROUP"
aws logs put-retention-policy --log-group-name "$LOG_GROUP" --retention-in-days 14Now give the execution role exactly what it needs: an ECR login token (this action works only on *), the image layers from one repository, log writes to one log group and one secret. AWS also publishes a managed policy, AmazonECSTaskExecutionRolePolicy, but it covers every repository and log group in the account and does not include secrets:
cat > execution-policy.json <<JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "EcrLogin",
"Effect": "Allow",
"Action": "ecr:GetAuthorizationToken",
"Resource": "*"
},
{
"Sid": "PullOneRepository",
"Effect": "Allow",
"Action": ["ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage"],
"Resource": "arn:aws:ecr:${REGION}:${ACCOUNT_ID}:repository/${REPO}"
},
{
"Sid": "WriteOwnLogs",
"Effect": "Allow",
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:${REGION}:${ACCOUNT_ID}:log-group:${LOG_GROUP}:*"
},
{
"Sid": "ReadOneSecret",
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "${SECRET_ARN}"
}
]
}
JSON
aws iam put-role-policy --role-name hello-node-execution \
--policy-name start-hello-node --policy-document file://execution-policy.jsonIf you encrypt the secret with your own KMS key instead of the default one, the execution role also needs kms:Decrypt on that key.
Check it worked
aws iam list-role-policies --role-name hello-node-execution --query PolicyNames --output text
aws iam list-role-policies --role-name hello-node-task --query PolicyNames --output textThe first command prints start-hello-node. The second prints nothing: the task role has no permissions, which is what you want here.
Step 6 · Write and register the task definition
The task definition is a JSON document. Write it with your variables filled in:
cat > taskdef-v1.json <<JSON
{
"family": "${FAMILY}",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": "X86_64" },
"executionRoleArn": "${EXEC_ROLE_ARN}",
"taskRoleArn": "${TASK_ROLE_ARN}",
"containerDefinitions": [
{
"name": "web",
"image": "${IMAGE}",
"essential": true,
"portMappings": [{ "containerPort": ${PORT}, "protocol": "tcp" }],
"environment": [{ "name": "PORT", "value": "${PORT}" }],
"secrets": [{ "name": "API_TOKEN", "valueFrom": "${SECRET_ARN}" }],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "${LOG_GROUP}",
"awslogs-region": "${REGION}",
"awslogs-stream-prefix": "hello-node"
}
}
}
]
}
JSON
jq -e . taskdef-v1.json > /dev/null && echo "valid JSON"What each part does:
networkMode: awsvpcis the only mode Fargate supports. Every task gets its own network interface and private IP in your subnet, and the security group applies to that interface.cpuandmemoryare for the whole task.256CPU units is a quarter of a vCPU, the smallest Fargate size, and it can be paired with 512, 1024 or 2048 MiB. Other combinations are rejected when you register.runtimePlatformmust match how the image was built. You built with--platform linux/amd64, so this isX86_64. An image built on an Apple Silicon Mac without that flag is ARM64; setcpuArchitecturetoARM64for it. ARM64 is also cheaper: checked on 26 November 2026, Linux/ARM in US East (N. Virginia) was 0.03238 USD per vCPU-hour against 0.04048 USD for x86, about 20 percent less.executionRoleArnandtaskRoleArnare the two roles from the last step.secretsputs the secret's value into theAPI_TOKENenvironment variable when the container starts. The task definition only holds the ARN. A task that is already running keeps the old value if you change the secret; new tasks pick it up.logConfigurationsends everything the container prints to stdout and stderr to CloudWatch Logs, in streams namedhello-node/web/<task ID>.
Register it. ECS stores it as revision 1 of the hello-node family; each later registration adds a revision, and old ones never change:
aws ecs register-task-definition --cli-input-json file://taskdef-v1.json \
--query 'taskDefinition.[family,revision,status]' --output textCheck it worked
The command prints hello-node, 1 and ACTIVE. Read the secret reference back to see that only the ARN is stored, never the token:
aws ecs describe-task-definition --task-definition "${FAMILY}:1" \
--query 'taskDefinition.containerDefinitions[0].secrets[0].valueFrom' --output textStep 7 · Create a cluster and a service with two tasks
A cluster is a named group for services and tasks. With Fargate it holds no servers, and an empty cluster costs nothing:
aws ecs create-cluster --cluster-name "$CLUSTER" --query 'cluster.status' --output textFrom this command on, AWS bills you until the clean-up step. Create the service: two copies of revision 1, spread over your two subnets, each with a public IP:
aws ecs create-service \
--cluster "$CLUSTER" \
--service-name "$SERVICE" \
--task-definition "${FAMILY}:1" \
--desired-count 2 \
--launch-type FARGATE \
--platform-version LATEST \
--network-configuration "awsvpcConfiguration={subnets=[${SUBNETS}],securityGroups=[${SG_ID}],assignPublicIp=ENABLED}" \
--deployment-configuration "minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}" \
--query 'service.[serviceName,status,desiredCount]' --output text
aws ecs wait services-stable --cluster "$CLUSTER" --services "$SERVICE"assignPublicIp=ENABLEDis required here. A task in a public subnet without a public IP cannot reach ECR, Secrets Manager or CloudWatch, because there is no NAT gateway to send its traffic through, and it fails to start.minimumHealthyPercent=100andmaximumPercent=200mean a deployment starts the new tasks first, up to four in total, and stops old ones only once new ones are running. You never drop below two.- The deployment circuit breaker watches each deployment. If new tasks keep failing to start, ECS stops the deployment and rolls the service back to the last revision that worked.
wait services-stable polls every 15 seconds until both tasks are running, for up to 10 minutes. The first start takes a minute or two while Fargate pulls the image.
Check it worked
aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" \
--query 'services[0].[status,desiredCount,runningCount,launchType]' --output textIt prints ACTIVE, 2, 2 and FARGATE. To call a task, find its public IP through its network interface, then request the page:
TASK_ARN=$(aws ecs list-tasks --cluster "$CLUSTER" --service-name "$SERVICE" \
--query 'taskArns[0]' --output text)
ENI_ID=$(aws ecs describe-tasks --cluster "$CLUSTER" --tasks "$TASK_ARN" \
--query "tasks[0].attachments[0].details[?name=='networkInterfaceId'].value" --output text)
TASK_IP=$(aws ec2 describe-network-interfaces --network-interface-ids "$ENI_ID" \
--query 'NetworkInterfaces[0].Association.PublicIp' --output text)
curl -s "http://${TASK_IP}:${PORT}/"
aws logs tail "$LOG_GROUP" --since 10mcurl prints the app's JSON reply, and logs tail shows whatever the app printed, in streams whose names begin hello-node/web/. If the service never becomes stable, aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" --query 'services[0].events[:5].message' says why; CannotPullContainerError usually means a missing public IP or a wrong image tag, and ResourceInitializationError mentioning secrets means the execution role cannot read the secret.
Step 8 · Roll out a new revision
Any change to what runs (a new image tag, an environment variable, more memory) is a new task definition revision that you point the service at. Here the change is a container health check, so ECS replaces a task whose app stops answering even though its process is still alive. The check runs inside the container, so it uses node from the image rather than curl, which the slim Node.js image does not have.
Build revision 2 from revision 1 with jq, so the rest of the file stays exactly as it was:
jq '.containerDefinitions[0].healthCheck = {
"command": ["CMD", "node", "-e", "fetch(\"http://127.0.0.1:" + (.containerDefinitions[0].portMappings[0].containerPort | tostring) + "/\").then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 15
}' taskdef-v1.json > taskdef-v2.json
aws ecs register-task-definition --cli-input-json file://taskdef-v2.json \
--query 'taskDefinition.revision' --output textThe health-check command must exist inside the image. If you run your own image instead of hello-node and it has no Node.js (the nginx image from the ECR tutorial, for example), use a command that image has, such as ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1/ || exit 1"]; otherwise every new task goes UNHEALTHY and the circuit breaker rolls the service back to revision 1.
The registration prints 2. Now move the service to it and wait:
aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" \
--task-definition "${FAMILY}:2" --query 'service.taskDefinition' --output text
aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" \
--query 'services[0].deployments[].[status,taskDefinition,runningCount]' --output text
aws ecs wait services-stable --cluster "$CLUSTER" --services "$SERVICE"Run the describe-services line a few times while you wait. During the rollout it shows two deployments: PRIMARY with revision 2, its running count climbing to 2, and ACTIVE with revision 1, still serving until the new tasks are healthy. Then the old deployment disappears.
If you shipped a broken revision, roll back the same way: update-service with --task-definition hello-node:1. Revisions never change, so revision 1 is exactly what ran before.
Check it worked
aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" \
--query 'services[0].[taskDefinition,runningCount]' --output textIt prints an ARN ending in task-definition/hello-node:2 and 2. A task's health now shows in aws ecs describe-tasks ... --query 'tasks[0].healthStatus' as HEALTHY once the first checks pass.
Step 9 · Scale to zero and delete everything
Scaling to zero stops the tasks, and with them the Fargate and public IP charges, while keeping the service's settings. That is enough if you want to come back tomorrow:
aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" \
--desired-count 0 --query 'service.desiredCount' --output text
aws ecs wait services-stable --cluster "$CLUSTER" --services "$SERVICE"To remove it all, delete the service and wait until it is gone, then the cluster, and deregister both revisions:
aws ecs delete-service --cluster "$CLUSTER" --service "$SERVICE" --query 'service.status' --output text
aws ecs wait services-inactive --cluster "$CLUSTER" --services "$SERVICE"
aws ecs delete-cluster --cluster "$CLUSTER" --query 'cluster.status' --output text
aws ecs deregister-task-definition --task-definition "${FAMILY}:1" --query 'taskDefinition.status' --output text
aws ecs deregister-task-definition --task-definition "${FAMILY}:2" --query 'taskDefinition.status' --output textDeregistered revisions are marked INACTIVE and cost nothing; aws ecs delete-task-definitions removes them for good if you want a tidy list.
The next command deletes the secret immediately, with no recovery window. Make sure nothing else uses hello-node/api-token first. Then remove the log group, the roles and the security group:
aws secretsmanager delete-secret --secret-id "$SECRET_ARN" --force-delete-without-recovery \
--query Name --output text
aws logs delete-log-group --log-group-name "$LOG_GROUP"
aws iam delete-role-policy --role-name hello-node-execution --policy-name start-hello-node
aws iam delete-role --role-name hello-node-execution
aws iam delete-role --role-name hello-node-task
aws ec2 delete-security-group --group-id "$SG_ID"
cd ~
rm -rf ~/fargate-demoIf delete-security-group fails with DependencyViolation, the stopped tasks' network interfaces are still being released. Wait a minute and run it again.
Last, the ECR repository, which bills for the storage its image uses. --force deletes the repository together with every image in it, and there is no undo, so skip this command if you pointed REPO at a repository you want to keep:
aws ecr delete-repository --repository-name "$REPO" --force \
--query 'repository.repositoryName' --output textCheck it worked
aws ecs describe-clusters --clusters hello-node --query 'clusters[0].status' --output text
aws iam list-roles --query "Roles[?starts_with(RoleName, 'hello-node')].RoleName" --output text
aws ec2 describe-security-groups --filters Name=group-name,Values=hello-node-tasks \
--query 'SecurityGroups[].GroupId' --output text
aws ecr describe-repositories --query "repositories[?repositoryName=='hello-node'].repositoryName" --output textThe first command prints INACTIVE, and the other three print nothing. In the Billing console, Fargate charges stop growing from the moment the tasks stopped.
Next steps
- Tighten who can reach the tasks with security groups and network ACLs: control traffic with security groups and network ACLs.
Related tutorials
- How to Write a Dockerfile for a Node.js AppYou will write a Dockerfile for a small Express app on Node.js 26, build it into an image, run it as a container on port 3000 as a non-root user, and order the file so rebuilds take seconds.
- Control traffic in AWS with security groups and network ACLsYou will build a three-tier set of security groups that chain by group ID, add a network ACL that blocks one abusive address range at the subnet edge, and run a query that lists every rule open to the whole internet.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials