πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

This project demonstrates real-world cloud architecture patterns and DevOps best practices, making it an ideal hands-on learning experience for engineers looking to master AWS infrastructure-as-code, containerization, and automated deployment workflows.

Perfect for building portfolio projects or preparing for cloud certifications while gaining practical experience with enterprise-grade multi-tier application deployment.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ‘£
60 Days of DevOps (Complete)
30 Days of MLOps (Complete)
90 Days of Cloud (in progress)

πŸ“š Key Practice Points

  • Shell Scripting: Shell Scripting & AWS CLI to Automate AWS Cloud
  • VPC: Custom VPC with public and private subnets across 2 availability zones
  • EC2: Frontend and backend instances, one per Availability Zone (Auto Scaling is one of the challenges)
  • ECR: Elastic Container Registry for Docker images
  • Application Load Balancer: Distributes traffic to frontend instances
  • RDS MySQL: Managed database service
  • Security Groups: Network-level security
  • IAM Roles: Secure access management
  • NAT Gateway: Outbound internet access for private subnets

🧠 Learn here

This Project will help you understand how the presentation, application, and data tiers interact within a production-grade AWS environment using modern cloud-native services.

Architecture Overview

Network layout of the three-tier portfolio app: ALB, frontend and backend EC2 instances, NAT gateways and RDS across two AZs

Tiers

  1. Presentation Tier (Frontend): Flask-based personal portfolio hosted on EC2 instances behind an Application Load Balancer
  2. Application Tier (Backend): Flask API backend on EC2 instances in private subnets
  3. Data Tier (Database): RDS MySQL database in private subnets

Network Architecture

VPC Design

CIDR Block: 10.0.0.0/16

Subnet Layout

Subnet Type AZ CIDR Purpose
Public-1 us-east-1a 10.0.1.0/24 ALB, NAT GW, Frontend EC2
Public-2 us-east-1b 10.0.2.0/24 ALB, NAT GW, Frontend EC2
Private-1 us-east-1a 10.0.11.0/24 Backend EC2
Private-2 us-east-1b 10.0.12.0/24 Backend EC2
Database-1 us-east-1a 10.0.21.0/24 RDS instance
Database-2 us-east-1b 10.0.22.0/24 RDS standby (only if Multi-AZ is on)

Routing

Public Route Table

  • Destination: 0.0.0.0/0
  • Target: Internet Gateway
  • Associated Subnets: Public-1, Public-2

Private Route Tables (per AZ)

  • Destination: 0.0.0.0/0
  • Target: NAT Gateway (in same AZ)
  • Associated Subnets: Private-1, Private-2

Database Route Tables (per AZ)

  • Destination: 0.0.0.0/0
  • Target: NAT Gateway (in same AZ)
  • Associated Subnets: Database-1, Database-2

The database subnets don't need this NAT route: RDS works without internet access, and leaving the route out keeps the data tier fully private.

Security Architecture

Security Groups

ALB Security Group

Inbound Rules:
- Port 80 (HTTP) from 0.0.0.0/0
- Port 443 (HTTPS) from 0.0.0.0/0

Outbound Rules:
- All traffic to 0.0.0.0/0

Frontend EC2 Security Group

Inbound Rules:
- Port 5000 from ALB Security Group
- Port 22 (SSH) from 0.0.0.0/0 (restrict in production)

Outbound Rules:
- All traffic to 0.0.0.0/0

Backend EC2 Security Group

Inbound Rules:
- Port 5001 from Frontend Security Group
- Port 22 (SSH) from Public Subnets

Outbound Rules:
- All traffic to 0.0.0.0/0

Database Security Group

Inbound Rules:
- Port 3306 (MySQL) from Backend Security Group

Outbound Rules:
- All traffic to 0.0.0.0/0

IAM Architecture

EC2 Instance Role

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "cloudwatch:PutMetricData",
        "ec2:DescribeVolumes",
        "ec2:DescribeTags"
      ],
      "Resource": "*"
    }
  ]
}

Attached Policies:

  • AmazonSSMManagedInstanceCore (for Session Manager)

Application Architecture

Frontend Layer

Technology Stack:

  • Flask 3.0.0
  • Gunicorn (WSGI server)
  • Requests library
  • HTML/CSS/JavaScript

Responsibilities:

  • Serve web UI (personal portfolio)
  • Proxy API requests to backend
  • Handle user interactions
  • Display data from backend

Endpoints:

  • GET / - Main portfolio page
  • GET /health - Health check
  • GET /api/projects - Proxy to backend
  • GET /api/skills - Proxy to backend
  • POST /api/contact - Proxy to backend
  • GET /api/stats - Proxy to backend

Configuration:

  • Port: 5000
  • Workers: 2
  • Timeout: 60 seconds

Backend Layer

Technology Stack:

  • Flask 3.0.0
  • Flask-CORS
  • Gunicorn (WSGI server)
  • MySQL Connector Python

Responsibilities:

  • RESTful API endpoints
  • Database operations (CRUD)
  • Business logic
  • Data validation

Endpoints:

  • GET /health - Health check with DB status
  • GET /api/projects - Fetch projects from DB
  • GET /api/skills - Fetch skills from DB
  • POST /api/contact - Save contact form to DB
  • GET /api/stats - Get portfolio statistics

Configuration:

  • Port: 5001
  • Workers: 2
  • Timeout: 60 seconds

Database Connection:

  • Host: RDS endpoint (from environment)
  • Database: appdb
  • User: admin (from environment)
  • Password: Secure password (from environment)

Database Layer

Technology: Amazon RDS for MySQL 8.4

Use MySQL 8.4. RDS for MySQL 8.0 left standard support on July 31, 2026, and new 8.0 instances are enrolled in paid RDS Extended Support. If the repo's rds.tf still says engine_version = "8.0", change it to "8.4" before you deploy.

Configuration:

  • Instance Class: db.t3.micro
  • Storage: 20 GB (gp3)
  • Encrypted: Yes
  • Multi-AZ: No (enable for production)
  • Backup Retention: 7 days

Schema:

-- Projects Table
CREATE TABLE projects (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    technologies VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Skills Table
CREATE TABLE skills (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    category VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Contacts Table
CREATE TABLE contacts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Load Balancing

Application Load Balancer

Configuration:

  • Type: Application Load Balancer
  • Scheme: Internet-facing
  • IP Address Type: IPv4
  • Subnets: Public-1, Public-2

Target Group:

  • Protocol: HTTP
  • Port: 5000
  • Health Check Path: /health
  • Health Check Interval: 30 seconds
  • Healthy Threshold: 2
  • Unhealthy Threshold: 2
  • Timeout: 5 seconds

Listener:

  • Protocol: HTTP
  • Port: 80
  • Default Action: Forward to Frontend Target Group

Prerequisites

  • Docker Installed locally for Local Development
  • AWS Account with appropriate permissions
  • AWS CLI configured with credentials
  • Terraform >= 1.0

Project Structure

portfolio-app-ec2/
β”œβ”€β”€ terraform/
β”‚   β”œβ”€β”€ main.tf              # Main Terraform configuration
β”‚   β”œβ”€β”€ variables.tf         # Input variables
β”‚   β”œβ”€β”€ outputs.tf           # Output values
β”‚   β”œβ”€β”€ vpc.tf              # VPC and networking
β”‚   β”œβ”€β”€ security_groups.tf  # Security group rules
β”‚   β”œβ”€β”€ ec2.tf              # EC2 instances and IAM roles
β”‚   β”œβ”€β”€ ecr.tf              # ECR repositories
β”‚   β”œβ”€β”€ alb.tf              # Application Load Balancer
β”‚   β”œβ”€β”€ rds.tf              # RDS MySQL database
β”‚   └── terraform.tfvars.example  # Example variables file
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ docker-compose.yml  # Local development
β”‚   β”œβ”€β”€ frontend/           # Frontend Flask application
β”‚   β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”‚   β”œβ”€β”€ app.py
β”‚   β”‚   └── templates/
β”‚   └── backend/            # Backend Flask API
β”‚       β”œβ”€β”€ Dockerfile
β”‚       β”œβ”€β”€ app.py
β”‚       └── requirements.txt
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ build-and-push.sh   # Build and push to ECR
β”‚   β”œβ”€β”€ deploy.sh           # Automated deployment
β”‚   β”œβ”€β”€ user_data_frontend_v2.sh  # ECR-based Deployment 
β”‚   β”œβ”€β”€ user_data_backend_v2.sh   # ECR-based Deployment

This Project uses Docker & Docker Compose for Local Development:

Project Source Codes

Local Development Setup

The app/ directory includes Docker Compose configuration for local development and testing before AWS deployment.

Quick Start


git clone https://github.com/sd031/portfolio-app-ec2.git
cd portfolio-app-ec2/app

# Start all services
docker compose up -d

# Access the application
open http://localhost:5000

What Gets Started

Service Port URL
Frontend 5000 http://localhost:5000
Backend API 5001 http://localhost:5001
MySQL Database 3306 localhost:3306

Common Commands

Start Services

# Start in background
docker compose up -d

# Start with logs
docker compose up

# Start specific service
docker compose up -d backend

Stop Services

# Stop all services
docker compose down

# Stop and remove volumes (clean slate)
docker compose down -v

View Logs

# All services
docker compose logs -f

# Specific service
docker compose logs -f frontend
docker compose logs -f backend
docker compose logs -f database

# Last 50 lines
docker compose logs --tail=50

Rebuild After Changes

# Rebuild all services
docker compose build

# Rebuild specific service
docker compose build backend

# Rebuild and restart
docker compose up -d --build

Deploying to AWS

Step 1: Build and push Docker images to ECR:

./scripts/build-and-push.sh Image_tag

e.g.

./scripts/build-and-push.sh 1.0.0

This will create the ECR repo if it doesn't exist and build an image and push to ECR for both frontend and backend

aws ecr create-repository \
            --repository-name $repo_name \
            --region $AWS_REGION \
            --image-scanning-configuration scanOnPush=true \
            --encryption-configuration encryptionType=AES256 \
            --tags Key=Project,Value=$PROJECT_NAME Key=ManagedBy,Value=Script &>/dev/null

Step 2: Deploy the Infrastructure and Application

./scripts/deploy.sh 

This script automates the cloud resource and application deployment via Terraform

#!/bin/bash

# Portfolio Web App Application Deployment Script
# This script automates the deployment process

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Print colored output
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if required tools are installed
check_prerequisites() {
    print_info "Checking prerequisites..."
    
    if ! command -v aws &> /dev/null; then
        print_error "AWS CLI is not installed. Please install it first."
        exit 1
    fi
    
    if ! command -v terraform &> /dev/null; then
        print_error "Terraform is not installed. Please install it first."
        exit 1
    fi
    
    print_info "All prerequisites met!"
}

# Check AWS credentials
check_aws_credentials() {
    print_info "Checking AWS credentials..."
    
    if ! aws sts get-caller-identity &> /dev/null; then
        print_error "AWS credentials are not configured. Run 'aws configure' first."
        exit 1
    fi
    
    ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
    REGION=$(aws configure get region)
    
    print_info "AWS Account ID: $ACCOUNT_ID"
    print_info "AWS Region: $REGION"
}

# Create SSH key pair if it doesn't exist
create_key_pair() {
    KEY_NAME="3tier-app-key"
    KEY_FILE="$KEY_NAME.pem"
    
    if [ -f "$KEY_FILE" ]; then
        print_warning "Key pair $KEY_FILE already exists. Skipping creation."
        return
    fi
    
    print_info "Creating SSH key pair..."
    
    aws ec2 create-key-pair \
        --key-name $KEY_NAME \
        --query 'KeyMaterial' \
        --output text > $KEY_FILE
    
    chmod 400 $KEY_FILE
    
    print_info "Key pair created: $KEY_FILE"
}

# Initialize Terraform
init_terraform() {
    print_info "Initializing Terraform..."
    
    cd terraform
    terraform init
    cd ..
    
    print_info "Terraform initialized successfully!"
}

# Validate Terraform configuration
validate_terraform() {
    print_info "Validating Terraform configuration..."
    
    cd terraform
    
    if ! terraform validate; then
        print_error "Terraform configuration is invalid!"
        cd ..
        exit 1
    fi
    
    cd ..
    
    print_info "Terraform configuration is valid!"
}

# Create terraform.tfvars if it doesn't exist
create_tfvars() {
    TFVARS_FILE="terraform/terraform.tfvars"
    
    if [ -f "$TFVARS_FILE" ]; then
        print_warning "terraform.tfvars already exists. Skipping creation."
        return
    fi
    
    print_info "Creating terraform.tfvars from example..."
    
    cp terraform/terraform.tfvars.example $TFVARS_FILE
    
    print_warning "Please edit $TFVARS_FILE and update the db_password!"
    print_warning "Press Enter to continue after updating the file..."
    read
}

# Plan Terraform deployment
plan_terraform() {
    print_info "Planning Terraform deployment..."
    
    cd terraform
    terraform plan -out=tfplan
    cd ..
    
    print_info "Terraform plan created successfully!"
}

# Apply Terraform configuration
apply_terraform() {
    print_info "Applying Terraform configuration..."
    print_warning "This will create resources in your AWS account and may incur costs."
    print_warning "Press Enter to continue or Ctrl+C to cancel..."
    read
    
    cd terraform
    terraform apply tfplan
    cd ..
    
    print_info "Infrastructure deployed successfully!"
}

# Display outputs
display_outputs() {
    print_info "Deployment completed! Here are the outputs:"
    
    cd terraform
    
    echo ""
    echo "=========================================="
    echo "Application URL:"
    terraform output alb_url
    echo "=========================================="
    echo ""
    
    echo "Other outputs:"
    terraform output
    
    cd ..
    
    print_info "Wait 2-3 minutes for the application to fully initialize."
    print_info "Then access your application using the URL above."
}

# Test deployment
test_deployment() {
    print_info "Testing deployment..."
    
    cd terraform
    ALB_URL=$(terraform output -raw alb_url)
    cd ..
    
    print_info "Waiting for application to be ready..."
    sleep 60
    
    print_info "Testing health endpoint..."
    if curl -f "$ALB_URL/health" &> /dev/null; then
        print_info "Health check passed!"
    else
        print_warning "Health check failed. The application may still be initializing."
        print_warning "Please wait a few more minutes and try accessing: $ALB_URL"
    fi
}

# Main deployment flow
main() {
    echo ""
    echo "=========================================="
    echo "3-Tier Web Application Deployment"
    echo "=========================================="
    echo ""
    
    check_prerequisites
    check_aws_credentials
    create_key_pair
    create_tfvars
    init_terraform
    validate_terraform
    plan_terraform
    apply_terraform
    display_outputs
    test_deployment
    
    echo ""
    print_info "Deployment completed successfully!"
    echo ""
}

# Run main function
main

This creates the network (VPC, subnets, NAT gateways), then launches the frontend and backend EC2 instances, the RDS database instance and the load balancer.

As output, you will get the Load Balancer URL. If you visit the site, it will look like this:

To destroy all the cloud resources and stop billing run:

./scripts/destroy.sh

This script destroys cloud resources via the Terraform destroy command.

PS: This is not the most optimized way to run a container; ECS or EKS would be a better choice, but treat this as a practice project for running EC2-based applications


Challenges

  • Move the instances into Auto Scaling groups with scaling policies
  • Put an internal load balancer in front of the backends (today every frontend calls backend 1 only)
  • Implement CloudWatch monitoring and alarms
  • Add SSL/TLS certificate (ACM)
  • Implement CI/CD pipeline
  • Add ElastiCache for session management
  • Implement backup and disaster recovery

🀷🏻 How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das), and use #90DaysOfCloud to engage with the community!


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post