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.
| Family | Optimized For | Use Cases | Example Types |
|---|---|---|---|
| General Purpose (T3, M6i) | Balanced compute, memory, networking | Web servers, development environments, small databases | t3.medium, m6i.large, m6i.xlarge |
| Compute Optimized (C6i) | High-performance processors | Batch processing, gaming servers, scientific modeling, ML inference | c6i.large, c6i.2xlarge |
| Memory Optimized (R6i) | Fast performance for memory-intensive workloads | In-memory databases, real-time big data analytics | r6i.large, r6i.4xlarge |
| Storage Optimized (I3, D2) | High sequential read/write to local storage | Data warehousing, distributed file systems, log processing | i3.large, d2.xlarge |
| Accelerated Computing (P4d, G5) | GPU and specialized hardware | Machine learning training, graphics rendering, HPC | p4d.24xlarge, g5.xlarge |
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.
# 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
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.
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.
{
"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.ā
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.
- 1Minimum Capacity: The minimum number of instances to run, even during low demand
- 2Desired Capacity: The target number of instances Auto Scaling tries to maintain
- 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 Type | How It Works | Best For |
|---|---|---|
| Target Tracking | Maintains a target metric value (e.g., 50% CPU) | Most workloads ā simple and effective |
| Step Scaling | Scales based on alarm thresholds with different steps | Fine-grained control over scaling behavior |
| Simple Scaling | Adds/removes fixed number of instances | Legacy ā prefer target tracking |
| Scheduled Scaling | Scales based on time schedule | Predictable traffic patterns |
| Predictive Scaling | Uses ML to predict and pre-scale | Variable but predictable patterns |
# 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: 60Health 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.