How to Use AWS ECS Fargate

Pratiksha kadamPratiksha kadam
8 min read

Are you looking for a way to run Docker containers in the cloud without managing servers?

AWS ECS Fargate is your go-to solution! With ECS Fargate, you can focus on building and deploying your containerized application, while AWS takes care of the infrastructure behind the scenes. It’s like getting a chauffeur for your containers — just sit back and enjoy the ride.

In this article, we’ll walk through the simple steps to run your first Docker container using AWS ECS Fargate. Whether you’re a beginner or someone just exploring cloud-native tools, you’ll find this guide beginner-friendly and easy to follow. Let’s dive in!


What is AWS ECS Fargate?

Before we jump into the setup, let’s get a quick understanding. AWS ECS (Elastic Container Service) is a fully managed container orchestration service. Fargate is the serverless compute engine for containers on ECS — it removes the need to provision and manage servers.

With Fargate, you don’t need to worry about EC2 instances or clusters. You just define your task, tell AWS what container image to use, and Fargate runs it for you. Simple and powerful.


What You’ll Need Before You Start

Here’s what you’ll need to run your first container:

  • An AWS account (you can sign up for free).

  • Docker installed on your local machine.

  • A Docker image (we’ll use a simple “hello world” container).

  • AWS CLI and ECS CLI (optional but useful).

    Step 1: Create a Simple Docker Image

    First, let’s create a basic Docker container.

  • This image will just return a “Hello from ECS Fargate!” message.

      # Dockerfile
      FROM alpine
      CMD ["echo", "Hello from ECS Fargate!"]
    

    Save this as Dockerfile in a new directory, and then build and tag your image:

      docker build -t hello-fargate .
    

    Once it’s built, you’ll need to push it to a container registry. For AWS, we’ll use Amazon ECR (Elastic Container Registry).


    Step 2: Push Docker Image to Amazon ECR

    To use your image with ECS, it needs to live in ECR. First, create a new ECR repository:

      aws ecr create-repository --repository-name hello-fargate
    

    Authenticate Docker with ECR:

      aws ecr get-login-password | docker login --username AWS --password-stdin [your_aws_account_id].dkr.ecr.[region].amazonaws.com
    

    Then tag and push your image:

      docker tag hello-fargate:latest [your_aws_account_id].dkr.ecr.[region].amazonaws.com/hello-fargate
      docker push [your_aws_account_id].dkr.ecr.[region].amazonaws.com/hello-fargate
    

    Step 3: Create a Task Definition in ECS

    Now, go to the AWS Console → ECS → Task Definitions → Create New Task Definition. Choose “Fargate” as the launch type.

    Under container definitions:

    • Name: hello-fargate

    • Image: Paste the full ECR URL of your Docker image

    • Memory: 512 MB

    • CPU: 256

Save the task definition and you're almost there.


Step 4: Run Your Task Using Fargate

Now go to ECS → Clusters → Create Cluster → Choose “Networking Only” (Fargate). Name your cluster and create it.

Then go to the cluster → Tasks → Run New Task:

  • Launch Type: Fargate

  • Task Definition: Select your created task

  • Platform version: Latest

  • Cluster: Select your cluster

  • Subnets and Security Groups: Choose default or configure as needed

  • Auto-assign public IP: ENABLED

Click “Run Task” and AWS will handle the rest!


Step 5: Verify the Output

After the task runs, click on it and scroll to the logs section. You should see the output:

    Hello from ECS Fargate!

Congratulations! You've just run your first Docker container using ECS Fargate — no servers, no stress.


Why Fargate Rocks

Fargate makes life easier for developers and teams who want to scale quickly without getting lost in infrastructure. It’s perfect for microservices, quick deployments, and even testing container apps on the fly.

It also integrates beautifully with other AWS services like CloudWatch, ALB (Application Load Balancer), and IAM for fine-grained control and observability.


Wrap-Up

Getting started with ECS Fargate is surprisingly easy, and it opens the door to scalable, managed container deployments. If you’re already working with Docker locally, transitioning to the cloud with Fargate is a logical next step — and it doesn't require becoming a DevOps guru overnight.

Whether you’re spinning up microservices or testing an MVP, ECS Fargate provides the tools and scalability you need, without the complexity of managing the infrastructure.


FAQs

1. Can I use ECS Fargate for production workloads?
Absolutely! Fargate is highly reliable and scalable. Many companies run full production workloads on it.

2. Do I need to learn Kubernetes to use ECS Fargate?
Nope! ECS is simpler than Kubernetes and you can use it with or without knowing k8s.

3. How is ECS different from EKS?
ECS is Amazon’s own container orchestration system, while EKS is based on Kubernetes. ECS is simpler; EKS offers more flexibility for Kubernetes users.

4. Can I run multiple containers in a single Fargate task?
Yes, just like in Docker Compose, you can define multiple containers in one task definition.

5. Is ECS Fargate expensive?
Pricing is based on vCPU and memory used. It’s pay-as-you-go, so it can be cost-effective for intermittent or small workloads.


AWS ECS Fargate (Terraform Edition)

If you've already run your first Docker container with AWS ECS Fargate and want to level up, it’s time to automate your setup using Terraform.

  • Infrastructure as Code (IaC) is a must-have for managing scalable and repeatable deployments, and Terraform makes it dead simple to define cloud resources in a clean, version-controlled way.

    In this extended guide, we’ll walk through how to provision an ECS Fargate service that runs your Docker container using Terraform — from the container definition to networking and auto-scaling. Let’s automate everything!


    Terraform Setup

    In the first tutorial, we did everything manually via the AWS Console. This time, we’ll:

    • Use Terraform to define infrastructure.

    • Automatically provision VPC, subnets, security groups, and IAM roles.

    • Deploy a containerized app using ECS Fargate.

    • (Optional) Attach an Application Load Balancer for external access.


🛠️ Pre-Requisites

Before we begin, make sure you have:

  • Terraform installed (v1.3 or newer).

  • An AWS CLI profile configured.

  • Docker image pushed to ECR (from the previous guide or any valid image).


Folder Structure

Here’s a suggested structure for your Terraform project:

    ecs-fargate-terraform/
    │
    ├── main.tf
    ├── variables.tf
    ├── outputs.tf
    └── terraform.tfvars

Let’s populate these step-by-step.


Step 1: Define Variables in variables.tf

    variable "region" {
      default = "us-east-1"
    }

    variable "app_name" {
      default = "hello-fargate"
    }

    variable "ecr_image" {
      description = "Full ECR image URI"
      type        = string
    }

Step 2: Set Your Values in terraform.tfvars

    region    = "us-east-1"
    app_name  = "hello-fargate"
    ecr_image = "123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-fargate:latest"

Step 3: Create Infrastructure in main.tf

Here’s where the magic happens — we’ll define a VPC, subnets, ECS cluster, IAM roles, security group, task definition, and a Fargate service.

    provider "aws" {
      region = var.region
    }

    # Create a VPC and networking
    module "vpc" {
      source  = "terraform-aws-modules/vpc/aws"
      version = "3.19.0"
      name = "${var.app_name}-vpc"
      cidr = "10.0.0.0/16"

      azs             = ["${var.region}a", "${var.region}b"]
      public_subnets  = ["10.0.1.0/24", "10.0.2.0/24"]

      enable_nat_gateway = false
      single_nat_gateway = true

      tags = {
        Name = "${var.app_name}-vpc"
      }
    }

    # Security group for ECS service
    resource "aws_security_group" "ecs_sg" {
      name        = "${var.app_name}-sg"
      description = "Allow HTTP"
      vpc_id      = module.vpc.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"]
      }
    }

    # ECS Cluster
    resource "aws_ecs_cluster" "cluster" {
      name = "${var.app_name}-cluster"
    }

    # IAM Role for Task Execution
    resource "aws_iam_role" "ecs_task_execution_role" {
      name = "${var.app_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" "ecs_execution_policy" {
      role       = aws_iam_role.ecs_task_execution_role.name
      policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
    }

    # Task Definition
    resource "aws_ecs_task_definition" "task" {
      family                   = "${var.app_name}-task"
      requires_compatibilities = ["FARGATE"]
      cpu                      = "256"
      memory                   = "512"
      network_mode             = "awsvpc"
      execution_role_arn       = aws_iam_role.ecs_task_execution_role.arn

      container_definitions = jsonencode([
        {
          name      = "app"
          image     = var.ecr_image
          essential = true
          portMappings = [
            {
              containerPort = 80
              hostPort      = 80
            }
          ]
        }
      ])
    }

    # Fargate Service
    resource "aws_ecs_service" "service" {
      name            = "${var.app_name}-service"
      cluster         = aws_ecs_cluster.cluster.id
      task_definition = aws_ecs_task_definition.task.arn
      desired_count   = 1
      launch_type     = "FARGATE"

      network_configuration {
        subnets         = module.vpc.public_subnets
        security_groups = [aws_security_group.ecs_sg.id]
        assign_public_ip = true
      }

      depends_on = [
        aws_iam_role_policy_attachment.ecs_execution_policy
      ]
    }

Step 4: Outputs in outputs.tf

    output "cluster_name" {
      value = aws_ecs_cluster.cluster.name
    }

    output "service_name" {
      value = aws_ecs_service.service.name
    }

    output "task_definition" {
      value = aws_ecs_task_definition.task.family
    }

Step 5: Run Terraform

Initialize, plan, and apply your Terraform configuration:

    terraform init
    terraform plan
    terraform apply

After a few minutes, Terraform will have fully provisioned:

  • A VPC and public subnets

  • ECS cluster

  • IAM roles and permissions

  • Security groups

  • Your Docker container running on Fargate 🎉


Optional: Add Load Balancer for Public Access

Want to make your app accessible via the browser? You can add an ALB (Application Load Balancer) and point it to your Fargate service. This requires target groups and listeners — let me know if you'd like a step-by-step on that too!


Why Use Terraform for ECS Fargate?

Using Terraform:

  • Makes deployments reproducible

  • Avoids manual errors

  • Supports version control

  • Enables easy rollbacks

  • Scales effortlessly as your architecture grows

This is essential if you're deploying in a team or automating CI/CD pipelines.


Wrap-Up

And that’s how you go from a basic Docker container to a fully managed ECS Fargate deployment powered by Terraform! You now have the tools to define scalable infrastructure, handle complex applications, and automate deployments with ease.

Remember — containers are the future, but automation is the real power play. With ECS Fargate and Terraform together, you’re ready to handle production-grade infrastructure like a pro.


FAQs

1. Can I update my Docker image without destroying everything in Terraform?
Yes! You can simply update the ECR image tag and rerun terraform apply. It’ll update the task definition.

2. How do I auto-scale ECS Fargate services?
You can attach ECS service autoscaling policies using aws_appautoscaling_* resources in Terraform.

3. Is Terraform better than AWS CloudFormation?
Terraform is cloud-agnostic, has a cleaner syntax, and often preferred by DevOps teams. But both are valid.

4. Can I deploy multiple containers in the same task?
Yes! Just add more container definitions in the container_definitions JSON array.

5. Do I need to recreate the whole cluster to make changes?
Not usually. Terraform is smart enough to update only what’s necessary — as long as you define changes correctly.

0
Subscribe to my newsletter

Read articles from Pratiksha kadam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pratiksha kadam
Pratiksha kadam