Module 2

Compute & Database

Launch EC2 instances, configure Auto Scaling Groups, set up RDS PostgreSQL, and load-balance with ALB.

EC2ASGRDSALBLaunch Template

What You'll Build

With your networking in place, it's time to deploy compute and database resources. You'll create an RDS PostgreSQL database, an Application Load Balancer, and an Auto Scaling Group โ€” all through the AWS Console.

Module 2 โ€” Resource Checklist

0/8 (0%)
  • โ˜IAM Role
    sandbox-ec2-role
  • โ˜Key Pair
    sandbox-key
  • โ˜DB Subnet Group
    sandbox-db-subnet-group
  • โ˜RDS Instance
    sandbox-db
  • โ˜Target Group
    sandbox-tg
  • โ˜Application Load Balancer
    sandbox-alb
  • โ˜Launch Template
    sandbox-lt
  • โ˜Auto Scaling Group
    sandbox-asg
AzureAWSNotes
Virtual MachineEC2Nearly identical concept
VMSSAuto Scaling GroupASG + Launch Template โ‰ˆ VMSS
Azure DB for PostgreSQLRDS PostgreSQLVery similar. AWS has DB Subnet Groups
App GatewayALBALB is simpler; App Gateway has built-in WAF
Managed IdentityIAM Instance ProfileAttach IAM Role to EC2 for permissions

Step 1: Create an IAM Role for EC2

EC2 instances need an IAM Role to interact with AWS services (SSM for terminal access, CloudWatch for logs, S3 for deployments). This is like Azure Managed Identity.

๐Ÿงช

Console: IAM โ†’ Roles โ†’ Create role

Step 1 โ€” Trusted entity:

SettingValue
Trusted entity typeAWS service
Use caseEC2

Click Next.

Step 2 โ€” Permissions: Search and select these policies:

Policy NamePurpose
AmazonSSMManagedInstanceCoreSSM Session Manager (SSH alternative)
CloudWatchAgentServerPolicySend logs/metrics to CloudWatch
AmazonS3ReadOnlyAccessPull deployment artifacts from S3

Click Next.

Step 3 โ€” Name:

SettingValue
Role namesandbox-ec2-role

Click Create role.


Step 2: Create a Key Pair

For emergency SSH access. You'll primarily use SSM Session Manager (no SSH needed), but a key pair is a good backup.

๐Ÿงช

Console: EC2 โ†’ Key Pairs โ†’ Create key pair

SettingValue
Namesandbox-key
Key pair typeRSA
Private key file format.pem (Mac/Linux)

Click Create key pair โ€” the .pem file downloads. Save it!

bash
# Make it usable (run in your terminal)
chmod 400 ~/Downloads/sandbox-key.pem

Step 3: RDS PostgreSQL

RDS (Relational Database Service) is a managed database. AWS handles backups, patching, and failover โ€” you just connect and query.

  • DB Subnet Group: Tells RDS which subnets to use (must span 2+ AZs)
  • Multi-AZ: Automatic failover to standby in another AZ (production feature)
  • Instance Class: db.t3.micro is free-tier eligible
โ˜๏ธ Azure Parallel

Azure Database for PostgreSQL uses VNet integration or Private Endpoints. AWS RDS uses Security Groups + DB Subnet Groups โ€” functionally equivalent.

๐Ÿงช

Console: RDS โ†’ Subnet groups โ†’ Create DB subnet group

SettingValue
Namesandbox-db-subnet-group
DescriptionPrivate subnets for AWS Sandbox RDS
VPCsandbox-vpc

Add subnets:

AZSubnet
us-east-1asandbox-private-1a (10.0.10.0/24)
us-east-1bsandbox-private-1b (10.0.11.0/24)

Click Create.

๐Ÿงช

Console: RDS โ†’ Databases โ†’ Create database

SettingValue
Creation methodStandard create
Engine typePostgreSQL
Engine versionPostgreSQL 15 (latest 15.x)
TemplatesFree tier
DB instance identifiersandbox-db
Master usernamedbadmin
Master passwordChoose a strong password (note it!)
DB instance classdb.t3.micro
Storage typegp2
Allocated storage20 GB
Storage autoscalingโŒ Uncheck
VPCsandbox-vpc
DB subnet groupsandbox-db-subnet-group
Public accessNo
Security groupsandbox-rds-sg (remove default!)
Initial database namesandbox
Enhanced MonitoringโŒ Uncheck

Click Create database. Wait 5-10 minutes for Available.

๐Ÿ’ก Tip

Copy the endpoint! Click sandbox-db โ†’ under Connectivity & security โ†’ copy the Endpoint(e.g., sandbox-db.xxxxx.us-east-1.rds.amazonaws.com). You'll need it for the Launch Template.


Step 4: Application Load Balancer

The ALB distributes incoming HTTP/HTTPS traffic across your EC2 instances. It sits in public subnets and forwards to a Target Group.

๐Ÿ”€ ALB

The load balancer itself. Lives in public subnets, has its own DNS name.

๐ŸŽฏ Target Group

A collection of targets (EC2 instances) with health check configuration.

๐Ÿ‘‚ Listener

Listens on a port (80/443) and routes traffic to the target group.

๐Ÿงช

Console: EC2 โ†’ Target Groups โ†’ Create target group

SettingValue
Target typeInstances
Target group namesandbox-tg
Protocol : PortHTTP : 3000
VPCsandbox-vpc
Health check path/health
Healthy threshold2
Unhealthy threshold3
Timeout5 seconds
Interval30 seconds

Click Next. Skip registering targets (ASG will handle this). Click Create target group.

๐Ÿงช

Console: EC2 โ†’ Load Balancers โ†’ Create โ†’ Application Load Balancer

SettingValue
Namesandbox-alb
SchemeInternet-facing
IP address typeIPv4
VPCsandbox-vpc
Mappingsโœ… us-east-1a โ†’ sandbox-public-1a
โœ… us-east-1b โ†’ sandbox-public-1b
Security groupssandbox-alb-sg (remove default!)
Listener: ProtocolHTTP
Listener: Port80
Listener: Default actionForward to โ†’ sandbox-tg

Click Create load balancer. Wait ~2-3 minutes until Active.

๐Ÿ’ก Tip

Copy the DNS name! Select sandbox-alb โ†’ copy the DNS name (e.g., sandbox-alb-123456.us-east-1.elb.amazonaws.com). This is your public URL.


Step 5: EC2 Auto Scaling Group

Instead of launching individual EC2 instances, you'll use a Launch Template (blueprint) + Auto Scaling Group (scales up/down).

โ˜๏ธ Azure Parallel

VMSS comparison: Azure VMSS bundles image and scaling config in one resource. AWS separates them: Launch Template (image config) + ASG (scaling).

๐Ÿงช

Console: EC2 โ†’ Launch Templates โ†’ Create launch template

SettingValue
Launch template namesandbox-lt
Template version descriptionInitial v1
AMIAmazon Linux 2023
Instance typet3.micro
Key pairsandbox-key
Security groupssandbox-ec2-sg
IAM instance profile (Advanced)sandbox-ec2-role

User data (in Advanced details, paste this script):

bash
#!/bin/bash
set -e

# Install Node.js 18
curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs git

# Install CodeDeploy agent (for later CI/CD module)
yum install -y ruby wget
cd /home/ec2-user
wget https://aws-codedeploy-us-east-1.s3.amazonaws.com/latest/install
chmod +x ./install
./install auto

# Create the application directory
mkdir -p /home/ec2-user/sandbox-app/app
cd /home/ec2-user/sandbox-app/app

# Initialize app and install dependencies
npm init -y
npm install express pg dotenv

# Create the Express server inline
cat > server.js << 'EOF'
const express = require('express');
const { Pool } = require('pg');
const os = require('os');
require('dotenv').config();

const app = express();
app.use(express.json());

// Set up Postgres connection pool
const pool = new Pool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
});

// The crucial /health endpoint for the ALB
app.get('/health', (req, res) => {
  res.status(200).send('OK');
});

// Provide instance hostname to prove ALB routing
app.get('/api/info', (req, res) => {
  res.json({ hostname: os.hostname(), message: 'Hello from EC2 Auto Scaling!' });
});

// Dummy task API
app.get('/api/tasks', (req, res) => {
  res.json([{ id: 1, title: 'Sample task', description: 'DB not connected in demo' }]);
});

app.post('/api/tasks', (req, res) => {
  res.status(201).json({ status: 'created' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
EOF

# Create environment file
cat > .env << 'ENVEOF'
PORT=3000
NODE_ENV=production
DB_HOST=REPLACE_WITH_YOUR_RDS_ENDPOINT
DB_PORT=5432
DB_NAME=sandbox
DB_USER=dbadmin
DB_PASSWORD=REPLACE_WITH_YOUR_RDS_PASSWORD
ENVEOF

# Start the app with PM2
npm install -g pm2
pm2 start server.js --name sandbox
pm2 startup
pm2 save
โš ๏ธ Warning

Before creating: Replace DB_HOST with your RDS endpoint from Step 3, and DB_PASSWORD with your RDS password!

Click Create launch template.

๐Ÿงช

Console: EC2 โ†’ Auto Scaling Groups โ†’ Create

Step 1 โ€” Launch template:

SettingValue
ASG namesandbox-asg
Launch templatesandbox-lt

Step 2 โ€” Network:

SettingValue
VPCsandbox-vpc
Subnetssandbox-private-1a, sandbox-private-1b

Step 3 โ€” Load balancing:

SettingValue
Load balancingAttach to existing load balancer
Target groupsandbox-tg
Health check typeโœ… ELB
Health check grace period300 seconds

Step 4 โ€” Group size:

SettingValue
Desired capacity2
Minimum capacity1
Maximum capacity4
Scaling policyTarget tracking
MetricAverage CPU utilization
Target value70

Click through Next โ†’ Create Auto Scaling group.

Wait 3-5 minutes. Then check:

  1. EC2 โ†’ Instances โ€” 2 new instances should appear
  2. EC2 โ†’ Target Groups โ†’ sandbox-tg โ†’ Targets โ€” both should become healthy

๐Ÿงช Test the Full Deployment

Once your target group shows healthy targets, open your ALB DNS in a browser or use curl:

bash
# Replace with YOUR ALB DNS name
ALB_DNS="sandbox-alb-123456.us-east-1.elb.amazonaws.com"

# Health check
curl http://$ALB_DNS/health

# List tasks
curl http://$ALB_DNS/api/tasks

# Create a task
curl -X POST http://$ALB_DNS/api/tasks \
  -H "Content-Type: application/json" \
  -d '{"title": "Learn AWS VPC", "description": "Understand CIDR blocks"}'

# Hit /api/info multiple times โ€” notice the hostname changes!
# That's the ALB distributing traffic across ASG instances.
curl http://$ALB_DNS/api/info
curl http://$ALB_DNS/api/info
๐Ÿ’ก Tip

Load balancing proof: Call /api/info repeatedly. Each response shows a different hostname โ€” proving the ALB is routing across your ASG instances.


Key Takeaways

  • RDS handles database management โ€” you focus on queries, AWS handles backups/patching
  • ALB + Target Group is the standard pattern for HTTP load balancing
  • Launch Template + ASG = reproducible, auto-healing, auto-scaling compute
  • User Data scripts run only on first boot โ€” update the Launch Template to change config
  • The /health endpoint is critical โ€” it's how the ALB knows which instances are alive
  • Always use IAM Roles for EC2 (never embed access keys in code)