// Why this matters
If you need to deploy a Flask API on ECS Fargate with Terraform, the real work is not the container. It is the dozen supporting resources that make it reachable, private, observable and elastic. Teams that click these together in the console end up with an environment nobody can reproduce, and the first time someone needs a second copy (staging, a new region, a customer-isolated stack) the clicking starts again.
Fargate removes the node fleet from the picture: no AMIs to patch, no capacity to bin-pack, no cluster autoscaler. What you pay for is vCPU and memory per running task. That makes the scaling policy the main cost lever, so it deserves to be explicit code that a reviewer can read, not a console setting someone tuned once.
This article walks through a layout we have used for small and mid-size HTTP APIs: a file per concern, security-group-to-security-group rules, a JSON task-definition template, and step scaling on CPU. It is deliberately plain Terraform with a thin Makefile, which keeps it easy to hand over to a team that does not want a framework.
// The problem
The brief was simple to state: host a containerised REST API without managing servers, make it survive load spikes, and make the whole thing repeatable from a clean account. The pain sits in the details. A load balancer that cannot reach tasks because the target type is wrong, tasks that restart in a loop because the health check path returns a redirect, a service that scales up but never back down, a task that cannot pull its image because the execution role is missing a policy.
Constraints we worked within: the API is stateless, traffic is bursty rather than constant, the operators are not Kubernetes people, and the delivery had to be a folder of Terraform they can read in an afternoon. Anything requiring a bespoke controller or a service mesh was out.
Without codifying this, the failure modes are quiet. A hand-built service with a fixed count of two tasks works until a marketing email lands, then falls over. A service with an over-generous fixed count of ten works but costs five times what it should overnight.
// The solution
The architecture is the standard Fargate shape. A VPC with public subnets (ALB, NAT gateways) and private subnets (tasks) across two or more availability zones. An Application Load Balancer in the public subnets forwards to an IP-type target group. An ECS cluster and a service running a task definition on Fargate in the private subnets. An execution role lets ECS pull the image and write logs. CloudWatch collects container logs and the CPU metrics that drive scaling.
Security is expressed as references between groups. The load balancer group accepts the public listener port from the internet; the task group accepts the container port only from the load balancer group. Nothing about a task is reachable from anywhere else, and if the subnets are re-addressed the rules still hold. Egress goes through NAT so tasks can reach package mirrors and third-party APIs without public addresses.
For scaling we chose step scaling driven by two alarms rather than target tracking. Target tracking is the better default for most services, and we say so below, but step policies make the thresholds and the cooldown explicit and are easy to explain to a client: at or above 85 percent average CPU for two minutes add a task, at or below 10 percent for two minutes remove one, with a 60 second cooldown, between a minimum of 3 and a maximum of 6 tasks.
The container definition is rendered from a JSON template so the image, ports, log configuration and resource sizes come from variables. We considered inlining it with jsonencode and that is what we would do today; the template file was chosen because the people maintaining it were already comfortable editing ECS JSON copied from the console. Both are shown, because the choice is mostly taste.
- Docker imageFlask API with a health-check route, pipenv-locked
- VPC networkpublic and private subnets, IGW, NAT, route tables
- Security groupstasks accept traffic only from the load balancer group
- ALBpublic subnets, IP target group, health checks, listener
- Fargate servicetask definition from a JSON template, private subnets
- IAMexecution role for image pull and logging
- Alarms gateCPU at or above 85% scales up; at or below 10% scales down
- Auto scalingmin 3, max 6 tasks, 60s cooldown
- Logscontainer log group in CloudWatch
// Before you start
- Terraform 1.5 or newer and the AWS provider 5.x; a remote state backend (S3 plus locking) is strongly recommended.
- An AWS account and a role with permissions for VPC, ECS, ELB, IAM roles, CloudWatch and Application Auto Scaling.
- Docker, and an ECR repository (or any registry the tasks can reach) to hold the image.
- Python 3.8+ and pipenv if you want to run the Flask app locally.
- Working knowledge of CIDR planning and how ALB target groups differ between instance and IP targets.
// Step-by-step implementation
01 Lay out the project one concern per file
Split the root module by concern: network, alb, security, roles, ecs, auto_scaling, logs, plus variables and outputs. It looks like ceremony for a small stack, but it pays off the first time a reviewer asks "where is the scaling threshold". Nobody has to search a 600 line main.tf.
Keep the container source next to the infrastructure in an app directory so a change to either shows up in one pull request. Pin the AWS provider and Terraform versions so a teammate running a newer binary does not produce a different plan.
02 Define the variables that matter
Expose only what operators legitimately change: image, CPU, memory, desired count and bounds, the listener port and the health check path. Everything else is a local. Fargate only accepts specific CPU and memory pairs, so document them in the description rather than discovering it at apply time.
03 Build the network: public edge, private compute
One public and one private subnet per availability zone, carved from the VPC range with cidrsubnet. Each private subnet routes to a NAT gateway in the public subnet of the same zone, so losing a zone does not take out egress for the others. For a cost-sensitive dev stack you can use a single NAT, but make that a conscious variable, not an accident.
04 Chain the security groups
The load balancer group is the only one with an internet CIDR. The task group references the load balancer group as its source, which means the rule says "traffic from the load balancer" rather than "traffic from these addresses". Tasks need outbound access for image pulls through NAT and for any downstream calls, so egress stays open; tighten it with VPC endpoints later if you need a zero-internet posture.
05 Add the ALB, IP target group and health check
Fargate tasks with awsvpc networking register by IP, so the target group must be type ip; getting this wrong gives a target group that silently stays empty. The health check path must return a plain 200. A route that redirects will mark every task unhealthy and ECS will cycle them forever, which is the single most common first-deploy failure.
We gave the service a health check grace period so slow-starting containers (a Python app loading a model, for instance) are not killed while still booting.
06 Create the Flask container and the task definition
The app is intentionally tiny: a root route that returns 200 for the load balancer, and a REST resource. Install dependencies from the lock file with pipenv so a build next month resolves the same versions. In production, run it under gunicorn rather than the Flask development server, and do not set debug mode.
The task definition is rendered from a JSON template. It carries the port mapping and a log configuration pointing at the log group we create next.
07 Wire the cluster, execution role, service and logs
The execution role is what ECS itself uses to pull the image and ship logs; it is not the role your application code runs under. Attach the managed task-execution policy and nothing broader. If the app needs AWS APIs, add a separate task role.
Tasks go in the private subnets with no public address. The service depends on the listener so Terraform does not try to attach a service to a load balancer that has no listener yet, which fails with a confusing error.
08 Add CPU alarms and step-scaling policies
Register the service as a scalable target with a floor and a ceiling, then create two step policies and two alarms. The up policy applies when the metric is above the alarm threshold (lower bound 0 relative to the threshold); the down policy applies when it is below (upper bound 0). Evaluating over two one-minute periods filters out momentary spikes, and the 60 second cooldown stops the service oscillating.
Step scaling gives you explicit control. If you would rather not tune thresholds, replace the two policies and alarms with one target tracking policy on average CPU at, say, 60 percent. It reacts proportionally and removes the need for a low-end alarm. We kept the step form here because the thresholds were part of the agreed behaviour.
09 Wrap it in a Makefile and deploy
A three-target Makefile is enough: build and push the image, plan, apply. It keeps the commands identical between laptops and CI and gives a handover team one obvious entry point. Build the image first because the service needs a pullable tag on first apply.
// How to verify it works
- Run
terraform outputand open the load balancer DNS name on the listener port: the root route should return HTTP 200. aws ecs describe-services --cluster flask-api --services flask-api --query "services[0].[runningCount,desiredCount]"should show the minimum task count on both sides.aws elbv2 describe-target-health --target-group-arn <tg-arn>should list every task IP as healthy.- Try to reach a task IP directly from outside the VPC: it must time out, proving the security group chain works.
- Generate load with a tool such as hey for a few minutes and watch
aws application-autoscaling describe-scaling-activities --service-namespace ecsshow a scale-up, then a scale-down after load stops.
// Design decisions and trade-offs
- Security-group-to-security-group rules instead of CIDRs; NAT gives private egress.
- File-per-concern layout: network, alb, ecs, auto_scaling, security, roles, logs.
- Image, CPU, memory and task count exposed as variables.
// Pitfalls and lessons learned
- Target type instance with awsvpc tasks: the group stays empty and the ALB returns 503. Use ip.
- A health check path that redirects (301/302) or needs auth marks tasks unhealthy and triggers a restart loop. Serve a dedicated 200 route.
- Forgetting
ignore_changes = [desired_count]makes every apply reset the autoscaler decision. - Private subnets without a working NAT route cannot pull the image, and the task stops with a "CannotPullContainerError" a minute later.
- Invalid CPU and memory pairs only fail at apply time. Keep the allowed combinations in the variable description.
- Running the Flask development server with debug on in the container exposes an interactive debugger. Use gunicorn.
- A default 300 second deregistration delay makes deploys and scale-in feel hung.
// Frequently asked questions
How do I deploy a Flask API on ECS Fargate with Terraform?
Build a Docker image and push it to ECR, then use Terraform for a VPC with public and private subnets, an ALB with an IP target group, an ECS cluster, a task definition, a Fargate service in the private subnets and an execution role. This article contains each file.
Should I use step scaling or target tracking for ECS?
Target tracking is simpler and usually better. Choose step scaling when you want explicit thresholds and cooldowns, or need different behaviour at different severity levels.
Why does my ECS service keep restarting tasks?
Almost always the health check: wrong path, a redirect, a wrong port, or no grace period for a slow start. Check the target group health reason first.
Do Fargate tasks need public IPs?
No. Put them in private subnets and route egress through NAT or VPC endpoints. Only the load balancer needs to be public.
How do I roll out a new image?
Apply with a new image tag so the task definition revision changes. ECS replaces tasks gradually behind the load balancer; see ECS Blue/Green Deployments with CodeDeploy and GitHub Actions for a staged variant.
// The outcome
Server-less hosting that scales itself, delivered as plain Terraform with a Makefile wrapper.
// Where to take it next
- Terminate TLS on the listener with an ACM certificate and redirect port 80.
- Move to blue/green deployments with ECS Blue/Green Deployments with CodeDeploy and GitHub Actions.
- Add a request-count or latency alarm alongside CPU, and a dashboard for it.
- Replace the NAT dependency with VPC endpoints for ECR, logs and S3 to cut egress cost, and consider Cloud Governance as Code with Cloud Custodian to police tagging.