What you’ll build
You will package a small Node.js web app in a Docker image, push the image to Amazon Elastic Container Registry (ECR), and run it on Amazon Elastic Container Service (ECS) with AWS Fargate. Fargate runs containers without EC2 instances for you to manage.
Before you start
- An AWS account and an IAM user with permission to use ECR, ECS, IAM and VPC resources.
- Docker installed and running on your computer.
- The AWS CLI version 2, configured with your credentials.
- Node.js on your computer, to create the app’s
package-lock.json.
Step 1: Write a small app and a Dockerfile
Create a folder with two files. First, app.js:
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send(`Hello from ECS at ${new Date().toISOString()}`);
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Run npm install express in the folder. This creates package.json and package-lock.json.
Second, a Dockerfile:
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
The package-lock.json file lets npm ci install the same versions every time. Add a .dockerignore file that lists node_modules so your local copy does not overwrite the one the image builds.
Step 2: Build and run the image locally
docker build -t hello-app .
docker run -p 3000:3000 hello-app
Open http://localhost:3000 in your browser. Stop the container with Ctrl+C.
If you are on an Apple silicon Mac, build for the platform Fargate uses: docker build --platform linux/amd64 -t hello-app .. An image built for the wrong CPU architecture fails to start on ECS with an exec format error.
Step 3: Create an ECR repository and push the image
Create a repository, log Docker in to ECR, tag the image and push it. Replace 123456789012 with your account ID.
aws ecr create-repository --repository-name hello-app --region us-east-1
aws ecr get-login-password --region us-east-1 | \
docker login --username AWS --password-stdin \
123456789012.dkr.ecr.us-east-1.amazonaws.com
docker tag hello-app:latest \
123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-app:v1
docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-app:v1
Use a versioned tag such as v1. A tag like latest does not update the running service by itself, so versioned tags make it clear which build is running.
Step 4: Create an ECS cluster
Create a cluster to hold the service:
aws ecs create-cluster --cluster-name hello-cluster
An ECS cluster is a logical group. Creating one has no charge by itself. The Fargate capacity is billed when tasks run.
Step 5: Create a task definition
A task definition describes the container: its image, its port and its logs. Create the log group first, then save this as taskdef.json:
aws logs create-log-group --log-group-name /ecs/hello-app
{
"family": "hello-app",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "hello-app",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-app:v1",
"essential": true,
"portMappings": [
{ "containerPort": 3000, "protocol": "tcp" }
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/hello-app",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
}
}
]
}
Register it:
aws ecs register-task-definition --cli-input-json file://taskdef.json
Two roles matter here, and readers often mix them up:
- The task execution role lets ECS pull the image from ECR and write logs to CloudWatch. The AWS managed policy
AmazonECSTaskExecutionRolePolicycovers this. The console can create a role with it for you. - The task role is what your app’s code uses to call other AWS services, such as S3 or DynamoDB. Add it only if the app needs it.
Keep secrets out of the task definition’s plain environment values. Reference them from AWS Secrets Manager or Systems Manager Parameter Store instead.
Step 6: Run a service
A service keeps a number of tasks running. Use the default VPC subnets, and create a security group that allows TCP port 3000 only from your own IP address. Replace the placeholders with your subnet and security group IDs.
aws ecs create-service \
--cluster hello-cluster \
--service-name hello-svc \
--task-definition hello-app \
--desired-count 1 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[<subnet-id>],securityGroups=[<security-group-id>],assignPublicIp=ENABLED}"
assignPublicIp=ENABLED gives the task a public address, so it can reach ECR without extra networking. That is fine for a test. For production, use private subnets with a NAT gateway or VPC endpoints, and put a load balancer in front.
Step 7: Test the app
In the ECS console, open the cluster, then the service, and select the task. The task’s network section shows its public IP address. Open http://<public-ip>:3000 in your browser. You should see the greeting with the current time.
If the page does not load, check that the security group allows port 3000 from your IP address.
Step 8: Update the app
Make a change, build and push a new tag, then register a new revision of the task definition with the new image:
docker build -t hello-app .
docker tag hello-app:latest 123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-app:v2
docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-app:v2
Edit taskdef.json to use hello-app:v2, register the task definition again, and point the service at the new revision:
aws ecs update-service \
--cluster hello-cluster \
--service hello-svc \
--task-definition hello-app:2
ECS starts new tasks with the new image and stops the old ones. The deployment circuit breaker can roll back a failed deployment automatically if you turn it on.
Clean up
Remove the service first, then the cluster and the image repository:
aws ecs update-service --cluster hello-cluster --service hello-svc --desired-count 0
aws ecs delete-service --cluster hello-cluster --service hello-svc --force
aws ecs delete-cluster --cluster hello-cluster
aws ecr delete-repository --repository-name hello-app --force
aws logs delete-log-group --log-group-name /ecs/hello-app
Check the security group you created, and delete it if you no longer need it.
Costs
- Fargate bills per vCPU-hour and per GB-hour of memory while tasks run. In us-east-1 on Linux x86, the rates are about $0.04048 per vCPU-hour and $0.004445 per GB-hour. Check the pricing page for current rates. Fargate Spot can cost less for tasks that can be interrupted.
- ECS itself has no control plane fee.
- ECR charges for the storage of your images.
- Public IPv4 addresses cost about $0.005 per hour each.
- A load balancer adds its own hourly charge, if you add one.
Troubleshooting
CannotPullContainerError. The task cannot reach ECR. In a public subnet, enable “Assign public IP”. In a private subnet, add a NAT gateway or VPC endpoints for ECR and CloudWatch Logs. Also check that the execution role has the ECR permissions.exec format errorin the logs. The image was built for a different CPU architecture. Rebuild with--platform linux/amd64, or set the task to ARM64 and build for ARM.- The task starts, then stops. Read the task’s logs in CloudWatch under
/ecs/hello-app. A common cause is an app that listens on a different port from the port mapping. - The page does not load. Check the security group’s port and source IP, and that the task is in the RUNNING state.
Next steps
- Compare EKS for Kubernetes workloads in the EKS setup guide, and read can Kubernetes be used on AWS for the options.
- Add a database for the app with the Amazon RDS guide.
- Read the guide to avoiding unexpected AWS charges before you leave the service running.