Mastering Amazon EC2
šŸ“–Ebook3 chapters

Mastering Amazon EC2

The Complete Guide to AWS Compute

S

Sarah Chen

November 1, 2025

1h read

Introduction to Amazon EC2

Amazon Elastic Compute Cloud (EC2) is a web service that provides resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers by providing complete control over computing resources. EC2 reduces the time required to obtain and boot new server instances to minutes, allowing you to quickly scale capacity up and down as your computing requirements change.

This elasticity is the defining characteristic that makes cloud computing so powerful. Instead of buying servers that sit idle most of the time, you pay only for the compute capacity you actually use. When demand spikes, you scale up. When it drops, you scale down. This fundamental shift from capital expenditure to operational expenditure has transformed how businesses think about IT infrastructure.

Why EC2 Matters

EC2 is the backbone of AWS compute. Even as serverless and containerized workloads grow, EC2 remains essential for stateful applications, legacy workloads, high-performance computing, and as the foundation for managed services like ECS and EKS. Understanding EC2 deeply is non-negotiable for any cloud practitioner.

Instance Types Explained

AWS offers a vast selection of instance types optimized for different use cases. Instance types comprise varying combinations of CPU, memory, storage, and networking capacity, giving you the flexibility to choose the right mix of resources for your applications. Understanding instance families is key to right-sizing your workloads.

FamilyOptimized ForUse CasesExample Types
General Purpose (T3, M6i)Balanced compute, memory, networkingWeb servers, development environments, small databasest3.medium, m6i.large, m6i.xlarge
Compute Optimized (C6i)High-performance processorsBatch processing, gaming servers, scientific modeling, ML inferencec6i.large, c6i.2xlarge
Memory Optimized (R6i)Fast performance for memory-intensive workloadsIn-memory databases, real-time big data analyticsr6i.large, r6i.4xlarge
Storage Optimized (I3, D2)High sequential read/write to local storageData warehousing, distributed file systems, log processingi3.large, d2.xlarge
Accelerated Computing (P4d, G5)GPU and specialized hardwareMachine learning training, graphics rendering, HPCp4d.24xlarge, g5.xlarge
EC2 Instance Family Overview

Amazon Machine Images (AMIs)

An AMI provides the information required to launch an instance. Think of it as a template that contains the operating system, application server, and applications. You can launch multiple instances from a single AMI when you need multiple instances with the same configuration — this is the foundation of horizontal scaling.

terminal
Bash
# Find the latest Amazon Linux 2023 AMI
aws ec2 describe-images \
  --owners amazon \
  --filters "Name=name,Values=al2023-ami-*-x86_64" \
            "Name=state,Values=available" \
  --query 'Images | sort_by(@, &CreationDate) | [-1].[ImageId, Name]' \
  --output table

# Launch an instance from the AMI
aws ec2 run-instances \
  --image-id ami-0123456789abcdef0 \
  --instance-type t3.micro \
  --key-name my-key-pair \
  --security-group-ids sg-0123456789abcdef0 \
  --subnet-id subnet-0123456789abcdef0 \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=WebServer}]' \
  --user-data file://bootstrap.sh
  • AWS-provided AMIs: Amazon Linux, Ubuntu, Windows Server, Red Hat — maintained by AWS or official vendors
  • AWS Marketplace AMIs: Pre-configured solutions from third parties — may have additional licensing costs
  • Community AMIs: Shared by other AWS users — use with caution, verify the source
  • Custom AMIs: Your own images — create from running instances to capture your configurations
2Chapter

Understanding EC2 Pricing

One of the most important aspects of working with EC2 is understanding the different pricing models. Choosing the right pricing model can reduce your costs by up to 90% compared to on-demand pricing. This isn't about being cheap — it's about being smart with your resources.

On-Demand Instances

On-demand instances let you pay for compute capacity by the second with no long-term commitments. This is the most flexible pricing model and is ideal for applications with unpredictable workloads that cannot be interrupted. You pay for exactly what you use, with no upfront costs.

Reserved Instances & Savings Plans

Reserved Instances and Savings Plans provide significant discounts (up to 72%) compared to on-demand pricing. In exchange, you commit to a consistent amount of usage for a 1 or 3-year term. Savings Plans are the more flexible option — they apply to any instance family, size, OS, or region.

pricing-comparison.txt
Plain Text
Cost Comparison Example: m6i.large running 24/7 for 1 year

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Pricing Model          │ Hourly Rate │ Annual Cost │ Savings │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│ On-Demand              │    $0.096   │    $841     │    0%   │
│ 1-Year No Upfront      │    $0.060   │    $526     │   37%   │
│ 1-Year All Upfront     │    $0.055   │    $480     │   43%   │
│ 3-Year All Upfront     │    $0.035   │    $307     │   63%   │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Spot Instances

Spot Instances let you take advantage of unused EC2 capacity at up to 90% discount compared to on-demand prices. The trade-off: AWS can reclaim these instances with a 2-minute warning when it needs the capacity. This makes spot instances ideal for fault-tolerant, flexible workloads.

Spot Instance Best Practices

Design your applications to handle interruptions gracefully. Use spot-friendly architectures: stateless workers, checkpoint-based processing, containerized workloads, and mixed instance type fleets. Combine spot with on-demand in Auto Scaling Groups for cost-optimized, resilient deployments.

spot-fleet-config.json
JSON
{
  "LaunchTemplateConfigs": [{
    "LaunchTemplateSpecification": {
      "LaunchTemplateId": "lt-0123456789abcdef0",
      "Version": "$Latest"
    },
    "Overrides": [
      { "InstanceType": "c5.large", "WeightedCapacity": 1 },
      { "InstanceType": "c5a.large", "WeightedCapacity": 1 },
      { "InstanceType": "c5n.large", "WeightedCapacity": 1 },
      { "InstanceType": "c6i.large", "WeightedCapacity": 1 }
    ]
  }],
  "SpotOptions": {
    "AllocationStrategy": "price-capacity-optimized",
    "InstanceInterruptionBehavior": "terminate"
  },
  "TargetCapacitySpecification": {
    "TotalTargetCapacity": 10,
    "OnDemandTargetCapacity": 2,
    "SpotTargetCapacity": 8,
    "DefaultTargetCapacityType": "spot"
  }
}

ā€œThe best cost optimization strategy isn't choosing the cheapest option — it's choosing the right pricing model for each workload. A well-optimized AWS bill uses a strategic mix of on-demand, savings plans, and spot instances.ā€

A

AWS Cost Optimization Whitepaper

3Chapter

EC2 Auto Scaling

EC2 Auto Scaling helps you maintain application availability and allows you to automatically add or remove EC2 instances according to conditions you define. This is the mechanism that turns cloud computing's promise of elasticity into reality — scaling your infrastructure automatically in response to demand.

Auto Scaling Groups

An Auto Scaling Group (ASG) contains a collection of EC2 instances that share similar characteristics and are treated as a logical grouping for the purposes of instance scaling and management. You define the minimum, maximum, and desired capacity, and Auto Scaling maintains the desired number of instances.

  1. 1Minimum Capacity: The minimum number of instances to run, even during low demand
  2. 2Desired Capacity: The target number of instances Auto Scaling tries to maintain
  3. 3Maximum Capacity: The upper limit on instances, prevents runaway scaling

Scaling Policies

Scaling policies define how your Auto Scaling Group responds to changing demand. AWS offers several types of scaling policies, each suited to different use cases.

Policy TypeHow It WorksBest For
Target TrackingMaintains a target metric value (e.g., 50% CPU)Most workloads — simple and effective
Step ScalingScales based on alarm thresholds with different stepsFine-grained control over scaling behavior
Simple ScalingAdds/removes fixed number of instancesLegacy — prefer target tracking
Scheduled ScalingScales based on time schedulePredictable traffic patterns
Predictive ScalingUses ML to predict and pre-scaleVariable but predictable patterns
EC2 Auto Scaling Policy Types
scaling-policy.yaml
YAML
# CloudFormation - Target Tracking Scaling Policy
CPUUtilizationPolicy:
  Type: AWS::AutoScaling::ScalingPolicy
  Properties:
    AutoScalingGroupName: !Ref WebServerASG
    PolicyType: TargetTrackingScaling
    TargetTrackingConfiguration:
      PredefinedMetricSpecification:
        PredefinedMetricType: ASGAverageCPUUtilization
      TargetValue: 50.0
      ScaleInCooldown: 300
      ScaleOutCooldown: 60

Health Checks

Auto Scaling performs health checks on instances to ensure only healthy instances are serving traffic. When an instance fails a health check, Auto Scaling terminates it and launches a replacement. You can configure EC2 status checks, ELB health checks, or custom health checks.

Health Check Configuration

For production workloads behind a load balancer, always use ELB health checks in addition to EC2 status checks. ELB health checks verify that your application is actually responding, not just that the instance is running. Configure appropriate health check grace periods to give instances time to bootstrap.

#AWS#EC2#Compute#Auto Scaling#Spot Instances