Table of Contents

Introduction
Business Requirements
Architecture
Pre-requisites
Implementation Steps in Words
Technical Implementation Steps
Pipeline Configuration
Key Benefits
Conclusion

1. Introduction

Modern application delivery demands speed, scalability, and reliability. Running workloads on traditional servers often introduces overhead — managing OS patches, scaling infrastructure manually, and dealing with environment inconsistencies between development and production.
This blog walks you through a fully automated, Infrastructure-as-Code (IaC) driven deployment of a containerized web application on AWS ECS Fargate using Terraform and AWS CodeBuild. The entire infrastructure — from container registry to load balancer — is provisioned and torn down through automated pipelines, eliminating manual intervention and enabling repeatable deployments.
By the end of this guide, you will understand:

How to containerize a simple Apache web server using Docker
How to provision AWS ECS Fargate infrastructure using Terraform
How to automate the full deploy and destroy lifecycle using AWS CodeBuild buildspec files.

2. Business Requirements

Organizations moving to the cloud typically have the following non-negotiable requirements:

Requirement How This Project Addresses It
Zero server management AWS Fargate removes the need to provision or manage EC2 instances
Automated deployments AWS CodeBuild pipelines handle build, push, and deploy automatically
Cost control Infrastructure can be destroyed on demand using the destroy pipeline
High availability ECS service runs 2 task replicas across multiple private subnets
Security Containers run in private subnets; only the ALB is internet-facing
Centralized logging All container logs are shipped to AWS CloudWatch with KMS encryption
State management Terraform remote state is stored in S3 for team collaboration

3. Architecture

 ┌─────────────────────────────────────────────────────────────┐ │ AWS Cloud (us-east-1) │ │ │ User Request │ ┌──────────────┐ ┌──────────────────────────────┐ │ ──────────────────────►│ │ Application │ │ VPC (custom-vpc) │ │ Port 80 │ │ Load Balancer │ │ │ │ │ │ (internet- │ │ Public Subnets │ │ │ │ facing) │ │ ┌──────────┐ ┌──────────┐ │ │ │ │ │◄───────┤ │ public-1 │ │ public-2 │ │ │ │ │ SG: SG_LB │ │ └──────────┘ └──────────┘ │ │ │ └──────┬───────┘ │ │ │ │ │ Port 8080 │ Private Subnets │ │ │ ▼ │ ┌──────────────────────┐ │ │ │ ┌──────────────┐ │ │ ECS Fargate Service │ │ │ │ │ Target Group │ │ │ (desired count: 2) │ │ │ │ │ (Ubuntu-tg) │───────►│ │ │ │ │ │ │ Health: / │ │ │ ┌────────┐ ┌───────┐ │ │ │ │ └──────────────┘ │ │ │Task 1 │ │Task 2 │ │ │ │ │ │ │ │Ubuntu │ │Ubuntu │ │ │ │ │ ┌──────────────┐ │ │ │:8080 │ │:8080 │ │ │ │ │ │ Amazon ECR │ │ │ └────────┘ └───────┘ │ │ │ │ │ (ubuntu-repo)│ │ │ SG: sg_ecs │ │ │ │ └──────────────┘ │ └──────────────────────┘ │ │ │ └──────────────────────────────┘ │ │ ┌──────────────┐ ┌──────────────┐ ┌───────────────┐ │ │ │ CloudWatch │ │ KMS Key │ │ S3 (State) │ │ │ │ Log Group │ │ (Encryption) │ │ terraform- │ │ │ └──────────────┘ └──────────────┘ │ state-files │ │ │ └───────────────┘ │ └─────────────────────────────────────────────────────────────┘ 

Traffic Flow:

  • User sends an HTTP request to the ALB on port 80.

  • ALB listener forwards the request to the Target Group on port 8080.

  • Target Group routes traffic to one of the two ECS Fargate tasks running in private subnets.

  • The Ubuntu container responds with a dynamic hostname-based message
    Container logs are streamed to CloudWatch Logs, encrypted with KMS.

4. Pre-requisites

Before you can run this project, ensure the following AWS resources are already created in your account:

  • VPC named custom-vpc with public and private subnets tagged public-* and private-*.

  • Security Groups: SG_LB (for the load balancer) and sg_ecs (for ECS tasks).

  • IAM Roles: ecsTaskExecutionRole and ecsTaskRole with appropriate ECS permissions.

  • S3 Bucket: terraform-state-files-8759855 for Terraform remote state storage.

  • AWS CodeBuild Projects: One for deploy (deploybuildspec.yaml) and one for destroy (destroybuildspec.yaml)
    Docker must be enabled in the CodeBuild environment (use a build image that supports Docker)

5. Implementation Steps in Words

Here is the high-level journey from code commit to a live application:

Step 1 — Dockerize the Application
A simple Ubuntu-based Apache web server is containerized. The Dockerfile installs Apache, reconfigures it to listen on port 8080 (instead of the default 80), and serves a dynamic HTML page showing the container's hostname.

Step 2 — Define Infrastructure as Code
All AWS infrastructure is defined using Terraform across modular .tf files. Variables are cleanly separated from resource definitions, and all sensitive configuration lives in terraform.tfvars.

Step 3 — Provision ECR and Push Docker Image
The deploy pipeline first creates the ECR repository using a targeted Terraform apply, then builds the Docker image locally, authenticates to ECR, and pushes the image with the latest tag.

Step 4 — Provision Full AWS Infrastructure
With the image available in ECR, Terraform provisions the full stack: CloudWatch log group, KMS key, ECS cluster, task definition referencing the pushed image, ECS Fargate service, ALB, target group, and listener.

Step 5 — Application Goes Live
ECS pulls the container image from ECR and starts 2 task replicas in private subnets. The ALB distributes traffic across them. The application is accessible via the ALB DNS name.

Step 6 — Teardown on Demand
The destroy pipeline runs terraform destroy to cleanly remove all provisioned resources, ensuring no lingering costs.

6. Technical Implementation Steps

6.1 Dockerfile

FROM public.ecr.aws/docker/library/ubuntu:24.04 RUN apt-get update && apt-get install -y apache2 && apt-get clean && rm -rf /var/lib/apt/lists/* RUN sed -i 's/80/8080/g' /etc/apache2/ports.conf RUN sed -i 's/<VirtualHost \*:80>/<VirtualHost *:8080>/' /etc/apache2/sites-available/000-default.conf RUN echo "ServerName localhost" >> /etc/apache2/apache2.conf CMD ["/bin/bash","-c","echo \"This is web server $(hostname)\" > /var/www/html/index.html && exec apache2ctl -D FOREGROUND"] EXPOSE 8080 

The Dockerfile starts from the official Ubuntu 24.04 image pulled from the public ECR gallery. It installs Apache2, then uses sed to reconfigure Apache's listening port from the default 80 to 8080 — both in ports.conf and the default virtual host config. At container startup, it dynamically writes the container's hostname into index.html, making it easy to verify load balancing by seeing different hostnames on page refresh. Apache runs in the foreground as the main container process.

6.2 Terraform/provider.tf — Backend & Provider Configuration

terraform { backend "s3" { bucket = "terraform-state-files-8759855" key = "ecs.tfstate" region = "us-east-1" } required_providers { aws = { source = "hashicorp/aws" version = "6.51.0" } } } provider "aws" { region = var.aws_region } 

This file does two critical things. First, it configures an S3 remote backend to store the Terraform state file (ecs.tfstate), which is essential for team collaboration and pipeline-based deployments — the state is never stored locally. Second, it pins the AWS provider to version 6.51.0, preventing unexpected breaking changes from provider upgrades. The region is kept dynamic via a variable.

6.3 Terraform/data.tf — Reading Existing AWS Resources

data "aws_vpc" "custom-vpc" { filter { name = "tag:Name" values = ["custom-vpc"] } } data "aws_subnets" "public" { filter { name = "tag:Name" values = ["public-*"] } } data "aws_subnets" "private" { filter { name = "tag:Name" values = ["private-*"] } } data "aws_security_group" "sg_lb" { name = "SG_LB" } data "aws_security_group" "sg_ecs" { name = "sg_ecs" } data "aws_iam_role" "task_exec" { name = "ecsTaskExecutionRole" } data "aws_iam_role" "task_role" { name = "ecsTaskRole" } 

Rather than recreating foundational resources like VPC, subnets, security groups, and IAM roles, this file uses Terraform data sources to reference resources that already exist in the AWS account. This follows the principle of separation of concerns — the networking layer is managed independently, and this project simply reads its outputs. Subnets are looked up by tag name pattern (public-, private-), making the code flexible across multi-AZ setups.

6.4 Terraform/ecr.tf — Amazon ECR Repository

resource "aws_ecr_repository" "ecr" { name = var.ecr_repo_name image_tag_mutability = "MUTABLE" image_scanning_configuration { scan_on_push = true } } 

This creates the Amazon Elastic Container Registry repository where the Docker image is stored. image_tag_mutability = "MUTABLE" allows the latest tag to be overwritten on each pipeline run, enabling a simple continuous deployment pattern. scan_on_push = true enables automatic vulnerability scanning every time an image is pushed, providing a built-in security gate without any additional tooling.

6.5 Terraform/ecs.tf — ECS Cluster, Task Definition & Service

# CloudWatch Log Group resource "aws_cloudwatch_log_group" "cw_log" { name = var.cloudwatch_log_group } # KMS Key for encryption resource "aws_kms_key" "kms" { description = "kms key required for encryption" deletion_window_in_days = 7 } # ECS Cluster with encrypted exec logging resource "aws_ecs_cluster" "ecs" { name = var.ecs_name configuration { execute_command_configuration { kms_key_id = aws_kms_key.kms.arn logging = "OVERRIDE" log_configuration { cloud_watch_encryption_enabled = true cloud_watch_log_group_name = aws_cloudwatch_log_group.cw_log.name } } } } # Task Definition resource "aws_ecs_task_definition" "task_def" { family = var.ecs_task_definition.family requires_compatibilities = var.ecs_task_definition.requires_compatibilities network_mode = var.ecs_task_definition.network_mode cpu = var.ecs_task_definition.cpu memory = var.ecs_task_definition.memory task_role_arn = data.aws_iam_role.task_role.arn execution_role_arn = data.aws_iam_role.task_exec.arn container_definitions = jsonencode([...]) } # ECS Fargate Service resource "aws_ecs_service" "ecs_service" { name = "susseta" cluster = aws_ecs_cluster.ecs.id task_definition = aws_ecs_task_definition.task_def.arn desired_count = 2 launch_type = "FARGATE" load_balancer { ... } network_configuration { assign_public_ip = false security_groups = [data.aws_security_group.sg_ecs.id] subnets = data.aws_subnets.private.ids } } 

This is the core of the infrastructure. It creates four interconnected resources:

CloudWatch Log Group — captures all stdout/stderr from running containers
KMS Key — encrypts ECS Exec session logs and CloudWatch logs for security compliance
ECS Cluster — the logical boundary for your containerized workloads, configured with encrypted exec command logging
Task Definition — the blueprint for the container: 1 vCPU, 2 GB RAM at the task level (800 CPU units and 1500 MB reserved for the container), pointing to the ECR image URL, with awslogs log driver configured
ECS Service — maintains 2 running replicas of the task using the Fargate launch type, placed in private subnets with no public IP, wired to the ALB target group.

6.6 Terraform/alb.tf — Application Load Balancer

resource "aws_lb_target_group" "tg" { name = var.target_group.name port = var.target_group.port protocol = var.target_group.protocol target_type = var.target_group.target_type vpc_id = data.aws_vpc.custom-vpc.id health_check { enabled = var.target_group.health_check_enable healthy_threshold = var.target_group.healthy_threshold interval = var.target_group.interval path = var.target_group.path } } resource "aws_lb" "alb" { name = var.lb.name load_balancer_type = var.lb.load_balancer_type internal = var.lb.internal ip_address_type = var.lb.ip_address_type security_groups = [data.aws_security_group.sg_lb.id] subnets = data.aws_subnets.public.ids } resource "aws_lb_listener" "listener" { count = length(data.aws_subnets.public.ids) load_balancer_arn = aws_lb.alb.arn port = var.lb_listener.port protocol = var.lb_listener.protocol default_action { type = var.lb_listener.type target_group_arn = aws_lb_target_group.tg.arn } } 

Three resources work together to expose the application to the internet. The Target Group (Ubuntu-tg) uses ip as the target type — required for Fargate — and performs health checks against the root path / every 30 seconds, requiring 5 consecutive successes to mark a target healthy. The ALB (frontend-lb) is internet-facing, deployed across public subnets, and protected by the SG_LB security group. The Listener watches on port 80 and forwards all HTTP traffic to the target group, with one listener created per public subnet.

6.7 Terraform/var.tf & terraform.tfvars — Variables

# var.tf — type definitions and descriptions variable "ecs_task_definition" { type = object({ family = string network_mode = string requires_compatibilities = list(string) cpu = number memory = number cpu_allocations = number memory_allocations = number container_name = string container_port = number log_driver = string }) } 
# terraform.tfvars — actual values ecr_repo_name = "ubuntu-repo" cloudwatch_log_group = "aws-cloudwatch-group-ubuntu" ecs_name = "Ubuntu-cluster" ecs_task_definition = { family = "Ubuntu-td" network_mode = "awsvpc" log_driver = "awslogs" requires_compatibilities = ["FARGATE"] cpu = 1024 memory = 2048 cpu_allocations = 800 memory_allocations = 1500 container_name = "Ubuntu" container_port = 8080 } aws_region = "us-east-1" 

The variable strategy cleanly separates type safety (var.tf) from runtime values (terraform.tfvars). Using object() types for complex variables like ecs_task_definition, target_group, lb, and lb_listener groups related settings together, avoids variable sprawl, and lets Terraform validate the entire object shape at plan time. To deploy to a different environment, only the .tfvars file needs to change — the resource definitions remain untouched.

6.8 Terraform/output.tf — Outputs

output "public_subnet_ids" { value = data.aws_subnets.public.ids } output "private_subnet_ids" { value = data.aws_subnets.private.ids } 

Outputs make key infrastructure values accessible after terraform apply, useful for debugging, downstream automation, or cross-stack references. Here, the resolved public and private subnet IDs are exported — helpful for verifying that the correct subnets were selected by the tag-based data source filters.

7. Pipeline Configuration

The CI/CD automation is powered by two AWS CodeBuild buildspec files that handle the complete infrastructure lifecycle.

7.1 Deploy Pipeline — deploybuildspec.yaml

version: 0.2 env: variables: TF_VERSION: "1.8.5" TERRAFORM_DIR: "Terraform" URL: "009846316881.dkr.ecr.us-east-1.amazonaws.com/" REPO: "ubuntu-repo" TAG: "latest" phases: install: commands: - curl -fsSLo terraform.zip "https://releases.hashicorp.com/terraform/${TF_VERSION}/..." - unzip -q terraform.zip -d /usr/local/bin/ pre_build: commands: - terraform init && terraform validate - terraform plan -target=aws_ecr_repository.ecr -out=tfplanecr - terraform apply -target=aws_ecr_repository.ecr tfplanecr - docker buildx build -t $URL$REPO:$TAG . - aws ecr get-login-password | docker login --username AWS --password-stdin $URL - docker push $URL$REPO:$TAG build: commands: - terraform plan -input=false -out=tfplan - terraform apply -input=false tfplan 

The deploy pipeline is split into three phases:

Install Phase: Downloads and installs the pinned Terraform version (1.8.5) directly from HashiCorp releases into /usr/local/bin, ensuring a consistent toolchain regardless of the CodeBuild base image.

Pre-Build Phase: This is the most critical phase. It first creates only the ECR repository using a targeted apply (-target=aws_ecr_repository.ecr). This is necessary because the ECS task definition references the ECR image URL — the repository must exist before the full plan can succeed. Then it builds the Docker image using buildx, authenticates to ECR using the AWS CLI's temporary credential mechanism (get-login-password), and pushes the image. A 60-second sleep is included to allow ECR to fully register the pushed image.

Build Phase: With the image safely in ECR, a full Terraform plan and apply provisions the remaining infrastructure — ECS cluster, task definition, service, ALB, target group, and listener.

7.2 Destroy Pipeline — destroybuildspec.yaml

version: 0.2 env: variables: TF_VERSION: "1.8.5" TERRAFORM_DIR: "Terraform" phases: install: commands: - curl -fsSLo terraform.zip "https://releases.hashicorp.com/terraform/${TF_VERSION}/..." - unzip -q terraform.zip -d /usr/local/bin/ pre_build: commands: - terraform init -input=false build: commands: - terraform plan -destroy -input=false -out=destroy.tfplan - terraform apply -input=false destroy.tfplan 

The destroy pipeline is intentionally lean. It installs the same Terraform version, initializes the backend to load the existing state, generates a destroy plan (-destroy flag), and applies it. Using a plan file (destroy.tfplan) before the apply adds an extra layer of safety — you can inspect what will be destroyed before it happens. This pipeline is typically triggered manually to tear down the environment and stop incurring costs.

7.3 Pipeline Flow Diagram

 ┌─────────────────────────────────────────────────────────────────┐ │ DEPLOY PIPELINE │ │ │ │ ┌──────────┐ ┌───────────────────┐ ┌────────────────────┐ │ │ │ INSTALL │──►│ PRE_BUILD │──►│ BUILD │ │ │ │ │ │ │ │ │ │ │ │ Download │ │ terraform init │ │ terraform plan │ │ │ │ Terraform│ │ terraform validate│ │ terraform apply │ │ │ │ v1.8.5 │ │ Apply ECR only │ │ (full infra) │ │ │ └──────────┘ │ docker build │ └────────────────────┘ │ │ │ docker push │ │ │ └───────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ DESTROY PIPELINE │ │ │ │ ┌──────────┐ ┌───────────────────┐ ┌────────────────────┐ │ │ │ INSTALL │──►│ PRE_BUILD │──►│ BUILD │ │ │ │ │ │ │ │ │ │ │ │ Download │ │ terraform init │ │ terraform plan │ │ │ │ Terraform│ │ (loads S3 state) │ │ -destroy │ │ │ │ v1.8.5 │ └───────────────────┘ │ terraform apply │ │ │ └──────────┘ │ (destroys all) │ │ │ └────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ 

8. Key Benefits

No Server Management ECS Fargate is a serverless compute engine for containers. There are no EC2 instances to patch, resize, or monitor. AWS manages the underlying infrastructure entirely.

Immutable Infrastructure Every deployment produces a fresh infrastructure state from code. There is no configuration drift because resources are never modified in place — they are planned, applied, and optionally destroyed.

Security by Default

  • Containers run in private subnets with no public IPs.

  • Only the ALB is exposed to the internet.

  • Container logs are encrypted with a customer-managed KMS key.

  • ECR scans every pushed image for vulnerabilities automatically.

  • IAM roles follow least privilege — the task execution role and task role are separate.

Cost Efficiency Fargate charges only for the vCPU and memory reserved per running task. The destroy pipeline ensures you can completely eliminate costs when the environment is not needed, such as in a dev or demo setup.

Repeatable and Portable The entire stack is defined in code. Deploying to a new AWS region or account requires changing a handful of values in terraform.tfvars and re-running the pipeline

Observability Built In Every container's stdout and stderr are automatically captured by CloudWatch Logs under the aws-cloudwatch-group-ubuntu log group, with stream prefix app. No additional logging agents are needed inside the container.

9. Conclusion

This project demonstrates a production-aligned pattern for containerized application deployment on AWS. By combining Docker for application packaging, Terraform for infrastructure provisioning, and AWS CodeBuild for CI/CD automation, the entire lifecycle — from code to running container to teardown — is managed as code with no manual steps.
The architecture enforces security best practices by keeping workloads in private subnets, using encrypted logging, and leveraging IAM roles for all AWS API access. The modular Terraform structure makes it straightforward to extend — adding auto-scaling policies, HTTPS listeners, or additional services requires minimal changes to the existing files.
Whether you are building a proof of concept or a foundation for a production microservice, this approach gives you a reliable, auditable, and cost-controlled deployment platform on AWS.

Repository Structure

aws-app-deployment-ecs/ ├── Dockerfile # Container image definition ├── deploybuildspec.yaml # CodeBuild spec for deploy pipeline ├── destroybuildspec.yaml # CodeBuild spec for destroy pipeline └── Terraform/ ├── provider.tf # AWS provider & S3 backend config ├── data.tf # Data sources for existing AWS resources ├── ecr.tf # ECR repository resource ├── ecs.tf # ECS cluster, task definition & service ├── alb.tf # ALB, target group & listener ├── var.tf # Variable type definitions ├── terraform.tfvars # Variable values └── output.tf # Stack outputs 

Built with ❤️ using AWS ECS Fargate, Terraform, and AWS CodeBuild