What Does EC2 Mean?
On This Page
What do you want to do?
Quick Definition
Amazon EC2 lets you rent virtual computers in the cloud instead of buying and maintaining physical servers. You can choose the power, memory, and storage you need, and you only pay for what you use. It is like having a computer that you can turn on or off whenever you want, accessible from anywhere.
Common Commands & Configuration
aws ec2 describe-instances --instance-ids i-0abcd1234efgh5678 --query 'Reservations[0].Instances[0].[InstanceId,InstanceType,State.Name]' --output tableRetrieve specific metadata about a single instance, including ID, type, and current state, displaying it as a table.
Questions frequently require filtering or querying specific fields; mastering --query with JMESPath is essential for the Developer Associate and Solutions Architect exams.
aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t3.micro --key-name MyKeyPair --security-group-ids sg-12345678 --subnet-id subnet-12345678 --user-data file://bootstrap.sh --count 1Launch a single EC2 instance from an AMI with specified type, key pair, security group, subnet, and user data from a file.
Understanding run-instances parameters is fundamental; the exam tests your ability to build launch templates and user data files for automation.
aws autoscaling create-auto-scaling-group --auto-scaling-group-name my-asg --launch-template LaunchTemplateId=lt-12345678 --min-size 1 --max-size 5 --desired-capacity 2 --vpc-zone-identifier subnet-11111111,subnet-22222222 --health-check-type ELB --health-check-grace-period 300Create an Auto Scaling group using a launch template, specifying subnet and health check settings.
Auto Scaling with ELB health checks is a high-focus topic for AWS-SAA; knowing how to integrate health checks and graceful periods is crucial.
aws ec2 modify-instance-attribute --instance-id i-0abcd1234efgh5678 --instance-type "{\"Value\": \"t3.small\"}"Change the instance type of a stopped instance from the command line.
The exam tests that instance resizing requires a stopped state, except for some newer instance types supporting Elastic Fabric Adapter; they also test that instance-store instances cannot be resized without re-provisioning.
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/rolenameRetrieve temporary IAM role credentials from the EC2 instance metadata (IMDSv1).
This is a critical security command; exams check understanding of IMDSv1 vs v2 and how to avoid security vulnerabilities like credential theft via SSRF.
cloud-init-per once docker_install apt-get update && apt-get install -y docker.ioRun a command only on first boot using cloud-init per instance module.
The Developer Associate exam tests cloud-init and user data persistence; many questions require ensuring a package installs only once, not on every reboot.
aws ec2 request-spot-instances --spot-price "0.05" --instance-count 3 --launch-specification file://spot-config.jsonRequest multiple Spot Instances using a launch specification file.
Spot Instances appear in most compute exams; knowing how to specify Spot request parameters and configure interruption behaviors is common.
aws ec2 associate-address --instance-id i-0abcd1234efgh5678 --allocation-id eipalloc-12345678Attach an Elastic IP (EIP) to a running instance.
EIP association and disassociation scenarios: remapping for high availability, avoiding charges for unused EIPs, and understanding public IP reassignment on stop/start.
EC2 appears directly in 3,609exam-style practice questions in Courseiva's question bank — one of the most-tested concepts on CLF-C02. Practise them →
Must Know for Exams
EC2 is a primary topic in all three major AWS exams. On the AWS Cloud Practitioner exam, you are expected to understand the basic concepts, pricing models (On-Demand, Reserved, Spot), and the relationship between EC2 and other services like EBS and VPC. Questions are often scenario-based, asking which pricing model is most cost-effective for a steady-state workload versus a flexible workload. You should also know the difference between stopping and terminating an instance.
On the AWS Developer Associate exam, EC2 is central to understanding compute environments for applications. You need to know about instance metadata, user data scripts, and how to deploy applications using Elastic Beanstalk (which runs on EC2). You may encounter questions about configuring Auto Scaling groups, load balancers, and how to secure instances with IAM roles and security groups. Familiarity with instance types and their naming conventions is also tested.
For the AWS Solutions Architect Associate exam, EC2 is a deep topic. Questions often involve high-availability and fault-tolerant architectures using EC2 with multiple Availability Zones, Auto Scaling, and Elastic Load Balancing. You need to understand placement groups for low latency or high availability, and how to choose between instance store volumes and EBS for different durability and performance needs. Pricing optimization scenarios requiring Reserved Instances or Spot Instances are common. You will also troubleshoot networking issues related to security groups and NACLs.
For non-AWS exams like Google ACE, Google Cloud Digital Leader, AZ-104, and Azure Fundamentals, EC2 (and its equivalents like Google Compute Engine or Azure Virtual Machines) appears as a comparable concept. You may be asked to compare cloud compute services across providers, or to explain the benefits of virtual machines in the cloud. The foundational knowledge of virtual compute is tested, though less detailed than in AWS-specific exams.
Simple Meaning
Imagine you need a powerful computer to run a big project, but you only need it for a few hours a month. Buying a physical computer would be expensive, and it would sit idle most of the time. Amazon EC2 solves this by letting you rent a virtual computer from Amazon's data centers. You pick the specs, like how many CPUs, how much memory, and how much storage, and you can start using it in minutes. When you are done, you can turn it off and stop paying.
This virtual computer is called an instance. You can connect to it from your own laptop or desktop over the internet. It behaves just like a real computer: you can install software, run applications, host websites, or process data. Because it is in the cloud, you can also scale up to a bigger instance if you need more power, or scale down to save money. You are in control.
Think of EC2 like a utility service, similar to electricity or water. You do not build your own power plant; you plug into the grid and pay for what you use. EC2 is the same for computing: you do not need to own servers, you just tap into Amazon's massive infrastructure. This is why companies of all sizes love EC2: it is flexible, cost-effective, and removes the headache of managing hardware. For exam purposes, remember that EC2 is the foundational compute service in AWS, and almost everything else in AWS interacts with it in some way.
Full Technical Definition
Amazon Elastic Compute Cloud (EC2) is a core Infrastructure as a Service (IaaS) offering from Amazon Web Services. It provides resizable virtual machines, known as instances, that run on physical hosts in AWS data centers. Each instance is a virtualized environment that includes a chosen combination of CPU, memory, storage, and networking capacity. EC2 relies on the Xen hypervisor (and more recently, the Nitro hypervisor for newer instance types) to abstract the underlying hardware and allocate resources securely among multiple tenants.
When you launch an EC2 instance, you select an Amazon Machine Image (AMI), which is a template containing the operating system (such as Amazon Linux, Ubuntu, Windows Server) and any pre-installed software. You also choose an instance type, which defines the hardware profile. Instance types are grouped into families: general purpose (e.g., t3, m5), compute optimized (e.g., c5), memory optimized (e.g., r5), storage optimized (e.g., i3), and accelerated computing (e.g., p3 for GPU workloads). Each family is designed for specific workload patterns.
Networking is controlled through Virtual Private Cloud (VPC). Your instance is launched into a VPC subnet, and you can assign security groups (stateful virtual firewalls) that control inbound and outbound traffic. Elastic IP addresses provide static public IPs, and Elastic Network Interfaces (ENIs) allow advanced networking configurations. Storage is provided via Amazon Elastic Block Store (EBS) volumes, which are network-attached persistent block storage, or instance store volumes, which are ephemeral and physically attached to the host.
EC2 instances can be started, stopped, terminated, or rebooted. When stopped, you do not pay for the instance, but you continue to pay for any associated EBS storage. When terminated, the instance is deleted and you lose it permanently unless you have taken an AMI snapshot. You can also use Auto Scaling to automatically adjust the number of instances based on demand, and Elastic Load Balancing to distribute traffic across them. EC2 integrates with many other AWS services, such as S3 for object storage, RDS for managed databases, and CloudWatch for monitoring. Exam questions often require understanding instance pricing models (On-Demand, Reserved, Spot, and Dedicated Hosts), instance lifecycle, and placement groups (Cluster, Spread, Partition).
Real-Life Example
Think of EC2 like renting a storage unit. You need a place to store your belongings, but you do not want to buy a whole house just for storage. A storage company offers different unit sizes: a small closet for a few boxes, a medium room for furniture, or a large garage for a car. You choose the size you need, pay a monthly fee, and you can access your unit whenever you want. If your needs change, you can upgrade to a bigger unit or downsize to a smaller one.
In the cloud world, EC2 is that storage company, but for computing power. The storage units are virtual servers. The different unit sizes are instance types (like t3.micro for small tasks or m5.large for bigger jobs). You pay for the time you use the server, similar to paying rent for the storage unit. When you are done, you close the unit (stop the instance) and stop paying. The company (AWS) takes care of the building security, electricity, and maintenance, so you do not have to.
Now imagine you run a seasonal business, like an online store that gets busy during holidays. You can rent extra storage units (instances) for the busy season and let them go when things slow down. This is exactly how companies use Auto Scaling with EC2: they add more instances during high traffic and remove them when traffic drops. The analogy holds for security too. Just as you lock your storage unit and control who has the key, you use security groups and key pairs to control access to your EC2 instance. You decide who can enter and what they can do.
This mapping helps you remember that EC2 gives you on-demand, resizable compute capacity that you manage just like a physical server, but without the hardware ownership. You are renting space in a massive, secure, well-maintained facility that is accessible from anywhere.
Why This Term Matters
EC2 is the backbone of modern cloud computing for AWS. It replaces the need for organizations to buy, house, power, and maintain physical servers. This shift reduces capital expenditure and operational overhead dramatically. A startup can launch a global application without buying any hardware, and an enterprise can migrate its on-premises data center to the cloud for better agility and cost control.
From a practical IT perspective, EC2 is where most applications run. Whether you are hosting a website, running a database, processing big data, or training machine learning models, EC2 provides the raw compute power. It also enables DevOps practices like infrastructure as code, because you can launch and terminate instances programmatically using APIs, SDKs, or tools like Terraform and CloudFormation.
EC2 matters because it is not just one service; it is a platform that integrates with nearly everything else in AWS. Understanding EC2 is fundamental to understanding AWS itself. For IT professionals, knowing how to choose instance types, configure security, manage storage, and control costs is a daily skill. For exam takers, EC2 questions are among the most common and most detailed on the AWS Cloud Practitioner, Developer Associate, and Solutions Architect exams.
How It Appears in Exam Questions
EC2 questions in AWS exams typically fall into several patterns. Scenario-based questions present a company requirement, such as a web application that experiences variable traffic. You must choose the right instance type or pricing model. For example: A company runs a batch processing job that can be interrupted. The most cost-effective choice is likely Spot Instances. Another common pattern is configuration questions: you are given a requirement for a specific number of vCPUs, memory, or network performance, and you must select the correct instance size from a list.
Troubleshooting questions are also frequent. A typical scenario: An EC2 instance is not accessible from the internet. The question asks you to identify the problem. Possible causes include missing an Internet Gateway in the VPC, incorrect route table entries, security group rules not allowing inbound traffic on port 80 or 22, or the instance not having a public IP address. You need to reason step-by-step.
Another pattern involves Auto Scaling and Elastic Load Balancing. You might be shown a diagram or description of an architecture where traffic is high but instances are not being added. The question asks why the Auto Scaling group is not launching new instances. Possible answers could be a misconfigured launch template, insufficient resource limits, or Health Check failures.
For the Cloud Practitioner exam, questions are simpler but still scenario-based. For example: A company wants to migrate a legacy application that requires a specific operating system license. Which EC2 pricing model is suitable? The answer is Dedicated Hosts. For Developer Associate, you may see questions about instance metadata and user data: How can an application retrieve its instance ID without AWS API access? By querying the instance metadata endpoint (http://169.254.169.254/latest/meta-data/).
Being familiar with these patterns will help you think like the exam designers and avoid surprises.
Practise EC2 Questions
Test your understanding with exam-style practice questions.
Example Scenario
A small online bookstore called 'PageTurners' is preparing for the holiday season. During normal months, they get about 500 visitors per day. But in December, traffic spikes to 10,000 visitors daily. The owner wants to ensure the website stays fast without paying for expensive servers that sit idle most of the year.
The solution is to use EC2 with Auto Scaling. Normally, the site runs on one EC2 instance of type t3.medium, which is enough for 500 visitors. In early December, the owner creates an Auto Scaling group with a minimum of one instance and a maximum of ten. They set a scaling policy to add one instance when CPU usage exceeds 70% and remove one when it drops below 30%. The instances launch from a custom AMI that includes the web server and application code. An Application Load Balancer distributes traffic across all running instances.
During the holiday rush, as more visitors come, the CPU on the single instance rises. The Auto Scaling group detects this and launches a second instance. Traffic is now split between two servers. If traffic continues climbing, more instances are added automatically. The website stays responsive. After the holidays, traffic drops, and instances are terminated one by one until only one remains.
The owner only paid for the compute capacity used. The extra instances ran for only a few weeks. This is exactly why EC2 is popular: you get the power of many servers when you need them, but you only pay for what you use. For the exam, remember that this scenario illustrates Auto Scaling, Load Balancing, and the pay-as-you-go model of EC2.
Common Mistakes
Thinking that stopping an EC2 instance is the same as terminating it.
Stopping an instance shuts it down but keeps the underlying EBS volumes and the instance configuration intact, so you can start it again later. Terminating permanently deletes the instance and its associated EBS volumes (if delete on termination is enabled). You cannot recover a terminated instance unless you have a backup.
Remember: Stop to pause, Terminate to delete. Always double-check before terminating, and consider using stopping for cost savings when you plan to reuse the instance.
Assuming that a t2.micro instance is always free tier eligible.
The AWS Free Tier includes 750 hours per month of t2.micro (or t3.micro in some regions) for 12 months, but only for new accounts. After 12 months or if you exceed 750 hours, you will be charged. Also, free tier does not include data transfer, EBS storage, or Elastic IP addresses.
Check your billing dashboard regularly. Do not assume any instance is free after the initial year. Use AWS Budgets to set alerts.
Setting security group inbound rules too permissively, like opening all ports to 0.0.0.0/0.
Opening all ports to the entire internet exposes your instance to security threats, including unauthorized access and attacks. Security groups should follow the principle of least privilege.
Only open the specific ports required (e.g., 22 for SSH, 80 for HTTP, 443 for HTTPS) and restrict source IP ranges to known trusted addresses if possible.
Using a public IP address for every instance instead of using an Elastic Load Balancer.
Public IPs change when you stop and start an instance (unless you use an Elastic IP). Relying on direct public IPs makes scaling and failover difficult and can expose instances directly to the internet.
For a multi-instance architecture, place instances behind an Elastic Load Balancer. Use private IPs for internal communication and let the load balancer handle public traffic.
Choosing On-Demand instances for all workloads without considering Reserved or Spot instances.
On-Demand is flexible but expensive. For predictable, long-running workloads, Reserved Instances can save up to 72%. For fault-tolerant batch jobs, Spot Instances can save up to 90%. Sticking to On-Demand unnecessarily inflates costs.
Analyze your workload patterns. Use Reserved Instances for steady-state servers, Spot Instances for flexible or interruptible tasks, and On-Demand only for short-term or unpredictable needs.
Forgetting to attach an IAM role to an instance, then hardcoding AWS credentials in the application.
Hardcoding credentials is a major security risk. If the instance is compromised, credentials are exposed. IAM roles automatically provide temporary credentials that are rotated, which is more secure and easier to manage.
Always create an IAM role with the necessary permissions and attach it to the EC2 instance at launch. Your application can then use the instance metadata service to get credentials without storing them.
Exam Trap — Don't Get Fooled
{"trap":"The exam asks: 'Which of the following will persist data after an EC2 instance is terminated?' A learner might answer 'Instance Store volumes' because they are physically attached to the host and seem reliable.","why_learners_choose_it":"Instance store volumes are often faster and directly attached, so it is tempting to think they would survive termination.
However, they are ephemeral and data is lost when the instance is stopped or terminated.","how_to_avoid_it":"Remember that instance store = temporary, EBS = persistent (unless 'Delete on Termination' is enabled). For exam questions about data persistence, the correct answer is almost always EBS volumes.
Instance store is used for cache, temporary files, or replicated data."
Commonly Confused With
EC2 itself is the virtual server. Auto Scaling is a service that automatically launches or terminates EC2 instances based on conditions you define (like CPU usage). EC2 provides the compute; Auto Scaling manages the quantity. Learners often use the term 'EC2' when they mean the auto-scaling group.
EC2 is the car, Auto Scaling is the system that decides to add or remove cars from a race based on how fast they are going.
EC2 hosts your application. ELB distributes incoming traffic across multiple EC2 instances. They work together but are separate services. A common confusion is thinking ELB is part of EC2, but it is a distinct AWS service that routes traffic to EC2 (and other targets).
EC2 is the restaurant kitchen. ELB is the host who seats customers at different tables (instances) to balance the workload.
EC2 is the virtual server that uses the storage. EBS provides the block-level storage volumes that you attach to EC2 instances. You can think of EC2 as the laptop and EBS as the hard drive. You can detach an EBS volume and attach it to another EC2 instance, but you cannot do that with the instance itself.
EC2 is the computer tower, EBS is the hard drive you plug into it. You can move the hard drive to another tower.
EC2 is a flexible, fully configurable virtual server service. Lightsail is a simplified version designed for beginners or simple projects, offering pre-configured plans at fixed monthly prices. EC2 gives you full control over networking, instance types, and storage, while Lightsail abstracts much of that complexity.
EC2 is like building a custom PC from parts; Lightsail is like buying a pre-built desktop with fixed specs.
EC2 provides persistent virtual servers that run continuously (or when started). Lambda runs code in response to events, with no server to manage at all. You upload code and Lambda runs it for a short time (up to 15 minutes). EC2 is IaaS, Lambda is FaaS (Function as a Service).
EC2 is a rented car you drive around all day; Lambda is a taxi that you call only when you need a ride for a short trip.
Step-by-Step Breakdown
Choose an Amazon Machine Image (AMI)
An AMI is a template that defines the operating system and any pre-installed software. AWS provides many AMIs (Amazon Linux, Ubuntu, Windows Server, etc.), and you can also create your own custom AMIs. Choosing the right AMI is critical because it determines the base software environment for your instance.
Select an instance type
Instance types define the hardware resources: CPU, memory, storage, and network performance. They are grouped into families optimized for different workloads. For example, t3 instances are general purpose, c5 instances are compute optimized, and r5 instances are memory optimized. The choice directly impacts performance and cost.
Configure networking (VPC, subnet, security group)
You specify the VPC and subnet where the instance will reside. You also create or select a security group, which acts as a firewall controlling inbound and outbound traffic. You can assign a public IP if the instance needs to be accessed from the internet. Proper networking configuration is essential for security and connectivity.
Attach storage (EBS or instance store)
You define the root volume and any additional volumes. EBS volumes are persistent and can be detached and reattached. Instance store volumes are ephemeral but offer higher I/O performance. You must decide on volume type (gp3, io2, st1, sc1) and size based on your workload requirements.
Add user data (optional)
User data is a script that runs automatically when the instance first starts. It is commonly used to install software, update packages, or configure the application. This is a powerful tool for automation and is often tested in Developer Associate exams.
Assign an IAM role (optional but recommended)
Attaching an IAM role allows applications running on the instance to access other AWS services (like S3 or DynamoDB) securely without storing access keys. The instance metadata service provides temporary credentials automatically. This is a best practice for security.
Launch the instance
After reviewing all configurations, you launch the instance. AWS provisions the virtual machine on a physical host, attaches the storage, and applies the networking rules. The instance typically becomes ready within a few minutes. You can launch multiple instances at once.
Connect to the instance
Once the instance is running, you can connect to it using SSH (for Linux) or RDP (for Windows). You need the private key pair specified during launch. For Linux instances, you also need the public IP or DNS name. Connection issues are common exam topics, often due to security group rules or missing key pairs.
Manage and monitor the instance
After launch, you can use the AWS Management Console, CLI, or SDK to start, stop, reboot, or terminate the instance. You can also enable CloudWatch monitoring to track metrics like CPU utilization and network traffic. Automated backups can be configured via EBS snapshots.
Terminate the instance when no longer needed
To stop incurring charges, you terminate the instance. Any attached EBS volumes are deleted by default, but you can modify this behavior. Instance store volumes are always lost. Termination is permanent, so ensure you have backups of important data.
Practical Mini-Lesson
EC2 is the cornerstone of AWS compute. To use it effectively in a real IT environment, you need to think beyond just 'launching a server.' Start by selecting the right instance type for your workload. For a web server, a general purpose type like t3.large might be sufficient, but for a video encoding pipeline, a compute-optimized c5a.4xlarge could be necessary. Always benchmark your application against different types in a staging environment before going to production.
Security is also a major concern. Beyond security groups, consider using AWS Systems Manager Session Manager instead of SSH for shell access. This avoids having to manage keys and provides audit logs. For production environments, never assign public IPs directly to instances; instead, use a load balancer and NAT gateway. This keeps your instances in private subnets, reducing the attack surface.
Cost management is another daily skill. Use the AWS Cost Explorer and Trusted Advisor to identify idle or oversized instances. Right-sizing can save significant money. For example, if you have a t3.xlarge running at 10% CPU, downsizing to t3.medium might cut costs by 75%. Also, always consider Reserved Instances for workloads that run 24/7, and Spot Instances for batch jobs, big data processing, or containerized applications that can handle interruptions.
What can go wrong? Common issues include hitting service limits (e.g., max number of instances per region), running out of EBS burst credits (for gp2 volumes), and misconfigured security groups that block necessary traffic. Also, when an instance fails a health check from the load balancer, the Auto Scaling group may terminate it and launch a new one, which can cause transient outages if not properly configured. Always test your Auto Scaling policies and health checks in advance.
For professionals, infrastructure as code is a must. Write your EC2 configurations in CloudFormation or Terraform, so you can reproduce environments consistently. Use launch templates rather than launch configurations when setting up Auto Scaling groups, as they support newer features like T2/T3 unlimited. Finally, keep your AMIs updated with the latest security patches using tools like EC2 Image Builder. These practices separate a beginner from a skilled cloud engineer.
EC2 Instance Types: Family, Size, and Optimal Selection
Amazon EC2 offers a broad range of instance types optimized for different use cases. Each instance type belongs to a family based on its primary resource allocation: compute optimized, memory optimized, storage optimized, accelerated computing, and general purpose. Instance types follow a naming convention such as t3.micro, c5.2xlarge, or r5b.8xlarge. The first character (or string) indicates the instance family, such as t for burstable general purpose, c for compute optimized, r for memory optimized, i for storage optimized, g for GPU, p for general-purpose GPU, and f for FPGA. The numeric version follows (e.g., 5, 6) and indicates the generation. Newer generations typically offer better price-performance and more features, such as enhanced networking and NVMe local SSDs. The size, such as micro, large, 2xlarge, or 24xlarge, indicates the number of vCPUs and memory relative to the base size of that type.
When selecting an EC2 instance type, the primary factors are CPU, memory, network bandwidth, and local storage requirements. For general-purpose workloads with balanced resources, the T3 or M6i families are common. T3 instances are burstable, meaning they can burst above a baseline performance level with CPU credits they accumulate during low activity. This is ideal for variable workloads such as web servers or development environments. If sustained high CPU is required, the M5 or M6i fixed-performance instances are better. Compute-optimized families like C6i are for high-performance front-end fleets, batch processing, and video encoding. Memory-optimized families such as R6g provide high memory-to-CPU ratios for in-memory caches, databases, and real-time analytics.
Storage instances like I3 and I4i offer high I/O via local NVMe SSDs, critical for high-performance databases and big data. Accelerated computing instances including P3 and G4dn are outfitted with GPUs for training machine learning models, 3D rendering, and scientific simulations. Understanding how to evaluate what the exam asks about instance selection is key: you need to match the workload characteristics to the instance family. For example, an always-on database requires an M5 or R5, not a T3 burstable type, because the baseline may not meet demand. For an exam scenario about batch processing with high CPU demand, the correct choice will be C5 or C6i.
The exam also tests on the ability to resize an instance after launch: you can change the instance type only if the current instance is stopped. However, note that instances in a placement group or with an instance store as the root device cannot be resized easily. For elastic scaling, the correct approach is often to use an Auto Scaling group with a launch template that specifies the correct instance type for the target workload.
Another common exam point: the difference between burstable and fixed performance. The AWS Cloud Practitioner exam focuses on understanding the naming and matching, while the Solutions Architect exam demands a deeper reasoning of costs, performance, and the corner cases like CPU credit exhaustion on T2 or T3 unlimited mode. T2 and T3 instances accumulate CPU credits when idle and spend them when bursting. T2 Unlimited can burst beyond the baseline but incurs additional cost if credits are exhausted. T3 Unlimited does not charge extra for bursting but uses credits. Knowing when to enable T2 Unlim on a web server versus switching to M5 is a classic exam scenario.
For Google ACE and Azure exams, comparables are machine families with custom machine types, but the core concept remains: picking the right size and family based on CPU/memory/storage mix. Googles naming is different (e.g., n1-standard-2, c2-highcpu) but the logic is identical. The common mistake is assuming all instances can be burstable or that larger sizes automatically perform better for single-threaded code. Always check if the workload is CPU-bound, memory-bound, or I/O-bound.
Memory-optimized instances have been extended by the R7g series with AWS Graviton processors, which offer better price-performance for ARM-based workloads. For exam questions comparing cost and performance, the choice often includes the Graviton-based instances for scale-out architectures. However, always verify software compatibility, as some enterprise applications do not support ARM. Instance type selection is a fundamental skill across all compute exams, requiring you to map workload needs to the correct family, generation, and size. Knowing when to use T3 for cost savings and when to use a dedicated instance type for intensive workloads will separate top scorers.
How EC2 Purchasing Options Affect Cost and Availability
Amazon EC2 offers multiple purchasing options to give you flexibility in managing costs and capacity. On-Demand instances pay per second or per hour for compute capacity with no long-term commitment. They are ideal for unpredictable workloads, applications that cannot be interrupted, or when testing and developing. The Cloud Practitioner exam validates that On-Demand is the most flexible but the most expensive at base rate. Spot Instances allow you to bid on unused EC2 capacity at a significantly discounted price, up to 90% off On-Demand. However, AWS can terminate Spot Instances with a 2-minute warning when capacity is reclaimed or the Spot price exceeds your maximum bid. They are great for fault-tolerant, stateless, or batch workloads that can handle interruption. An exam tip: always choose Spot for data analytics, CI/CD workers, or other tasks that can be checkpointed.
Reserved Instances (RIs) provide a substantial discount (up to 72%) in exchange for a 1-year or 3-year term commitment. Standard RIs offer the highest discount, while Convertible RIs allow you to change instance attributes (like family or size) with a lower discount. Scheduled RIs allow you to reserve capacity for recurring daily or weekly time windows. Reserved Instances can be purchased in three payment options: All Upfront, Partial Upfront, and No Upfront. All Upfront gives the highest discount. The exam tests that RIs are best for steady-state, predictable workloads like a company database running 24/7. When you need flexibility to switch instance families later, choose a Convertible RI. Another important detail: RIs are region-specific unless you purchase a Regional RI for a given Region; they cannot be used across regions automatically.
Savings Plans offer a more flexible alternative to RIs: you commit to a specific amount of compute spend (measured in dollars per hour) for either 1 or 3 years. This applies to EC2, AWS Lambda, and AWS Fargate. The Compute Savings Plan covers all regions and instance families, but the EC2 Savings Plan only covers a specific family in a region. On exams, a Savings Plan is often the correct answer when a company wants to save money on multiple services, including serverless, without locking into exact instance types. Savings Plans provide the same discounts as RIs but with broader applicability.
Spot Instances require understanding of the Spot price and termination behavior. The exam will test that Spot Instances are not suitable for critical, short-term, or stateful workloads unless you use a Spot Fleet or Spot Block (now deprecated) in specific cases. AWS also offers Spot Instance interruptions via the Rebalance Recommendation feature, which notifies you before a termination. For the Developer Associate exam, you must know how to handle interruptions using checkpointing and instance hibernation for Spot Instances.
Dedicated Hosts give you a physical server dedicated for your use, which helps meet compliance or licensing requirements (e.g., software with per-socket licenses). Dedicated Instances run on shared hardware but are isolated at the instance level. The difference: Dedicated Hosts give you visibility into sockets and cores, enabling BYOL, while Dedicated Instances do not. The Cost Explorer shows you recommendations for purchasing options based on historical usage.
For the Solutions Architect exam, you might be asked to design a cost-optimized architecture. For example, a company with a predictable 9-5 weekday workload should combine On-Demand for the startup phase and Reserved Instances for sustained usage (after a month of observation). When the workload is spiky, use Spot for the variable part. Another scenario: a media processing application that runs for 2 hours nightly can use Spot with a Spot Fleet to maintain target capacity. Understanding how to combine purchasing options is crucial.
Takeaways: On-Demand for short-term and elastic, Reserved Instances or Savings Plans for steady-state, and Spot for stateless fault-tolerant work. A common exam trap: assuming all workloads can be moved to Spot. For databases with single points of failure, never use Spot unless you architect for failover. Always reconsider the tradeoff between cost and reliability. For the AZ-104 exam, the analogous concept is Azure Reserved VM Instances and Azure Spot VMs, but the logic of commitment vs. interruption is identical. Knowing these options by heart will let you answer cost-related scenario questions quickly.
EC2 User Data and Instance Metadata: Automation and Configuration
When launching an EC2 instance, you can specify user data to run automated configuration tasks during the first boot cycle. User data is plain text that can be shell scripts or cloud-init directives. Shell scripts should start with #! (shebang) and execute as root. This is commonly used to install software packages, update the system, set environment variables, or start services. On the exam, you will be asked to design a launch configuration or template with user data to bootstrap a web server: install Apache, add index.html, and start the service. The sequence matters: the script runs after the instance starts and only once at launch unless you enable rerun via configuration. For Windows instances, user data can be a batch script or PowerShell script using the <powershell> tag. The key exam point: user data is a one-time operation, not for ongoing configuration management.
Instance metadata is available to the instance via a special IP address 169.254.169.254 (link-local address). Metadata contains information about the instance itself: instance ID, instance type, public IP address, hostname, security groups, and the region. The most common metadata endpoints are /latest/meta-data/ and /latest/user-data/. The user data endpoint returns the script you injected. Metadata is unauthenticated when called from within the instance, meaning any process on the instance can read the metadata. This is important for security: if you have a malicious process or a vulnerable application that can be tricked into making HTTP requests, the metadata can be retrieved. That includes the temporary IAM role credentials from the /latest/meta-data/iam/security-credentials/role-name endpoint. This is a well-known attack vector. For the Developer Associate exam, you should understand that metadata is used by the AWS CLI instances to sign API calls automatically, without managing keys manually on the instance.
User data and metadata are essential for instance initialization and configuration management. A classic exam scenario: you need to launch an instance with a custom startup script to join an Active Directory domain or install a monitoring agent. You would configure user data in the launch template. For a solution where the instance needs to register with a load balancer automatically, the user data could include a script that calls the AWS CLI to register the instance. Another classical exam question: you need to retrieve the instanceID from within the instance. The answer: query the metadata endpoint using curl http://169.254.169.254/latest/meta-data/instance-id. Similarly, to retrieve the availability zone, use /latest/meta-data/placement/availability-zone.
There is also dynamic data, such as instance-identity documents, which contain information about the AWS account, region, and instanceId, signed by AWS. You can verify this document to confirm the instance is running in a specific account. This is used for trust propagation in hybrid architectures.
For the Solutions Architect exam, you must be able to distinguish between using AWS Systems Manager Run Command vs. user data. User data is run at launch; Systems Manager can execute commands on running instances at any time. When troubleshooting, if your user data script fails, check the console output or system logs. For Linux, the user data log is in /var/log/cloud-init-output.log. For Windows, check the EC2 console's system log. Common pitfalls: not including the #!/bin/bash shebang, using Windows line endings on Linux, or trying to write to read-only filesystems. The exam will test your understanding that user data is only executed on the first boot, and subsequent launches (from the same AMI) do not rerun it unless you configure cloud-init modules to always run.
Metadata service can be configured with IMDSv1 (open to any process) or IMDSv2 (uses session-based token). AWS recommends using IMDSv2 to mitigate unauthorized access to metadata. You must enable it at the instance level. The exam will ask how to secure credentials: use IAM roles with IMDSv2 required, and restrict metadata access via security group rules? Actually, security groups cannot block internal traffic; you need to enforce IMDSv2 at the instance level and use iptables to block unexpected connections. This is an advanced exam topic for the Security Specialty but can appear in the Solutions Architect scenario.
In the Google ACE exam, similar concepts exist: custom metadata from the instance metadata server is accessed at 169.254.169.254 as well, and startup scripts can be defined. On Azure, the analogous is custom script extension and instance metadata service (IMDS). The cloud-agnostic principle: user data triggers automation, metadata provides context, and both are critical for dynamic orchestration. Perfecting this knowledge will help you answer questions about bootstrapped setups, configuration management, and secure credential handling across multiple clouds.
EC2 Security Groups and Network ACLs: Stateful vs Stateless Filtering
Security groups and network ACLs (NACLs) are two vital layers of network security for EC2 instances within Amazon Virtual Private Cloud (VPC). Security groups act as a virtual firewall for instances, controlling inbound and outbound traffic at the instance level. They are stateful, meaning that if you allow inbound traffic from a certain IP address, the response traffic is automatically allowed regardless of outbound rules. This is the most important distinction testable in all AWS exams, from Cloud Practitioner to Solutions Architect. Security groups operate at the network interface (ENI) of the instance. You can attach multiple security groups to an instance, and the rules are unified (logical AND for same-direction rules, but across groups they are cumulative). If any security group allows a particular traffic, it passes. They are permissive by default with zero inbound allowed initially, and all outbound allowed by default.
Network ACLs are stateless, operating at the subnet level. They assess traffic in and out of a subnet, and you must explicitly allow both inbound and outbound traffic separately because the state is not maintained. For example, if you allow inbound HTTP (port 80) from the Internet, you must also allow ephemeral outbound return traffic (usually ports 1024-65535) for the response to flow back. NACLs process rules in order by rule number (lowest first). They are evaluated in rule order until a matching allow or deny rule; if no rule matches, the traffic is denied. A classic exam scenario: when a client on the internet sends a request to an EC2 instance in a public subnet, the security group must allow inbound on port 80, the NACL must allow inbound port 80, and also the response outbound from the subnet must be allowed by the NACL (stateless). For security groups, only inbound rule matters for the ingress, statefulness handles the response.
Another common exam question: how to achieve dual-layer security. By default, security groups have no specific deny rules; you cannot explicitly deny traffic in a security group. You use security groups to allow only specific traffic, blocking everything else by the default deny. NACLs, on the other hand, can explicitly deny traffic from specific IPs. For example, to block a specific IP address range from reaching the subnet, you add a deny rule in the NACL with a lower number than the allow rules. This is a common scenario: a DDoS attack from a particular IP block: place a DENY in NACL. But security groups cannot block the IP if it is already allowed by another rule in the same group, because they are additive.
When building web application tiers, typical design: the web tier in public subnet, the app tier in private subnet. The web layer security group allows HTTP from anywhere (0.0.0.0/0). The app layer security group allows traffic only from the web layer security group as source. This creates an implicit chain: only traffic that passed the web security group can reach app instances, even if the NACL is permissive. The NACL for the app subnet should allow inbound traffic from the web subnet CIDR for the application port, and also allow ephemeral outbound ports for responses. The exam will often ask: why a certain connection fails? For example, an instance in private subnet can connect to internet via NAT gateway, but cannot be accessed from the internet because the private subnet NACL and security groups block incoming traffic. Understanding the flow through ENI, security group, and subnet NACL is critical.
For the Cloud Practitioner exam, you need only understand the fundamental differences: stateful vs stateless, and that security groups operate at instance level, NACLs at subnet level. For Developer Associate and Solutions Architect, you must design rules for multi-tier applications, use security groups as reference for rules, and configure NACLs for stateless traffic management. A high-level exam trick: if a question says a change in an outbound security group rule affects inbound traffic, the answer is no, because security groups are stateful; only inbound rule matters for allowing return traffic. But if you change an outbound NACL rule for ephemeral ports, it can affect inbound response to outbound requests.
Security group rules can reference other security groups (e.g., allow all traffic from the app security group). NACL rules cannot reference security groups; they only refer to CIDR blocks. This is a key distinction. Security groups have a limit of 60 inbound and 60 outbound rules, and a maximum of 5 security groups per ENI, but these limits can be increased. NACL rules must be <= 20 per subnet, but can also be increased.
For Azure, the equivalent is Network Security Groups (NSGs) which are stateful at the subnet or NIC level, but Azure also has Application Security Groups (ASGs) for grouping VMs. On Google, firewalls are stateful at the VPC level. Regardless of platform, mastering stateful vs stateless and understanding the purpose of subnet-level and instance-level barriers is necessary for any cloud exam. Many questions will use a troubleshooting scenario: an EC2 instance cannot be reached on port 443, but it can be reached on other ports. The answer: check the security group inbound rule for HTTPS; the NACL inbound rule might deny; or the application on the instance is not listening on 443. The exam often combines these layers with IAM instance roles and public subnet configuration. Remember, even if security group allows, the OS firewall may block traffic. The final authority is the OS. The exam rarely goes into OS details, but they might mention that security groups do not replace host-based firewalls.
security groups are instance-level, stateful, permissive-only. NACLs are subnet-level, stateless, and can deny traffic. On the exam, if you see an issue about connectivity after a change to outbound rules, think about statefulness. If you see a need to block a specific IP, use NACL. If you need to allow traffic between instances in different subnets using a logical grouping, use security groups. Knowing these differences ensures correct answers to multiple scenario-based questions across the compute and networking sections.
Troubleshooting Clues
Instance reaches terminal state 'terminated' immediately after launch
Symptom: The instance transitions from pending to terminated without ever reaching running. No status checks pass.
The most common cause is exceeding the EBS volume limit for the instance type, or a missing permission in the instance profile (if using an IAM role). Also occurs if you try to launch an instance type not supported in the selected availability zone, or if the AMI is not compatible (e.g., HVM vs PV). The API call immediately places the instance in a terminated state during validation.
Exam clue: AWS exams test that the root cause is often an unsupported instance type or incomplete launch specification. You must check the termination reason via describe-instances or console logs.
Instance launches but SSH/RDP connection fails on first attempt
Symptom: Ping fails, SSH timeout, or RDP cannot connect. Network connectivity appears fine (public IP assigned).
Common causes: incorrect security group rules (no inbound SSH port 22 or RDP port 3389 from your IP), key pair is not the correct one used during launch, or the OS firewall on the instance is blocking inbound. Could also be that user data script overrides network configuration. Another possibility: NACL is blocking inbound port. If using a private subnet, a NAT gateway or bastion host is required.
Exam clue: A classic exam scenario: 'You can't connect to your EC2 instance even though you configured the security group correctly.' The answer often involves checking NACL rules (stateless) or that the instance uses a wrong key pair. They might also ask about public DNS resolution or using the correct IP.
User data script did not run on first boot
Symptom: Expected configuration changes (e.g., installed packages, altered config files) are missing. Instance is running but not set up as intended.
User data is executed only on first boot by cloud-init. If the AMI does not have cloud-init installed, it will not run. The script may have syntax errors (e.g., missing shebang for Linux, incorrect PowerShell formatting for Windows). On Linux, check /var/log/cloud-init-output.log. On Windows, check C:\ProgramData\Amazon\EC2-Windows\Launch\Log. Also, if you stop and start the instance, user data is not repeated.
Exam clue: Exam questions often ask why a custom bootstrap script did not take effect. The correct answer: ensure cloud-init is present, or check log files. The exam also tests that you cannot rerun user data by simply restarting; you must re-create the instance or use a configuration management tool.
High CPU credit exhaustion on burstable instances (T2/T3)
Symptom: Instance performance drops significantly, latency increases, web requests slow down. The CPU Credit Balance metric in CloudWatch drops to zero.
T2/T3 instances accumulate CPU credits when idle and spend them when active. When the credit balance exhausts, the instance is throttled to the baseline CPU performance level (e.g., t3.micro baseline is 10% of a vCPU). The workload demands more than the baseline, causing performance degradation. This is common when the instance is used for a production database without understanding burstable limits.
Exam clue: The exam tests the difference between T2 Unlimited and T3 Unlimited. Solutions Architect scenarios ask for a solution: change to T3 Unlimited, move to M5 fixed performance, or enable unlimited mode (which incurs extra costs). The correct answer balances cost and performance requirements.
Elastic IP not releasing when instance is terminated
Symptom: You terminate an instance that has an Elastic IP (EIP) associated. The EIP remains allocated in your account and incurs charges. The EIP is no longer attached to any instance.
Elastic IPs are a separate resource. When an instance is terminated, the EIP is disassociated but not released. You must manually release it via the console or AWS CLI. A small hourly charge applies for any EIP not associated with a running instance.
Exam clue: Exam questions around cost optimization: one common source of wasted spend is unattached EIPs. The exam expects you to monitor for unused EIPs and automatically release them using AWS Config rules or Lambda.
Instance running but not registered with Classic Load Balancer (or ALB)
Symptom: Load balancer health checks are failing, target group shows unhealthy. The instance is running, web server is up, security groups allow load balancer traffic.
Outbound NACL or security groups may block the load balancer's health check traffic. The health check packets come from the load balancer nodes, but if the NACL on the subnet blocks the ephemeral response ports, the load balancer cannot get a response. Also, the instance may be in a private subnet without a route to the load balancer's subnets, or the load balancer itself is in a different VPC. Another cause: instance has no route to the load balancer's source IP addresses (though ALB send health checks from a specific subnet).
Exam clue: Tested frequently: if ALB health checks fail, check that the network ACL on the instance's subnet allows inbound from the ALB subnet CIDR and allows outbound ephemeral ports. Also verify security group for the instance allows traffic from the ALB security group. Exam questions often present a configuration where all security group rules look correct but health checks still fail, pointing to stateless NACL.
IAM role attached to instance not granting expected permissions
Symptom: Applications running on the EC2 instance fail with access denied when trying to access S3 or DynamoDB. The role has appropriate policies attached.
IAM role delegation relies on temporary credentials via instance metadata. The most common mistake: the instance role's trust policy has a wrong trust relationship with EC2. But more often, the instance was launched before the role was modified, and the credentials in the metadata cache are old. Also, if the instance uses IMDSv1, any process can retrieve credentials, but if IMDSv2 is enforced, the application must use a token. Another possibility: the application is using the incorrect region endpoint.
Exam clue: The exam tests that IAM roles are preferred over access keys on EC2. Troubleshooting scenario: role is attached but application fails. The key is to verify the credentials endpoint and ensure the role policy allows the action. Also, understand that it takes a few seconds for new role permissions to propagate to the role's cache. Questions often require you to check the policy and the trust relationship.
EC2 instance in a private subnet cannot reach the internet through a NAT Gateway
Symptom: Internet-bound traffic fails. You can ping private IP of other instances, but cannot ping google.com. NAT Gateway is configured in a public subnet with an elastic IP, and there is a route to it from the private subnet.
Common causes: route table for the private subnet does not have a 0.0.0.0/0 route pointing to the NAT Gateway. The NAT Gateway may be deleted or in the wrong subnet. If the NAT Gateway is in the same subnet as the instance, a route loop may occur. Also, security group of the NAT Gateway (if any) must allow outbound traffic. Another cause: the instance lacks a public DNS resolver; ensure /etc/resolv.conf uses valid DNS servers such as the VPC default (2 AWS ones).
Exam clue: This is a classic VPC networking question for Solutions Architect. The exam asks why a private instance cannot access the internet. The corrective action is usually updating the route table. Also test that the NAT Gateway must be in a public subnet, and the instance’s security group must allow outbound traffic on ports needed (e.g., 443 for HTTPS, 80 for HTTP).
Memory Tip
Remember EC2 as 'Elastic Compute Cloud', the 'C' is for Compute, and 'Elastic' means you can stretch it up or down. A useful mnemonic for instance families: 'General (t/m), Compute (c), Memory (r), Storage (i), GPU (p)'.
Learn This Topic Fully
This glossary page explains what EC2 means. For a complete lesson with labs and practice, see the topic guide.
Covered in These Exams
Current Exam Context
Current exam versions that test this topic — use these objectives when studying.
Related Glossary Terms
A 2-in-1 laptop is a portable computer that can switch between a traditional laptop form and a tablet form, usually by detaching or rotating the keyboard.
The 24-pin motherboard connector is the main power cable that connects the computer's power supply unit (PSU) to the motherboard, supplying electricity to the motherboard and its components.
Two-factor authentication (2FA) is a security method that requires two different types of proof before granting access to an account or system.
A 3D printer is a device that creates physical objects by depositing layers of material based on a digital model.
5G is the fifth generation of cellular network technology, designed to deliver faster speeds, lower latency, and support for many more connected devices than previous generations.
The 8-pin CPU connector is a power cable from the power supply that delivers dedicated electricity to the processor on a computer's motherboard.
802.1Q is the networking standard that allows multiple virtual LANs (VLANs) to share a single physical network link by tagging Ethernet frames with VLAN identification information.
802.1X is a network access control standard that authenticates devices before they are allowed to connect to a wired or wireless network.
Quick Knowledge Check
1.Which of the following is the most cost-effective option for running a batch processing job that can be interrupted at any time?
2.What happens to data on an instance store volume when you stop an EC2 instance?
3.A security group's inbound rules allow traffic from 0.0.0.0/0 on port 22. What does this mean?
Frequently Asked Questions
Can I use EC2 to host a website?
Yes, EC2 is a common choice for web hosting. You can install a web server (like Apache or Nginx) on a Linux or Windows instance, attach an Elastic IP, and configure security groups to allow HTTP/HTTPS traffic.
Are EC2 instances secure by default?
EC2 instances come with a security group that denies all inbound traffic unless you explicitly allow it. Outbound traffic is allowed by default. However, you must manage your own operating system security (patching, firewall) and use key pairs or IAM roles for authentication.
What is the difference between stopping and terminating an EC2 instance?
Stopping puts the instance in a stopped state, preserving the EBS volumes and allowing you to start it again. Terminating permanently deletes the instance and its attached EBS volumes (if delete on termination is enabled), and you cannot recover it.
How do I change the instance type of a running EC2 instance?
You must first stop the instance, then change the instance type in the console or CLI, and then start the instance again. Not all instance types are available in all Availability Zones.
Can I migrate an EC2 instance to a different AWS region?
Yes, you can create a snapshot of the root EBS volume, copy the snapshot to the target region, and then create an AMI from the snapshot to launch an instance in the new region.
Does EC2 support GPU-based instances?
Yes, EC2 offers accelerated computing instance families like p3, p4, g4, and g5 that include GPUs for machine learning, graphics rendering, and video processing workloads.
What is the free tier limit for EC2?
The AWS Free Tier includes 750 hours of t2.micro or t3.micro instances per month for the first 12 months. This covers one instance running all month, or multiple instances sharing the 750 hours.
Summary
Amazon EC2 is the foundational compute service in AWS, providing resizable virtual servers that you can launch and manage on demand. It replaces the need for physical hardware, offering flexibility, scalability, and cost efficiency. From hosting simple websites to running complex distributed systems, EC2 is used across virtually every industry.
For IT professionals, understanding EC2 is essential for architecting cloud solutions. You need to know instance types, pricing models, networking, storage options, and security best practices. These topics are heavily tested on AWS certification exams, especially Cloud Practitioner, Developer Associate, and Solutions Architect.
The key exam takeaways are: remember the difference between stopped and terminated instances, know when to use On-Demand vs Reserved vs Spot pricing, understand security groups and how they control traffic, and be able to troubleshoot common connectivity issues. EC2 is not just a service; it is a platform that integrates with Auto Scaling, Load Balancing, EBS, VPC, and many other AWS services.
Master EC2, and you have a strong foundation for everything else in AWS. Use the step-by-step breakdown and practical mini-lesson in this glossary to deepen your understanding, and rely on the memory tips and FAQ for quick revision before your exam.