
Running a Python application locally is usually straightforward. We install the dependencies, start the server, and test the endpoints.
The challenge begins when we need to deploy that application to production.
We need to think about containerization, networking, security, scaling, logs, and deployment automation. Manually creating every AWS resource through the console can work for a small experiment, but it becomes difficult to maintain as the application grows.
This is where AWS ECS Fargate and Terraform fit together.
Amazon ECS helps us manage containerized applications. Fargate runs those containers without requiring us to manage EC2 instances. Terraform lets us define AWS infrastructure in code, so we can version, review, and reproduce our deployment.
In this guide, we’ll deploy a small FastAPI application to AWS ECS Fargate using Terraform. We’ll create a Docker image, push it to Amazon ECR, configure an ECS service, and expose the application through an Application Load Balancer.
We’ll also cover the practical details that matter in production, including IAM roles, private networking, health checks, secrets, and deployment safety.
1. Understanding the Deployment Architecture
Before writing Terraform, it helps to understand how the components work together.
Our application will use this architecture:
Internet
|
v
Application Load Balancer
|
v
ECS Service
|
-------------------
| |
v v
Fargate Task Fargate Task
FastAPI FastAPI
| |
-------------------
|
CloudWatch Logs
ECR stores the container image
Terraform manages the infrastructureEach component has a specific responsibility:
AWS service | Purpose |
|---|---|
Amazon ECR | Stores the Docker image |
Amazon ECS | Manages the application service and tasks |
AWS Fargate | Runs the containers without managing servers |
Application Load Balancer | Routes traffic to healthy tasks |
IAM | Controls permissions |
CloudWatch Logs | Stores application logs |
Terraform | Defines and manages the infrastructure |
The load balancer sends requests to healthy Fargate tasks. ECS maintains the desired number of running tasks and can replace tasks that stop or become unhealthy.
2. What Is ECS Fargate?
Amazon ECS is a container orchestration service. It helps us deploy, manage, and scale containerized applications.
An ECS deployment commonly uses three concepts:
Cluster: A logical grouping for ECS workloads.
Task definition: The configuration for running a container, including its image, CPU, memory, ports, and environment.
Service: Maintains the desired number of running tasks and manages deployments.
Fargate is the compute engine that runs the containers. We don’t need to provision or patch EC2 instances ourselves.
For example, if our service is configured with two tasks, ECS attempts to keep two application instances running:
ECS Service
desired_count = 2
├── Fargate Task 1
│ └── FastAPI Container
│
└── Fargate Task 2
└── FastAPI ContainerThis is useful when we want to focus on application development instead of managing the underlying servers.
3. Create a FastAPI Application
Let’s start with a small Python application.
Create the following project structure:
fastapi-ecs/
├── app/
│ └── main.py
├── requirements.txt
├── Dockerfile
└── terraform/
├── main.tf
├── variables.tf
└── outputs.tfCreate app/main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {
"message": "Hello from FastAPI on AWS ECS Fargate"
}
@app.get("/health")
async def health():
return {
"status": "healthy"
}The / endpoint returns a simple response. The /health endpoint will be used by the load balancer and container health checks.
Create requirements.txt:
fastapi
uvicorn[standard]For a production application, pin dependency versions and use a repeatable dependency-management process.
4. Containerize the Application
ECS Fargate runs containers, so we need to package our FastAPI application into a Docker image.
Create a Dockerfile:
FROM python:3.12-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]A few choices here are worth understanding:
python:3.12-slimprovides a relatively small Python base image.PYTHONUNBUFFERED=1helps logs appear promptly.Installing dependencies before copying application code improves Docker layer caching.
Uvicorn listens on
0.0.0.0, allowing traffic to reach the application inside the container.
Build and run the image locally:
docker build -t fastapi-ecs .
docker run -p 8000:8000 fastapi-ecsOpen http://localhost:8000 and verify that the API responds.
5. Prepare AWS and Terraform
Before creating AWS resources, configure the AWS CLI.
aws configureFor production environments, prefer short-lived credentials through IAM Identity Center or an assumed role rather than long-lived access keys.
Verify your AWS identity:
aws sts get-caller-identityInstall Terraform and create the terraform directory.
For this walkthrough, we’ll use an existing VPC with:
Two public subnets for the Application Load Balancer
Two private subnets for ECS tasks
A NAT gateway or appropriate VPC endpoints for private-task access to AWS services
Using an existing VPC keeps the example focused on deploying the application. The private tasks still need a network path to pull their container image and reach any required AWS services.
6. Define Terraform Variables
Create terraform/variables.tf:
variable "aws_region" {
type = string
default = "ap-south-1"
}
variable "project_name" {
type = string
default = "fastapi-app"
}
variable "vpc_id" {
type = string
}
variable "public_subnet_ids" {
type = list(string)
}
variable "private_subnet_ids" {
type = list(string)
}
variable "container_image" {
type = string
description = "Full container image URI, including its tag"
}
variable "desired_count" {
type = number
default = 2
}The region ap-south-1 is AWS Mumbai. Select a region based on your users, data residency requirements, and infrastructure availability.
7. Configure the AWS Provider
Create terraform/main.tf:
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}Pinning the provider version helps make Terraform behavior more predictable. Commit the generated .terraform.lock.hcl file so the team uses consistent provider versions.
8. Create an ECR Repository
Amazon Elastic Container Registry stores the Docker images that ECS will run.
Add this resource to main.tf:
resource "aws_ecr_repository" "app" {
name = var.project_name
image_tag_mutability = "IMMUTABLE"
image_scanning_configuration {
scan_on_push = true
}
}Immutable tags help prevent an existing image tag from being overwritten.
For deployments, use a unique tag such as a Git commit SHA or release version rather than relying on latest.
9. Create the ECS Cluster
Add the ECS cluster:
resource "aws_ecs_cluster" "app" {
name = var.project_name
}The cluster provides a logical grouping for the ECS service and its tasks.
10. Configure IAM Roles
ECS uses two important IAM roles.
Task execution role
The execution role allows ECS to perform startup operations, such as pulling an image from ECR and writing logs to CloudWatch.
resource "aws_iam_role" "ecs_execution_role" {
name = "${var.project_name}-execution-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = {
Service = "ecs-tasks.amazonaws.com"
}
Action = "sts:AssumeRole"
}]
})
}
resource "aws_iam_role_policy_attachment" "execution_policy" {
role = aws_iam_role.ecs_execution_role.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}Application task role
The task role provides AWS permissions to the application running inside the container.
For example, if the FastAPI application needs to access S3, we should grant the required S3 permissions through this role.
resource "aws_iam_role" "ecs_task_role" {
name = "${var.project_name}-task-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = {
Service = "ecs-tasks.amazonaws.com"
}
Action = "sts:AssumeRole"
}]
})
}Keep these roles separate and follow the principle of least privilege. Avoid giving application tasks broad permissions they do not need.
11. Configure CloudWatch Logs
Create a log group:
resource "aws_cloudwatch_log_group" "app" {
name = "/ecs/${var.project_name}"
retention_in_days = 30
}A retention period helps control how long logs are stored and prevents them from accumulating indefinitely.
12. Define the ECS Task
The task definition describes how the FastAPI container should run.
resource "aws_ecs_task_definition" "app" {
family = var.project_name
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = "256"
memory = "512"
execution_role_arn = aws_iam_role.ecs_execution_role.arn
task_role_arn = aws_iam_role.ecs_task_role.arn
container_definitions = jsonencode([
{
name = "fastapi"
image = var.container_image
essential = true
portMappings = [
{
containerPort = 8000
protocol = "tcp"
}
]
logConfiguration = {
logDriver = "awslogs"
options = {
awslogs-group = aws_cloudwatch_log_group.app.name
awslogs-region = var.aws_region
awslogs-stream-prefix = "fastapi"
}
}
healthCheck = {
command = [
"CMD-SHELL",
"python -c \"import urllib.request; urllib.request.urlopen('http://localhost:8000/health')\" || exit 1"
]
interval = 30
timeout = 5
retries = 3
startPeriod = 20
}
}
])
}The task definition specifies the image, CPU, memory, container port, logging configuration, and health check.
The CPU and memory values are a small starting point. Choose a supported Fargate combination based on actual application requirements and load testing.
13. Configure Security Groups
The load balancer should accept internet traffic. The ECS tasks should accept application traffic only from the load balancer.
resource "aws_security_group" "alb" {
name = "${var.project_name}-alb-sg"
vpc_id = var.vpc_id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_security_group" "ecs" {
name = "${var.project_name}-ecs-sg"
vpc_id = var.vpc_id
ingress {
from_port = 8000
to_port = 8000
protocol = "tcp"
security_groups = [aws_security_group.alb.id]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}The ECS tasks are not directly exposed to the public internet.
For production, configure HTTPS and review outbound network permissions based on the services your application needs.
14. Create the Application Load Balancer
The Application Load Balancer routes requests to healthy ECS tasks.
resource "aws_lb" "app" {
name = "${var.project_name}-alb"
load_balancer_type = "application"
subnets = var.public_subnet_ids
security_groups = [aws_security_group.alb.id]
}
resource "aws_lb_target_group" "app" {
name = "${var.project_name}-tg"
port = 8000
protocol = "HTTP"
target_type = "ip"
vpc_id = var.vpc_id
health_check {
path = "/health"
protocol = "HTTP"
matcher = "200"
interval = 30
timeout = 5
healthy_threshold = 2
unhealthy_threshold = 3
}
}
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.app.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.app.arn
}
}For Fargate tasks using awsvpc networking, the target group must use target_type = "ip".
The load balancer checks the /health endpoint and routes traffic only to healthy targets.
15. Create the ECS Service
The ECS service maintains the desired number of running tasks.
resource "aws_ecs_service" "app" {
name = var.project_name
cluster = aws_ecs_cluster.app.id
task_definition = aws_ecs_task_definition.app.arn
desired_count = var.desired_count
launch_type = "FARGATE"
network_configuration {
subnets = var.private_subnet_ids
security_groups = [aws_security_group.ecs.id]
assign_public_ip = false
}
load_balancer {
target_group_arn = aws_lb_target_group.app.arn
container_name = "fastapi"
container_port = 8000
}
depends_on = [
aws_lb_listener.http,
aws_iam_role_policy_attachment.execution_policy,
]
}The service runs the tasks in private subnets without public IP addresses.
Those tasks still need outbound access to pull images and reach required AWS services. This can be provided through a NAT gateway or suitable VPC endpoints.
16. Add Terraform Outputs
Create terraform/outputs.tf:
output "ecr_repository_url" {
value = aws_ecr_repository.app.repository_url
}
output "load_balancer_dns_name" {
value = aws_lb.app.dns_name
}
output "ecs_cluster_name" {
value = aws_ecs_cluster.app.name
}
output "ecs_service_name" {
value = aws_ecs_service.app.name
}These outputs make it easier to retrieve the ECR repository address and application endpoint.
17. Initialize and Apply Terraform
Create terraform.tfvars:
aws_region = "ap-south-1"
project_name = "fastapi-app"
vpc_id = "vpc-xxxxxxxx"
public_subnet_ids = [
"subnet-public-a",
"subnet-public-b"
]
private_subnet_ids = [
"subnet-private-a",
"subnet-private-b"
]
container_image = "replace-after-pushing-image"
desired_count = 2Replace the VPC and subnet IDs with values from your AWS account.
Initialize Terraform:
cd terraform
terraform initReview the planned changes:
terraform planApply the infrastructure:
terraform applyTerraform creates the ECR repository, ECS cluster, IAM roles, task definition, security groups, load balancer, and ECS service.
For a team or production environment, use a remote Terraform backend with state locking and access controls. Terraform state can contain sensitive infrastructure details.
18. Build and Push the Docker Image
Retrieve the ECR repository URL:
terraform output -raw ecr_repository_urlSet the image variables:
AWS_REGION=ap-south-1
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR_REPOSITORY=fastapi-app
IMAGE_TAG=$(git rev-parse --short HEAD)Authenticate Docker with ECR:
aws ecr get-login-password --region "$AWS_REGION" \
| docker login \
--username AWS \
--password-stdin \
"$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com"Build the image:
docker build -t "$ECR_REPOSITORY:$IMAGE_TAG" .Tag the image:
docker tag \
"$ECR_REPOSITORY:$IMAGE_TAG" \
"$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$ECR_REPOSITORY:$IMAGE_TAG"Push it:
docker push \
"$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$ECR_REPOSITORY:$IMAGE_TAG"Use the full image URI, including the unique tag, as the container_image variable.
19. Deploy a New Image Version
When you build a new application version, push it to ECR with a new tag.
Update container_image in your Terraform variables:
container_image = "123456789012.dkr.ecr.ap-south-1.amazonaws.com/fastapi-app:abc1234"Then run:
terraform plan
terraform applyThe updated task definition triggers an ECS deployment.
For production, configure deployment health checks, deployment percentages, and a rollback strategy. A CI/CD pipeline can automate tests, image builds, image scanning, ECR pushes, and deployment updates.
20. Access the Application
Retrieve the load balancer DNS name:
terraform output -raw load_balancer_dns_nameOpen the returned hostname in a browser:
http://your-load-balancer-dns-nameYou should see a response similar to:
{
"message": "Hello from FastAPI on AWS ECS Fargate"
}You can also test:
http://your-load-balancer-dns-name/healthAt this point, the FastAPI application is running on ECS Fargate behind an Application Load Balancer.
21. Manage Secrets Securely
Most real applications need database credentials, API keys, or third-party service tokens.
Avoid hardcoding secrets into:
Docker images
Terraform files
Git repositories
Plain-text container environment variables
AWS Secrets Manager or Systems Manager Parameter Store can store sensitive configuration.
An ECS task definition can reference a secret:
secrets = [
{
name = "DATABASE_URL"
valueFrom = "arn:aws:secretsmanager:ap-south-1:123456789012:secret:database-url"
}
]Use the actual secret ARN from your environment.
The task execution role needs permission to retrieve the referenced secret. If a customer-managed KMS key is used, the role may also need permission to decrypt it.
22. Add HTTPS
The example uses HTTP to keep the first deployment simple.
For production:
Request or import a certificate in AWS Certificate Manager.
Configure an HTTPS listener on port 443.
Attach the certificate to the Application Load Balancer.
Redirect HTTP traffic to HTTPS.
Configure DNS to point your domain to the load balancer.
Allow inbound HTTPS traffic on the ALB security group. Keep the ECS task security group restricted to traffic from the load balancer.
23. Scale ECS Fargate Tasks
Our service currently uses:
desired_count = 2This tells ECS to maintain two running tasks.
For production, ECS Service Auto Scaling can adjust the desired task count based on metrics such as:
Average CPU utilization
Average memory utilization
Request count per target
Custom CloudWatch metrics
Scaling the application does not automatically solve every bottleneck. If the application depends on a database or external API, those dependencies must also be able to handle the additional load.
24. Monitor Logs and Health
The task definition sends container logs to CloudWatch Logs.
You can inspect the log group with:
aws logs describe-log-groups \
--log-group-name-prefix "/ecs/fastapi-app"Monitor important signals:
ECS task restarts
CPU and memory utilization
ALB target health
HTTP 4xx and 5xx responses
Request latency
Application exceptions
Deployment failures
Structured JSON logs and request IDs can make it easier to trace requests across services.
For more advanced observability, consider CloudWatch alarms, AWS X-Ray, or OpenTelemetry tracing.
25. Production Best Practices
Before deploying a production application, review the following:
Keep application tasks in private subnets
Expose the application through the load balancer instead of assigning public IP addresses directly to Fargate tasks.
Follow least-privilege IAM
Separate the task execution role from the application task role. Grant only the permissions each role requires.
Secure Terraform state
Use a remote backend with access controls and state locking. Do not commit Terraform state files to Git.
Use immutable image tags
Use a unique release identifier or commit SHA. This makes deployments reproducible and rollbacks easier.
Configure health checks
Use container and load balancer health checks. Ensure readiness checks reflect the application’s actual ability to serve requests.
Review AWS costs
NAT gateways, load balancers, and data transfer can contribute significantly to costs. Review your network design and AWS pricing before deploying production workloads.
Run migrations separately
If your application uses a relational database, run schema migrations through a controlled deployment job rather than allowing every ECS task to execute migrations during startup.
Test rollback procedures
A rollback should restore a known-good application version without leaving the database in an incompatible state. Prefer backward-compatible database changes during rolling deployments.
Conclusion
AWS ECS Fargate and Terraform provide a practical foundation for deploying Python applications using containers and infrastructure as code.
ECR stores the image, ECS manages the service, Fargate runs the containers, and the Application Load Balancer routes traffic to healthy tasks. Terraform makes the infrastructure repeatable, reviewable, and easier to automate.
The real benefit is not simply running FastAPI in AWS. It is having a deployment process that can be versioned, monitored, scaled, and reproduced.
Start with a small service, validate the deployment, and gradually add HTTPS, secrets management, autoscaling, deployment automation, and monitoring as your application grows.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


