Fun with Learning Technology
LearnCoursesQuestionsTracksToolsNewsExplorePractice
Fun with Learning Technology

A new problem, explained clearly, every day.

Subscribe
Learn
  • Lessons
  • Topics
  • News
  • Tools
  • Courses
  • Career tracks
  • Everything
Site
  • About
  • Contact
  • Support
  • Privacy
  • Terms
Get the daily one

One email per new problem. No spam.

Request a tutorial

Requests shape what gets made next.

© 2026 Fun with Learning TechnologyRSS
Home›Courses›AWS›EC2 — Instances, AMIs, and Auto Scaling

Core Services

EC2 — Instances, AMIs, and Auto Scaling

Amazon Elastic Compute Cloud (EC2) provides resizable, on-demand compute capacity in the cloud to run applications without managing physical hardware. It serves as the foundational building block for most AWS architectures, allowing developers to scale resources dynamically based on real-time traffic requirements. You reach for EC2 when you need complete control over your operating system, network configuration, and software environment.

Understanding EC2 Instance Types

EC2 instances are virtualized servers designed for specific workload profiles, such as compute-heavy, memory-intensive, or general-purpose tasks. Understanding the 'why' behind instance types is critical: they represent different physical hardware allocations on the underlying host. For example, 'c' series instances prioritize high-performance processors, while 'r' series emphasize large memory footprints for database caching. Selecting the right type prevents over-provisioning and ensures cost-efficiency. If your application crashes due to out-of-memory errors, you shift to a memory-optimized family; if it lags due to CPU bottlenecks, you switch to compute-optimized. By matching your application's resource fingerprint to the instance specification, you achieve optimal performance at the lowest possible cost. This logical mapping of requirements to hardware capabilities is the first step in designing a resilient cloud infrastructure.

# Example of identifying instance configuration using command line
aws ec2 describe-instance-types \
    --instance-types m5.large \
    --query "InstanceTypes[0].{CPU:VCpuInfo.DefaultVCpus, RAM:MemoryInfo.SizeInMiB}"

The Role of Amazon Machine Images (AMIs)

An Amazon Machine Image (AMI) acts as the blueprint for your instance, containing the operating system, file system permissions, and pre-installed software applications. Think of an AMI as a snapshot of a configured virtual machine. When you launch an instance, the system reads this blueprint to instantiate the volume structure. The reason we use AMIs is to achieve repeatable, immutable infrastructure. Instead of manually configuring a server every time, you bake your required environment—including security patches and runtime dependencies—into a custom AMI. This eliminates 'configuration drift,' where individual servers become unique snowflake environments that are impossible to troubleshoot. By treating your server configuration as a versioned image, you ensure that every instance launched is identical, predictable, and ready for service, which simplifies deployment pipelines and disaster recovery scenarios.

# Creating a custom AMI from an existing instance to use as a deployment baseline
aws ec2 create-image \
    --instance-id i-0abcdef1234567890 \
    --name "Production-Web-Server-v2" \
    --description "Hardened web server with security patches applied"

Bootstrapping Instances with User Data

While AMIs provide the static base, User Data allows you to perform dynamic configuration at runtime. User Data scripts are executed automatically when an instance starts for the first time. This is the crucial 'glue' that bridges the gap between a generic AMI and a specialized application server. By injecting variables or fetching secrets at boot, your architecture becomes flexible enough to adapt to its environment without human intervention. This mechanism is essential for scaling, as it allows new instances to automatically register themselves with load balancers or connect to persistent databases without manual setup. By keeping your AMIs 'thin' and using User Data for 'last-mile' configuration, you maintain a modular architecture where the base image rarely changes, but the behavior of your cluster remains highly customizable and responsive to environmental changes.

# A bash script provided in User Data to initialize a web server
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
echo "<h1>Hello from EC2</h1>" > /var/www/html/index.html

Auto Scaling Groups (ASG)

Auto Scaling Groups (ASG) manage the lifecycle of your EC2 instances to maintain the desired capacity and respond to fluctuating demand. An ASG works by monitoring health checks and performance metrics, automatically launching or terminating instances to match your defined criteria. The logic here is centered on elasticity: by automating the replacement of unhealthy nodes and the expansion of the fleet during traffic spikes, you ensure high availability without manual oversight. ASGs decouple your application state from the individual server instance, which is critical because cloud instances are inherently ephemeral. If an instance experiences a hardware failure, the ASG detects the failed health check and replaces it instantly with a fresh instance, ensuring that your application stays operational regardless of the underlying physical status of the hardware.

# Create an Auto Scaling Group to ensure constant capacity
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name WebServerGroup \
    --launch-template LaunchTemplateId=lt-0123456789,Version='$Latest' \
    --min-size 2 --max-size 10 --desired-capacity 3

Scaling Policies for Dynamic Demand

Scaling policies dictate when the ASG should add or remove instances, based on real-world triggers. Target Tracking policies are the industry standard: you define a goal, such as 'maintain CPU utilization at 50%,' and the system dynamically adjusts the instance count to keep performance within that target window. The reasoning behind this is predictive efficiency: instead of waiting for a manual alert to scale, the system monitors trends and adjusts resources proactively. By combining scaling policies with cooldown periods, you prevent the 'flapping' effect, where the system constantly adds and removes nodes in response to noise in the telemetry data. A well-tuned scaling policy balances cost and performance, ensuring you have exactly as much compute as you need to handle current request volumes, effectively optimizing your financial and operational overhead in real-time.

# Scaling policy to keep average CPU usage at 50%
aws autoscaling put-scaling-policy \
    --auto-scaling-group-name WebServerGroup \
    --policy-name CPU50Policy \
    --policy-type TargetTrackingScaling \
    --target-tracking-configuration '{"TargetValue": 50.0, "PredefinedMetricSpecification": {"PredefinedMetricType": "ASGAverageCPUUtilization"}}'

Key points

  • EC2 instances provide virtualized compute capacity that can be tailored to specific memory and processor requirements.
  • AMIs act as immutable blueprints that define the operating system and base application configuration for an instance.
  • User Data allows for dynamic runtime configuration of instances, enabling automated setup at the moment of launch.
  • Auto Scaling Groups ensure high availability by automatically replacing unhealthy instances and maintaining a specific fleet size.
  • Scaling policies use cloud metrics like CPU utilization to trigger the addition or removal of instances based on traffic.
  • Ephemeral nature is a core concept, meaning your applications must be designed to handle the loss of any single server.
  • Target Tracking is a preferred scaling method that keeps application performance consistent by adjusting resources to match a specific goal.
  • Effective cloud architecture relies on decoupling configuration from the underlying instance by using images and scripts in tandem.

Common mistakes

  • Mistake: Stopping an EC2 instance to change instance types without realizing the instance store data is lost. Why it's wrong: Instance store is ephemeral and wiped upon stopping. Fix: Back up critical data to EBS or S3 before stopping.
  • Mistake: Assuming an AMI is a global resource. Why it's wrong: AMIs are region-specific. Fix: Copy the AMI across regions if cross-region deployment is required.
  • Mistake: Configuring Auto Scaling cooldown periods incorrectly for short-lived spikes. Why it's wrong: Too short causes thrashing; too long prevents scaling during real demand. Fix: Analyze application metrics to set a cooldown that matches actual boot times.
  • Mistake: Relying on instance-level termination protection to prevent all data loss. Why it's wrong: Termination protection only stops API calls to terminate; it doesn't prevent data deletion or volume unattachment. Fix: Use EBS snapshots and Multi-AZ strategies for data durability.
  • Mistake: Misconfiguring the Auto Scaling health check type to EC2 when the app is crashed. Why it's wrong: EC2 health checks only detect power status, not application health. Fix: Use ELB health checks for Auto Scaling to ensure traffic is only sent to healthy applications.

Interview questions

What is an Amazon Machine Image (AMI) and why is it essential for EC2 instances?

An Amazon Machine Image (AMI) is a pre-configured template that serves as the blueprint for launching an EC2 instance. It includes the operating system, application server, and any necessary software packages. The reason it is essential is that it provides the required information to launch an instance, allowing you to deploy identical environments quickly across different AWS regions or accounts, ensuring consistency and reliability in your architecture.

Explain the role of EC2 instance types and how one should choose the right one.

EC2 instance types are specific combinations of CPU, memory, storage, and networking capacity designed for different use cases. You choose the right instance type by analyzing your application's resource demands. For example, 'c' family instances are compute-optimized for high-performance processors, while 'r' family instances are memory-optimized for RAM-intensive tasks. Choosing correctly is vital to balance performance and cost, preventing under-utilization or service degradation during peak operational loads.

How does EC2 Auto Scaling ensure high availability and cost optimization for an application?

EC2 Auto Scaling ensures high availability by automatically monitoring your applications and adding or removing instances to match demand. If an instance fails, it replaces it. To optimize costs, it scales down during low-traffic periods, preventing you from paying for idle resources. It works by using a 'Launch Template' that defines the instance configuration and 'Scaling Policies'—such as target tracking—that dictate exactly when and how many instances to provision.

Compare the differences between On-Demand instances and Spot instances in terms of use cases and risks.

On-Demand instances are for steady-state workloads where you pay for compute capacity by the second with no long-term commitment, offering high reliability as they are never interrupted. Spot instances, however, utilize spare AWS capacity at up to a 90% discount but can be reclaimed by AWS with a two-minute warning. Therefore, On-Demand is for critical production tasks, while Spot is best for fault-tolerant, flexible workloads like big data processing.

Explain the concept of an Auto Scaling Group's 'Cooldown Period' and its impact on infrastructure stability.

The Cooldown Period is a setting that instructs an Auto Scaling Group to wait for a specified time after a scaling activity completes before initiating another one. This is crucial for infrastructure stability because it allows time for newly launched instances to finish booting up, pass health checks, and begin serving traffic. Without this buffer, the system might misinterpret the initial performance metrics and incorrectly trigger another 'scale-out' event, leading to 'flapping' or unnecessary resource over-provisioning.

How would you design a fault-tolerant architecture using EC2 instances across multiple Availability Zones?

To design for fault tolerance, you should deploy your EC2 instances within an Auto Scaling Group that spans multiple Availability Zones (AZs). By spreading the load across AZs, you ensure that if one data center experiences an outage, your application remains available through the remaining healthy instances in other zones. Furthermore, you must configure a Load Balancer to distribute incoming traffic, which also performs regular health checks, automatically routing traffic away from any unhealthy instances that may have experienced internal service failures.

All AWS interview questions →

Check yourself

1. An application on an EC2 instance needs to persist data even if the instance is stopped. Which storage option should be used?

  • A.Instance Store
  • B.EBS Volume
  • C.RAM Disk
  • D.Ephemeral Storage
Show answer

B. EBS Volume
EBS volumes are persistent network-attached storage that survive instance stops. Instance Store, RAM disks, and Ephemeral storage are all cleared when an instance is stopped or terminated, making them unsuitable for persistent data.

2. What is the primary difference between a 'Stop' and a 'Terminate' action on an EC2 instance?

  • A.Stop keeps the EBS volume; Terminate deletes it
  • B.Stop incurs no cost; Terminate incurs hourly costs
  • C.Stop maintains the public IP address; Terminate releases it
  • D.Stop is only for Linux; Terminate is only for Windows
Show answer

A. Stop keeps the EBS volume; Terminate deletes it
When you terminate an instance, the associated EBS volumes are deleted by default, whereas stopping an instance preserves the root EBS volume and data. Terminated instances cannot be restarted, making the 'Stop' action the correct choice for temporary suspension.

3. You have a fleet of instances behind an Auto Scaling Group. You need to ensure that an instance is replaced if the web server process hangs, even if the EC2 status check passes. How do you achieve this?

  • A.Enable Termination Protection
  • B.Use Auto Scaling with EC2 health checks
  • C.Configure Auto Scaling to use ELB health checks
  • D.Set the cooldown period to zero
Show answer

C. Configure Auto Scaling to use ELB health checks
ELB health checks look at the application layer, allowing Auto Scaling to detect if a service is unresponsive. EC2 health checks only check hardware status, and termination protection or cooldown settings do not provide application-level monitoring.

4. An AMI has been created in the us-east-1 region. A developer in eu-west-1 cannot see this AMI to launch instances. Why?

  • A.AMIs must be shared via IAM roles
  • B.AMIs are region-locked and must be copied to the new region
  • C.The developer lacks the ec2:LaunchInstance permission
  • D.The AMI must be converted to an S3 bucket first
Show answer

B. AMIs are region-locked and must be copied to the new region
AMIs are region-bound resources. To use them in a different region, the 'Copy AMI' action must be performed to replicate the image metadata and data to the target region. IAM roles and S3 conversion are not the mechanisms for region-to-region sharing.

5. Which Auto Scaling policy type is best suited for maintaining an average CPU utilization of 50% across a group of instances?

  • A.Manual Scaling
  • B.Scheduled Scaling
  • C.Target Tracking Scaling
  • D.Step Scaling
Show answer

C. Target Tracking Scaling
Target Tracking Scaling is designed specifically to maintain a defined metric (like average CPU) at a target value by adjusting capacity automatically. Manual, scheduled, and step scaling require static definitions or fixed rules rather than dynamic adjustment to a specific target metric.

Take the full AWS quiz →

← PreviousS3 — Storage, Lifecycle, and VersioningNext →VPC — Networking Fundamentals

AWS

24 lessons, free to read.

All lessons →

Track your progress

Sign in to mark lessons done, score quizzes and keep notes.

Open in the app