Elastic Compute Cloud (EC2) Basics

OS Virtualization 101

OS Virtualization – Core Idea
OS Virtualization – Evolution Over Time

Traditional Setup (No Virtualization)

Early Virtualization Attempt

Emulation-Based Virtualization

Para-Virtualization

Hardware-Assisted Virtualization

Single Root I/O Virtualization (SR-IOV)

OS Virtualization – Summary Table
OS VirtualizationHardware Access MethodLimitations
No virtualizationApplications access hardware through the OS kernel using system callsDoes not support running multiple operating systems on the same machine
Emulation-basedGuest OS issues system calls that are translated by the hypervisor into instructions for physical hardwareBinary translation creates significant overhead, greatly reducing performance
Para-virtualizationModified guest OS sends hypercalls directly to the hypervisor instead of making privileged hardware callsWorks only with certain OSes and requires customization for specific hypervisors
Hardware-assistedCPU intercepts guest OS system calls and routes them to the hypervisorIO operations still rely on software translation between virtual and physical devices
SR-IOV (Single Root I/O Virtualization)Hardware devices expose multiple virtual interfaces, allowing guest OSes near-direct access to physical resourcesRequires compatible SR-IOV-enabled hardware, but provides excellent scalability and performance

Amazon EC2 (Elastic Compute Cloud) 101

Amazon EC2 – Core Concepts
EC2 Instances

EC2 Instance States

  1. Running (Active)
    • The instance is operational
    • Charges apply for compute, memory, networking, and storage
  2. Stopped (Inactive)
    • The instance is powered off
    • Charges apply only for storage
    • Can be restarted later
  3. Terminated (Deleted)
    • The instance is permanently removed
    • Cannot be recovered or restarted
    • No further charges apply
Connecting to Amazon EC2 Instances via SSH

Summary diagram:

Connecting to Older Windows Instances via RDP

Amazon Machine Image (AMI)

AMI Components:

Summary diagram:

EC2 Architecture & Resilience

EC2 Architecture

EC2 Instances

EC2 Hosts

EC2 Resiliency

EC2 Storage

EC2 Storage – Summary Table

EC2 StorageLocationDurabilityKey Benefit
Instance StorePhysically attached to the EC2 hostTemporary (data lost if instance stops or moves)Very high performance and low latency
Amazon EBS VolumeNetwork-based storage attached to the instancePersistent (data retained independently of instance lifecycle)Reliable storage with strong durability and availability

EC2 Networking

What is Amazon EC2 best used for?

EC2 Instance Types

Selecting an EC2 Instance Type

Factors Influenced by Instance Type

  1. Raw resources
    • CPU, memory, local storage type, and storage capacity
  2. Resource ratios
    • Example: a compute-optimized instance provides more CPU but less memory for the same cost
  3. Storage and network bandwidth
    • Example: EBS throughput depends on the instance’s capabilities; insufficient instance bandwidth may become the bottleneck
  4. System architecture
    • ARM vs x86 architectures
  5. CPU vendor
    • Example: Intel vs AMD processors
  6. Extra features/capabilities
    • Specialized hardware such as GPUs, FPGAs, or enhanced networking

Key takeaway: EC2 instances are highly customizable, allowing you to tailor compute resources to match your workload requirements precisely.

EC2 Instance Categories

Purpose: Group instance types based on workload characteristics and optimization goals

1. General Purpose

2. Compute Optimized

3. Memory Optimized

4. Accelerated Computing

5. Storage Optimized

Mnemonic to remember categories:
“Great Pirates Conquer Oceans, Master Onboard Acrobatics, Collect Stolen Opulence”

Decoding EC2 Instance Type

Example: R5dn.8xlarge

1. Family (R)

2. Generation (5)

3. Size (8xlarge)

4. Extra Capabilities (dn)

EC2 Instance Connect vs EC2 SSH

Well-Known Ports for Layer 7 Protocols
Connecting to EC2 via SSH
EC2 Instance Connect

Storage Refresher

Storage Types in EC2

1. By Location

2. By Persistence

AWS Storage Categories

1. Block Storage

2. File Storage

3. Object Storage

Storage Categories – Summary Table

Storage CategoryCollection ofStructureMountableBootable
Block StorageAddressable blocksNo built-in structure, configurable by OSYesYes
File StorageFilesFile system (FS)YesNo
Object StorageObjectsFlat (cannot configure hierarchy)NoNo
Storage Performance

Storage performance is determined by three interrelated metrics—they cannot be considered in isolation:

  1. Block Size (IO Size)
    • Size of data chunks written or read from storage
    • Measured in bytes (kB, MB…)
  2. IOPS (Input/Output Operations Per Second)
    • The number of read/write operations per second that the storage can handle
  3. Throughput
    • Amount of data processed per second
    • Measured in bytes per second (MB/s, Mbps…)

Relationship: Throughput=Block Size×IOPS
Analogy: Racing car

Key Considerations

Best practice in AWS:

Amazon EBS (Elastic Block Store) – Architecture

Amazon EBS – Key Concepts & Architecture

EBS Volume Types

EBS – General Purpose SSD (GP2 & GP3)

Types:

TypeNotesPerformanceUse cases
GP2Default SSDBurstable IOPS based on volume sizeBoot volumes, low-latency apps, Dev/Test
GP3Newer SSD, generally cheaperIOPS & throughput configurable independently from sizeBoot volumes, low-latency apps, Dev/Test, virtual desktops, medium single-instance DBs (MSSQL, Oracle)

Exam tip: Remember the size range, IOPS credit system, and GP2 vs GP3 differences. These details often appear in multiple-choice questions.

EBS GP2 Volumes – Key Points

GP3 – General Purpose SSD (newer version of GP2)

EBS – Provisioned IOPS SSD (IO1 / IO2 / IO2 Block Express)

EBS Provisioned IOPS SSD – Performance Comparison

Volume TypeSize RangeMax IOPSMax ThroughputMax IOPS per GBNotes
IO14 GB – 16 TB64,0001,000 MB/s50Original provisioned IOPS SSD
IO24 GB – 16 TB64,0001,000 MB/s500Higher durability & better price/performance vs IO1
IO2 Block Express4 GB – 64 TB256,0004,000 MB/s1,000Enterprise-grade extreme performance
EBS – Maximum Performance per EC2 Instance
EBS Volume TypeMax IOPS per EC2 InstanceMax Throughput per EC2 Instance
GP2 & GP3260,0007,000 MB/s
IO1260,0007,500 MB/s
IO2160,0004,750 MB/s
IO2 Block Express260,0007,500 MB/s
EBS HDD-Based Volumes

EBS ST1 – Throughput Optimized HDD

EBS SC1 – Cold HDD

EBS HDD Volumes – Type Performance Table

HDD TypeMax IOPSMax ThroughputBaseline RateBurst Rate
ST1500 IOPS500 MB/s40 MB/s per TB250 MB/s per TB
SC1250 IOPS250 MB/s12 MB/s per TB80 MB/s per TB

EC2 Instance Store Volumes – Architecture

Knowing the advantages and limitations of instance store volumes helps optimize cost and performance, while misusing them can lead to major issues.

EC2 Instance Store – Key Features
EC2 Instance Store – Architecture

Choosing Between EC2 Instance Store and EBS Volumes

Common Requirements for Storing EC2 Data

EBS Snapshots, Restore, and Fast Snapshot Restore (FSR)

EBS Snapshots – Key Characteristics
EBS Snapshot Restore – Performance & Fast Snapshot Restore (FSR)

DEMO: Useful Commands for Storage Volumes (Linux only)

Example: Mount an EBS Volume & Add a File

EBS Encryption

EBS Encryption – Overview
EBS Volume Encryption
EBS Snapshot Encryption
Additional Facts

Software Disk Encryption (OS-level)

EC2 Network Interfaces, Instance IPs, and DNS

EC2 Networking – Architecture
ENI Attributes & Configurations

AWS Console shows ENI attributes under the instance, but they belong to the ENI(s), not the instance itself.

Amazon Machine Images (AMIs)

Amazon Machine Image (AMI) – Key Concepts
AMI Creation (Baking)
AMI Lifecycle (4 Phases)
  1. Launch → start instance from existing AMI
  2. Configure → prepare instance with business-specific software/configuration
  3. Create Image → AMI creation generates volume snapshots and updates Block Device Mapping
  4. Launch (again) → new instance launched from AMI
    • EBS volumes restored from snapshots
    • Device IDs preserved
    • Supports the rapid creation of many instances with identical configuration

DEMO: Running WordPress with EC2

WordPress (WP) – Overview
Manual WP Install on EC2
Bake AMI with WP and Launch EC2
Copying and Sharing a WordPress AMI

EC2 Purchase Options

EC2 Purchase Options / Launch Types – Overview
EC2 Shared Hosts
EC2 On-Demand Instances
EC2 Spot Instances

Example:

  1. Initial spot price: 2 coins
  2. Spot price rises to 4 coins
    • Customer A’s instance (max bid 2) is terminated
    • Customer B’s instance (max bid 4) continues running
    • The freed capacity may now be used by On-Demand customers
  3. Key point: You only pay the current spot price, not your max bid.
  4. Risk: Spot instances can be terminated if the spot price exceeds your max bid.

EC2 Reserved Instances (RIs)

EC2 Dedicated Hosts – Key Points
EC2 Dedicated Instances – Overview
EC2 Host Models – Overview Table
EC2 Host ModelWho Manages Host CapacityDedicated Hardware?Billing SummaryTypical Use Case
Shared HostsAWSNoInstance fees only (runtime + allocated resources like storage & network)Default option for general workloads
Dedicated InstancesAWSYes1. Hourly regional fee for dedicated instances 2. Instance runtime feesWhen dedicated hardware is required but AWS manages host capacity
Dedicated HostsCustomerYesPay for the full hostSoftware licensed per physical HW (cores/sockets) or strict isolation needs
EC2 Shared Host Instance Types – Overview Table
Shared Host Instance TypeCost AdvantageInterruptionsRecommended Use Cases
On-DemandNoNone• Short-term or unpredictable workloads • Applications that cannot be interrupted
SpotHigh (up to 90%)Possible (if spot price exceeds your max)• Non-urgent workloads • Jobs that can be stopped and restarted • Bursty or parallelizable workloads • Stateless applications
ReservedModerate to High (depends on commitment)None (with capacity reservation, interruptions avoided even under high demand)• Long-term, steady workloads • Business-critical applications where uptime is essential

EC2 Reservations

AWS Reservations – Core Concepts
EC2 Reserved Instances (RIs)

Payment options:

  1. No Upfront – pay per-second instance fee at a reduced rate, no initial payment
    • Low barrier to entry
    • Smaller discount compared to upfront options
  2. Partial Upfront – pay part upfront, reduce per-second fees significantly
    • Balanced option
  3. All Upfront – full payment upfront, no per-second charges
    • Maximum discount

RI Scope:

  1. Regional – discounts apply across all AZs in a region; no capacity guarantees
    • Flexible, but the priority is the same as on-demand
  2. Zonal – discounts only in the specified AZ; includes capacity reservation
    • Less flexible but ensures higher launch priority

Standard RIs

Scheduled RIs (Discontinued)

EC2 Capacity Reservations
Compute Savings Plans

EC2 Instance Status Checks & Auto Recovery

EC2 Instance Status Checks (Monitoring EC2 Health)

EC2 Status Check Alarms

EC2 Auto Recovery

EC2 Termination Protection and Shutdown Behavior

Shutdown Behavior of EC2 Instances
EC2 Termination Protection

EC2 Instance Metadata Service (IMDS)

EC2 Instance Metadata – Overview
DEMO: Useful Commands for EC2 Instance Metadata

EC2 Instance Metadata Query Tool

Vertical & Horizontal Scaling

System Scaling
Vertical Scaling
Horizontal Scaling
Horizontal vs Vertical Scaling – Key Comparison

Advanced EC2

EC2 Bootstrapping with User Data

Bootstrapping Concepts
EC2 User Data
EC2 Bootstrapping – Architecture
  1. An EC2 instance is launched with its boot volume attached
  2. User Data is provided to the instance at launch
  3. The operating system checks for the presence of User Data
  4. If present, it is executed as a startup script
  5. The instance remains in a running state during execution
    • If the script succeeds → instance becomes service-ready
    • If the script fails → instance may run but be incorrectly configured
    • Instance health checks may pass even if setup is still ongoing, so “running” does not always mean “ready”
EC2 Bootstrapping – Boot-Time-To-Service-Time

Enhanced EC2 Bootstrapping with CFN-INIT

CFN-INIT – Key Concepts
CFN-INIT – Architecture
  1. CFN-INIT is triggered through UserData provided to the instance
    • Example: /opt/aws/bin/cfn-init -v --stack ${AWS::StackId} --resource EC2Instance --configsets wordpress_install --region ${AWS::Region}
  2. It retrieves configuration details from the CloudFormation template
    • Found under the Metadata section → AWS::CloudFormation::Init
  3. It applies the configuration to move the instance toward the defined desired state
    • Works with stack updates
      • Unlike User Data (which runs only once), CFN-INIT can reapply configuration whenever the stack is updated
      • This allows ongoing configuration management after launch
CFN CreationPolicy and CFN-SIGNAL

DEMO: Bootstrapping EC2 WordPress Installation

Configuring Bootstrap Scripts in EC2 User Data

Diagnosing Problems with EC2 Bootstrap Scripts

  1. User Data can always be retrieved from the Instance Metadata Endpoint
    • For newer AMIs (e.g., Amazon Linux 2023), a token may be required before accessing it.
  1. Log files are located in /var/log and provide execution details:
    • cloud-init-output.log → includes executed commands and their output
    • cloud-init.log → includes only the commands executed during boot
Bootstrapping WordPress with CFN-INIT

Diagnosing Problems with CFN-INIT

EC2 Instance Roles & InstanceProfile

EC2 Instance Roles – Architecture

EC2 Instance Profile

Credential Precedence for AWS CLI

SSM Parameter Store

SSM Parameter Store – Key Concepts
SSM Parameter Store Tiers
SSM Parameter Store TierNumber of ParametersParameter Value SizeParameter Policies AvailableCost
StandardUp to 10,000Up to 4 KBNoFree*
AdvancedNo limitUp to 8 KBYesPaid

*Additional charges may apply for higher throughput usage.

SSM Parameter Store – Characteristics
Useful CLI Commands for Retrieving Parameters

System and Application Logging on EC2

CloudWatch Logs for EC2
Demo: CloudWatch Agent Setup for WordPress EC2 Instance
  1. Create and configure an IAM role
    • Role type: EC2
    • Attach required managed policies:
      • CloudWatchAgentServerPolicy
      • AmazonSSMFullAccess
  2. Install the CloudWatch Agent
    • Command: sudo dnf install amazon-cloudwatch-agent
  3. Run the configuration wizard
    • Command:
      sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
    • Accept most defaults, but choose advanced metrics when prompted
    • Define log files to collect, such as:
      • /var/log/secure → authentication and security logs
      • /var/log/httpd/access_log → Apache access activity
      • /var/log/httpd/error_log → Apache error events
  4. Save the configuration
    • Stored locally at:
      /opt/aws/amazon-cloudwatch-agent/bin/config.json
    • Optionally store it in SSM Parameter Store for reuse
  5. Prepare required directories and files
    • Some Linux instances do not include required paths by default
    • Create them manually:
      • sudo mkdir -p /usr/share/collectd/
      • sudo touch /usr/share/collectd/types.db
  6. Start the CloudWatch Agent
    • Command:
      sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c ssm:AmazonCloudWatch-linux -s
    • This command retrieves the configuration from SSM and starts the agent

EC2 Placement Groups

EC2 Placement Groups – Overview
Cluster Placement Groups
Spread Placement Groups
Partition Placement Groups
EC2 Placement Groups – Summary Table
Feature / TypeCluster Placement GroupSpread Placement GroupPartition Placement Group
Placement StrategyInstances placed very close togetherInstances placed on separate hardwareInstances grouped into isolated partitions
Availability ZonesSingle AZ onlyCan span multiple AZsCan span multiple AZs
PerformanceVery high (low latency, high BW)StandardHigh within each partition
Fault ToleranceLowVery highHigh (isolated per partition)
Instance LimitNo fixed limit (capacity dependent)7 instances per AZ7 partitions per AZ (many instances each)
Hardware SharingOften sharedFully isolatedShared within partition only
Best Use CasesHPC, tightly coupled workloadsCritical isolated systemsLarge distributed, topology-aware systems
ComplexityLowLowHigher (requires planning)

EC2 Dedicated Hosts

CPU Sockets and Cores
EC2 Dedicated Hosts – Key Concepts & Overview

Types of Dedicated Hosts

Traditional Dedicated Hosts

Nitro-Based Dedicated Hosts

EC2 Dedicated Hosts – Considerations & Limitations

EC2 Enhanced Networking & EBS-Optimized Instances

EC2 Enhanced Networking
EBS-Optimized Instances

Containers & ECS

Containerization 101

OS Virtualization Problems
Containerization (Container Virtualization)
Image Anatomy
Container Anatomy
Container Registry

Amazon ECS (Elastic Container Service) 101

Amazon ECS – Key Concepts
Amazon ECS – Definitions

Container Definition

Task Definition

Service Definition

ECS Cluster Modes

Amazon ECS – EC2 Mode
Amazon ECS – Fargate Mode
ECS Cluster Modes – Comparison
ECS Cluster ModeContainer Host LocationContainer Host ManagementBilling
EC2EC2 instancesCustomerPay for full instances, regardless of container usage
FargateAWS-managed platformAWS (Fargate)Pay only for resources used by running tasks
Choosing Between EC2, ECS-EC2, and ECS-Fargate

DEMO: Build, Register, and Deploy a Docker Container Image on AWS

Running Docker on an EC2 Instance (Amazon Linux 2)
  1. Launch a t2.micro EC2 instance using Amazon Linux 2, then connect to it once it is running
  2. Install Docker on the instance sudo dnf install docker
    • DNF is a package manager used to install, update, and remove software packages on modern Linux distributions (successor to YUM)
  3. Start the Docker service sudo service docker start
  4. Verify Docker is running by listing containers docker ps
    • This will initially return a permission error because the current user is not allowed to interact with Docker
  5. Grant Docker permissions to the default user sudo usermod -a -G docker ec2-user
    • Adds ec2-user to the Docker group, allowing interaction with the Docker Engine
  6. Log out of the instance and reconnect
    • Required for group membership changes to take effect
  7. Switch to the ec2-user (if needed) sudo su – ec2-user
    • Necessary when using Session Manager instead of SSH or Instance Connect
  8. Run the verification command again docker ps
    • Should now execute without errors (no containers will be listed initially)
STEP 2: Building the “Container of Cats” Docker Image
STEP 3: Deploying “Container of Cats” with ECS Fargate
  1. Create an ECS cluster and select Fargate as the launch type
  2. Define a task
    • Add a container definition
    • Provide the image URI from Docker Hub (created in Step 2)
  3. Run the task in the ECS cluster
    • Choose a VPC where the task will be deployed

Container Image Registry (Amazon ECR)

Amazon ECR – Key Concepts
Amazon ECR – Benefits

Kubernetes Basics 101

Kubernetes (K8s) Concepts

Core Components

Kubernetes Cluster Structure

Node Components

Control Plane Components

Kubernetes Architecture Diagrams

Amazon EKS (Elastic Kubernetes Service) Basics

Amazon EKS – Key Concepts
Amazon EKS – Architecture