EC2 Interview Questions Part 02
50+ curated AWS EC2 interview questions with detailed answers — covering instance types, Auto Scaling, load balancers, storage, networking, and more. Basic to Advanced.
Ans: Amazon EC2 (Elastic Compute Cloud) is a cloud service provided by Amazon Web Services (AWS) that allows users to create and run virtual servers in the cloud. Instead of buying and maintaining physical servers, you can launch an EC2 instance within minutes and use it to host websites, run applications, store data, perform testing, or deploy DevOps and containerized workloads.
Common use cases:
- Web and application hosting (Company websites, E-commerce application like Amazon, Flipkart)
- Batch processing and big data workloads
- Machine learning model training
- Dev, test, and staging environments
- High-performance computing (HPC)
Ans: Amazon EC2 instances can be purchased using different pricing models based on your workload requirements:
On-Demand Instances: You pay only for the time you use the instance with no long-term commitment. They are ideal for short-term, testing, development, or unpredictable workloads where flexibility is important.
Reserved Instances: You commit to using specific resources for a 1-year or 3-year term in exchange for significant discounts compared to On-Demand pricing. They are best for stable, predictable workloads that run continuously.
Spot Instances: These use AWS’s unused computing capacity and can be up to 90% cheaper than On-Demand instances. However, AWS can terminate them with short notice when the capacity is needed elsewhere, making them suitable for fault-tolerant workloads such as batch processing, data analysis, and testing environments.
Ans: EC2 instance families are groups of instance types designed for different kinds of workloads. Each family provides a different balance of CPU, memory, storage, and networking performance.
- General Purpose (T, M families): Balanced CPU and memory, suitable for web servers, small databases, and general applications.
- Compute Optimized (C family): More CPU power, ideal for high-performance web servers, batch processing, and application servers.
- Memory Optimized (R, X family): Large amounts of RAM, suitable for databases, caching, and in-memory analytics.
- Storage Optimized (I, D family): High-speed local storage, used for big data, data warehousing, and log processing.
- Accelerated Computing (G, P family): Includes GPUs for machine learning, AI, graphics rendering, and video processing.
To choose the right instance family, first identify your application’s primary requirement.
- If it needs balanced resources, use General Purpose.
- If CPU usage is high, choose Compute Optimized.
- If the application stores large amounts of data in memory, use Memory Optimized.
- For storage-intensive workloads, use Storage Optimized.
- For AI, deep learning, or graphics workloads, choose Accelerated Computing instances.
The best practice is to monitor CPU, memory, and storage utilization and select the instance family that matches the resource your application uses most.
t3.micro for low-traffic apps. Use the AWS Compute Optimizer tool to get right-sizing recommendations based on actual CloudWatch usage data.An AMI (Amazon Machine Image) is a pre-configured template containing the OS, application server, and applications needed to launch an EC2 instance. Think of it as a snapshot of a fully configured server.
AMI types:
- AWS-provided — Amazon Linux 2, Ubuntu, Windows Server
- AWS Marketplace — third-party software (e.g., Bitnami WordPress)
- Custom (private) — your own golden images with pre-installed software
--no-reboot carefully — it skips filesystem flush. For production golden images, stop the instance first to ensure data consistency.Ans:
A Security Group is like a virtual firewall for an individual EC2 instance. It works at the instance level and is stateful, meaning if you allow incoming traffic, the return traffic is automatically allowed. Security Groups only support allow rules, so anything not explicitly allowed is denied by default. They are easier to manage and are most commonly used to control access to applications
A Network ACL (NACL) is a firewall for an entire subnet. It works at the subnet level and is stateless, meaning you must explicitly define rules for both inbound and outbound traffic. Unlike Security Groups, NACLs support both allow and deny rules, giving more granular control. Rules are evaluated in order, and the first match applies.
In simple terms, Security Groups control traffic at the instance level and are stateful and allow-only, while NACLs control traffic at the subnet level and are stateless with allow and deny rules.
Ans: EC2 Auto Scaling is a feature in AWS that automatically adjusts the number of EC2 instances in your application based on demand, so your application stays available and performs well even when traffic changes.
- How it Works: It works using an Auto Scaling Group (ASG) where you define minimum, maximum, and desired number of instances. AWS continuously monitors metrics like CPU usage, network traffic, or custom CloudWatch alarms. If traffic increases and demand goes up, Auto Scaling automatically launches new EC2 instances to handle the load. When demand decreases, it removes extra instances to save cost. You can also use load balancers to distribute traffic evenly across all running instances.
EC2 Auto Scaling automatically adjusts the number of EC2 instances in a group based on demand, ensuring high availability and cost efficiency.
EC2 Auto Scaling is a feature in AWS that automatically adjusts the number of EC2 instances in your application based on demand, so your application stays available and performs well even when traffic changes.
Ans: Placement Groups are a feature in Amazon Elastic Compute Cloud (EC2) that control how your instances are physically placed in AWS data centers to improve performance or availability.
There are three types of placement groups, each used for different needs:
- Cluster Placement Group
All instances are placed close together in the same availability zone.
Best for: High-performance, low-latency workloads Use cases: HPC (High Performance Computing), big data, machine learning, real-time analytics Benefit: Very fast network performance between instances Trade-off: Lower fault tolerance (if one rack fails, impact is higher) 2. Spread Placement Group
Instances are placed on different underlying hardware (separate racks).
Best for: Critical applications needing high availability Use cases: Small number of important servers, database nodes, disaster-sensitive workloads Benefit: Reduces risk of multiple instance failures at the same time Trade-off: Limited number of instances per group 3. Partition Placement Group
Instances are divided into partitions, where each partition has its own isolated hardware.
Best for: Large distributed systems Use cases: Hadoop, Kafka, Cassandra, distributed databases Benefit: Failure in one partition does not affect others Trade-off: More complex to manage
These are the three main storage options for EC2 instances:
| Feature | EBS | Instance Store | EFS |
|---|---|---|---|
| Type | Block storage | Ephemeral block | Managed NFS |
| Persistence | Persists after stop/terminate | Lost on stop/terminate | Fully persistent |
| Performance | Up to 256,000 IOPS (io2) | Very high (NVMe SSD) | Scales automatically |
| Sharing | Single instance only | Single instance only | Multiple instances |
| Cost | Per GB provisioned | Included in instance price | Per GB used |
When to use each:
- EBS → OS volume, database storage, general workloads
- Instance Store → temp files, caching, buffers (speed over durability)
- EFS → shared file storage across multiple instances (e.g., web farm with shared
/var/www)
# Attach an EBS volume to a running instance
aws ec2 attach-volume \
--volume-id vol-0123456789abcdef0 \
--instance-id i-0abcdef1234567890 \
--device /dev/xvdf
# Then mount it on the instance
sudo mkfs -t ext4 /dev/xvdf
sudo mkdir /data
sudo mount /dev/xvdf /data
Elastic Load Balancing (ELB) distributes incoming traffic across multiple EC2 instances, increasing availability and fault tolerance.
Types of Load Balancers:
| Type | OSI Layer | Best For |
|---|---|---|
| ALB (Application) | Layer 7 | HTTP/HTTPS, path-based routing, microservices |
| NLB (Network) | Layer 4 | TCP/UDP, ultra-low latency, static IPs |
| GWLB (Gateway) | Layer 3 | Firewalls, intrusion detection appliances |
| CLB (Classic) | L4/L7 | Legacy — avoid for new workloads |
ALB path-based routing example:
https://api.example.com/users → Target Group: users-service
https://api.example.com/orders → Target Group: orders-service
https://api.example.com/ → Target Group: frontend
Health check configuration:
aws elbv2 create-target-group \
--name my-targets \
--protocol HTTP \
--port 80 \
--vpc-id vpc-0123456789abcdef0 \
--health-check-path /health \
--health-check-interval-seconds 30 \
--healthy-threshold-count 2 \
--unhealthy-threshold-count 3
User Data is a script that runs automatically when an EC2 instance first launches. It’s used to bootstrap instances — install packages, start services, or configure the system without manual intervention.
#!/bin/bash
# This runs as root on first boot
# Update packages
yum update -y
# Install and start Nginx
amazon-linux-extras install nginx1 -y
systemctl start nginx
systemctl enable nginx
# Deploy app
aws s3 cp s3://my-bucket/app.tar.gz /opt/app.tar.gz
tar -xzf /opt/app.tar.gz -C /opt/
systemctl start myapp
Passing User Data via CLI:
aws ec2 run-instances \
--image-id ami-0abcdef1234567890 \
--instance-type t3.micro \
--user-data file://bootstrap.sh
/var/log/cloud-init-output.log. If your bootstrap script fails silently, SSH in and check that file first.An Elastic IP (EIP) is a static, public IPv4 address that you can allocate to your AWS account and associate with any EC2 instance or network interface.
Why you need it:
- By default, a public IP assigned to an EC2 instance changes every time you stop and start it
- An EIP stays the same until you release it — critical for DNS records pointing to your server
# Allocate an Elastic IP
aws ec2 allocate-address --domain vpc
# Associate it with an instance
aws ec2 associate-address \
--instance-id i-0abcdef1234567890 \
--allocation-id eipalloc-0123456789abcdef0
Instance Metadata Service (IMDS) is an internal HTTP endpoint available from within any EC2 instance at 169.254.169.254. It provides runtime information about the instance without needing AWS credentials.
Commonly accessed metadata:
# Instance ID
curl http://169.254.169.254/latest/meta-data/instance-id
# Public IP
curl http://169.254.169.254/latest/meta-data/public-ipv4
# IAM role credentials (temporary)
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/my-role
# Region (via dynamic data)
curl http://169.254.169.254/latest/dynamic/instance-identity/document | python3 -m json.tool
IMDSv2 (recommended — token-based):
# Step 1: Get a session token (TTL = 6 hours)
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
# Step 2: Use the token in subsequent requests
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/instance-id
HttpTokens: required in your launch template.Both define the configuration for launching EC2 instances, but Launch Templates are the modern replacement for Launch Configurations.
| Feature | Launch Template | Launch Configuration |
|---|---|---|
| Versioning | ✅ Multiple versions | ❌ Immutable |
| Mixed instance types | ✅ Yes (On-Demand + Spot) | ❌ No |
| T2/T3 Unlimited | ✅ Supported | ❌ Not supported |
| Modification | ✅ Create new version | ❌ Must replace |
| AWS recommendation | ✅ Use this | ⚠️ Legacy |
# Create a Launch Template
aws ec2 create-launch-template \
--launch-template-name my-app-lt \
--version-description "v1 - initial" \
--launch-template-data '{
"ImageId": "ami-0abcdef1234567890",
"InstanceType": "t3.micro",
"KeyName": "my-key-pair",
"SecurityGroupIds": ["sg-0123456789abcdef0"],
"UserData": "'$(base64 -w0 bootstrap.sh)'"
}'
Stopped:
- Instance is shut down — no compute charges (you still pay for EBS storage)
- The instance can be restarted — it keeps its instance ID, private IP, EBS volumes, and IAM role
- Public IP changes on restart (unless an Elastic IP is attached)
- Instance Store data is wiped
Terminated:
- Instance is permanently deleted — cannot be recovered
- Root EBS volume is deleted by default (if
DeleteOnTermination = true) - Additional EBS volumes persist by default
# Stop an instance (recoverable)
aws ec2 stop-instances --instance-ids i-0abcdef1234567890
# Terminate an instance (permanent)
aws ec2 terminate-instances --instance-ids i-0abcdef1234567890
# Protect against accidental termination
aws ec2 modify-instance-attribute \
--instance-id i-0abcdef1234567890 \
--disable-api-termination
terminate-instances calls from the CLI, Console, or API. It does NOT prevent termination from an Auto Scaling Group scale-in event.A systematic approach to EC2 health check failures:
Step 1 — Check the System Status Check (hardware issue):
aws ec2 describe-instance-status \
--instance-ids i-0abcdef1234567890 \
--query 'InstanceStatuses[].SystemStatus'
If Status = impaired → AWS hardware issue. Use EC2 Instance Recovery or stop/start to migrate to new hardware.
Step 2 — Check the Instance Status Check (OS/software issue): Common causes:
- Out of memory (OOM)
- Full disk (
/partition at 100%) - Boot failure (kernel panic, bad fstab entry)
# Get instance console output (boot logs)
aws ec2 get-console-output \
--instance-id i-0abcdef1234567890 \
--latest \
--output text
Step 3 — ELB health check failures:
# Check target health in a target group
aws elbv2 describe-target-health \
--target-group-arn arn:aws:elasticloadbalancing:...
# Common causes:
# - App not listening on the health check port
# - Security group blocking the load balancer's health check
# - Health check path returning non-200 status code
Step 4 — If SSH is unavailable:
# Use EC2 Instance Connect (browser-based SSH) or
# Use SSM Session Manager (no open port 22 required)
aws ssm start-session --target i-0abcdef1234567890
/var/log/messages and application logs to CloudWatch Logs. When an instance is unreachable, you can still read its last logs without SSH access.Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form