Skip to content

Lesson 3 of 30Core services

EC2

Launch and secure virtual servers, pick instance types and pricing models, and scale them with Auto Scaling groups.

15 min read0/4 questions

EC2 (Elastic Compute Cloud) is AWS's virtual server service, and it sits under far more of AWS than you can see: containers on ECS, managed databases and build runners all run on EC2-style machines. Even if you end up on Lambda or Fargate, knowing what an instance, a security group and an Auto Scaling group are makes every other service easier to reason about.

An instance is a virtual machine

An instance is a virtual machine running on AWS hardware. You choose three things when you launch one:

  • An AMI (Amazon Machine Image): the disk image to boot from. Amazon Linux 2023, Ubuntu 24.04, or your own image with your app baked in.
  • An instance type: how much CPU, memory and network it gets.
  • Where it lives: a subnet in one Availability Zone (subnets are lesson 5).

Its disk is usually an EBS volume (Elastic Block Store): a network-attached drive that lives on independently of the instance. Stop the instance and the EBS volume keeps your data. Some types also have instance store disks, which are physically attached and fast but wiped when the instance stops.

One EC2 instance and what it is made of
AZ us-east-1aYou: SSM sessionYouSSM sessionSecurity group: allow 443Security groupallow 443EC2 instance: t4g.smallEC2 instancet4g.smallAMI: Amazon LinuxAMIAmazon LinuxEBS volume: gp3, 20 GBEBS volumegp3, 20 GBInstance profile: IAM roleInstance profileIAM roleSnapshot: in S3Snapshotin S3boots fromroot diskcredsbackup

The instance boots from an AMI, a template disk image.

1/4

Instance types and families

Instance type names are a code: m7g.large means family m (general purpose), generation 7, attribute g (AWS Graviton, an ARM CPU), size large.

FamilyOptimized forTypical use
t (t3, t4g)Burstable: cheap baseline CPU with credits to burstSmall web apps, dev boxes
m (m7i, m7g)Balanced CPU and memoryMost app servers
c (c7g, c7i)ComputeVideo encoding, CPU-heavy APIs
r (r7g)MemoryCaches, in-memory analytics
g, pGPUsML training and inference

Each size step roughly doubles CPU, memory and price: large is 2 vCPUs, xlarge 4, 2xlarge 8. Graviton (g) instances are usually around 20% cheaper for the same work if your code runs on ARM (Python, Node and Java usually do with no changes).

Quick check
You are running a Redis-like in-memory cache that needs lots of RAM and modest CPU. Which family fits?
Need a nudge? A hint rules out a wrong answer.

Security groups: a stateful firewall

A security group is a firewall attached to an instance's network interface. It only has allow rules (no deny), and everything not allowed is blocked.

The important word is stateful: if a request is allowed in, the response is automatically allowed back out, and vice versa. You only write rules for who may start a connection.

allow HTTPS from anywhere, Postgres only from the app's security group
aws ec2 authorize-security-group-ingress --group-id sg-0web \  --protocol tcp --port 443 --cidr 0.0.0.0/0aws ec2 authorize-security-group-ingress --group-id sg-0db \  --protocol tcp --port 5432 --source-group sg-0web

That second rule is the pattern to remember: a security group can reference another security group as the source. "Allow 5432 from anything in sg-0web" keeps working as instances come and go, with no IP addresses to maintain.

Quick check
Your security group allows inbound TCP 443 from 0.0.0.0/0 and has no outbound rules at all. A browser connects on 443. Does the response get back?
Need a nudge? A hint rules out a wrong answer.

Getting onto the box: key pairs vs Session Manager

The classic way in is SSH with a key pair: AWS keeps the public key, you keep the .pem private key, and you open port 22 in the security group.

The better way today is SSM Session Manager. The instance runs the SSM agent (preinstalled on Amazon Linux), its role includes the AmazonSSMManagedInstanceCore policy, and you get a shell through AWS's API. No port 22, no keys to lose, and every session is logged.

aws ssm start-session --target i-0abc123def4567890

User data: run a script at first boot

User data is a script EC2 runs once when the instance first boots. It is how you install packages and start your app without logging in.

user-data.sh
#!/bin/bashdnf install -y dockersystemctl enable --now dockerdocker run -d -p 80:8000 --restart always \  123456789012.dkr.ecr.us-east-1.amazonaws.com/api:1.4.2

For anything bigger, bake an AMI with your app already installed (with a tool like EC2 Image Builder or Packer) so new instances start in seconds instead of installing for minutes.

Pricing models

You pay for an instance per second while it runs (60-second minimum on Linux). How you commit changes the price:

ModelDiscount vs on-demandCatch
On-DemandnoneMost expensive, no commitment
Savings Plansup to about 70%Commit to $X per hour of compute for 1 or 3 years
Reserved Instancesup to about 70%Older model, tied to an instance family
Spotup to about 90%AWS can reclaim it with a 2-minute warning

Spot is unused AWS capacity. It is perfect for work that can be interrupted and retried (batch jobs, CI runners, rendering), and wrong for your only database.

Pythoncost.py
# Example prices only. Real prices vary by Region and change over time.ON_DEMAND_HOURLY = 0.0832 # e.g. an m7g.large on-demandSAVINGS_PLAN_DISCOUNT = 0.35SPOT_DISCOUNT = 0.70HOURS = 730 # about one month def monthly(hourly, discount=0.0, count=1): return round(hourly * (1 - discount) * HOURS * count, 2) print("on-demand x3: $", monthly(ON_DEMAND_HOURLY, count=3))print("savings plan x3: $", monthly(ON_DEMAND_HOURLY, SAVINGS_PLAN_DISCOUNT, 3))print("2 SP + 4 spot: $", round(monthly(ON_DEMAND_HOURLY, SAVINGS_PLAN_DISCOUNT, 2) + monthly(ON_DEMAND_HOURLY, SPOT_DISCOUNT, 4), 2))
Output
Press Run (⌘ Enter) to see what happens.

A common real setup is the last line: a baseline of steady instances on a Savings Plan, plus Spot instances for extra capacity.

Match the pairs0/4 matched

Match the workload to the pricing model.

Choose an item, then its match on the other side.

Auto Scaling groups

An Auto Scaling group (ASG) keeps a fleet of identical instances healthy and sized right. You give it a launch template (AMI, type, security groups, user data), a min, max and desired count, and the subnets (spread across AZs) to use.

It does two jobs:

  • Self-healing. If an instance fails a health check, the ASG terminates it and launches a replacement.
  • Scaling. A target tracking policy keeps a metric near a target, like "average CPU at 60%". More load, more instances; less load, fewer.
Pythontarget_tracking.py
import math def desired(current, cpu, target=60, min_size=2, max_size=10): want = math.ceil(current * cpu / target) return max(min_size, min(max_size, want)) for cpu in [30, 60, 85, 99]: print(f"4 instances at {cpu}% CPU -> {desired(4, cpu)} instances")
Output
Press Run (⌘ Enter) to see what happens.
An ASG across two AZs behind a load balancer
Auto Scaling group (min 2, max 6)Load balancerLoad balancerUsersUsersInstance: AZ aInstanceAZ aInstance: AZ bInstanceAZ bNew instance: AZ aNew instanceAZ aCloudWatch: CPU 85%CloudWatchCPU 85%scale out

Two instances in two AZs share the traffic.

1/4
Quick check
Your ASG has min 2, desired 2, max 4. One instance's app crashes and fails the load balancer health check. What happens, if the ASG uses ELB health checks?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

Target tracking capacity

An Auto Scaling group with a target tracking policy tries to keep average CPU near a target. A simple model of what it does:

desired = ceil(current_instances * current_cpu / target_cpu)

then clamp desired between the group's min_size and max_size. Write desired_capacity(current, cpu, target, min_size, max_size).

desired_capacity(4, 90, 60, 2, 10)  →  6    (4 * 90 / 60 = 6)
desired_capacity(4, 20, 60, 2, 10)  →  2    (ceil(1.33) = 2)
desired_capacity(8, 95, 50, 1, 12)  →  12   (16, clamped to max)

All inputs are positive numbers, and min_size <= max_size.

def desired_capacity( current: int, cpu: float, target: float, min_size: int, max_size: int) -> int: pass
Key terms
AMI
Amazon Machine Image: the disk image an instance boots from.
EBS volume
A network-attached block disk for an instance. Survives stops; back it up with snapshots.
security group
A stateful, allow-only firewall on an instance's network interface.
Spot instance
Spare capacity at up to about 90% off that AWS can reclaim with a 2-minute warning.
Auto Scaling group
Keeps a fleet of identical instances at the desired count, replacing unhealthy ones and scaling on metrics.
user data
A script that runs on an instance's first boot, used to install and start software.

Almost there

4 questions left before you can complete this lesson.

0/4 answered