EC2 Interview Questions Part 01
50+ curated AWS EC2 interview questions with detailed answers — covering instance types, Auto Scaling, load balancers, storage, networking, and more. Basic to Advanced.
Amazon EC2 (Elastic Compute Cloud) is a web service that provides resizable virtual compute capacity in the cloud. You can launch and terminate instances on demand, paying only for what you use.
Common use cases:
- Web and application hosting
- Batch processing and big data workloads
- Machine learning model training
- Dev, test, and staging environments
- High-performance computing (HPC)
# Launch an EC2 instance using AWS CLI
aws ec2 run-instances \
--image-id ami-0abcdef1234567890 \
--instance-type t3.micro \
--key-name my-key-pair \
--security-group-ids sg-0123456789abcdef0 \
--subnet-id subnet-0123456789abcdef0 \
--count 1
AWS offers three main purchasing options for EC2 instances:
| Type | Use Case | Savings vs On-Demand |
|---|---|---|
| On-Demand | Short-term, unpredictable workloads | Baseline (no discount) |
| Reserved | Steady-state, predictable workloads (1–3 yr term) | Up to 72% |
| Spot | Fault-tolerant, flexible workloads | Up to 90% |
Key rule of thumb:
- On-Demand → dev/test, unpredictable traffic
- Reserved → production databases, always-on apps
- Spot → batch jobs, CI/CD runners, rendering
EC2 instance families are grouped by workload type:
| Family | Optimized For | Example Types |
|---|---|---|
| General Purpose | Balanced CPU/memory/network | t3, m6i, m7g |
| Compute Optimized | High CPU, low memory ratio | c6i, c7g |
| Memory Optimized | In-memory DBs, big data | r6i, x2idn |
| Storage Optimized | High I/O, NVMe SSD | i4i, d3 |
| Accelerated Computing | ML/GPU workloads | p4, g5, inf2 |
Naming convention — example m6i.xlarge:
m= family (general purpose)6= generation (6th gen)i= Intel processorxlarge= size (4 vCPU, 16 GiB RAM)
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
Creating a custom AMI:
# 1. Launch a base instance and configure it
# 2. Create an AMI from the running instance
aws ec2 create-image \
--instance-id i-0abcdef1234567890 \
--name "my-app-server-v1.0" \
--description "App server with Node.js 20 + Nginx" \
--no-reboot
# 3. Use the AMI ID to launch new instances
aws ec2 run-instances \
--image-id ami-<your-new-ami-id> \
--instance-type t3.medium
--no-reboot carefully — it skips filesystem flush. For production golden images, stop the instance first to ensure data consistency.Both control traffic in a VPC, but they operate at different layers:
| Feature | Security Group | Network ACL |
|---|---|---|
| Level | Instance level | Subnet level |
| State | Stateful | Stateless |
| Rules | Allow only | Allow + Deny |
| Evaluation | All rules evaluated | Rules evaluated in order |
| Default | Deny all inbound | Allow all traffic |
Stateful vs Stateless explained:
- Security Group (stateful) — if you allow inbound port 80, the response traffic is automatically allowed out. You don’t need a separate outbound rule.
- NACL (stateless) — you must explicitly add both inbound AND outbound rules for every connection, including ephemeral ports (1024–65535).
# Create a security group allowing HTTP + SSH
aws ec2 create-security-group \
--group-name web-sg \
--description "Allow HTTP and SSH" \
--vpc-id vpc-0123456789abcdef0
# Add inbound rules
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp --port 80 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp --port 22 --cidr 10.0.0.0/8
EC2 Auto Scaling automatically adjusts the number of EC2 instances in a group based on demand, ensuring high availability and cost efficiency.
Key components:
┌─────────────────────────────────────────────┐
│ Auto Scaling Group (ASG) │
│ Min: 2 Desired: 4 Max: 10 │
│ │
│ [EC2] [EC2] [EC2] [EC2] │
│ AZ-a AZ-a AZ-b AZ-b │
└─────────────────────────────────────────────┘
↑ scales based on
CloudWatch Alarm (CPU > 70%)
Scaling policies:
- Target Tracking — maintain a metric at a target value (e.g., keep CPU at 50%)
- Step Scaling — add/remove instances in steps based on alarm breach size
- Scheduled Scaling — scale at a specific time (e.g., every Monday 9am)
# Create a target tracking scaling policy (keep avg CPU at 50%)
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name cpu-target-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"TargetValue": 50.0
}'
Placement Groups control how instances are physically placed on the underlying hardware, affecting latency and fault tolerance.
| Type | Strategy | Best For |
|---|---|---|
| Cluster | All instances in same AZ, close together | HPC, low-latency apps, big data |
| Spread | Each instance on different hardware | Small critical apps, max fault tolerance |
| Partition | Groups of instances on separate partitions | Kafka, Cassandra, HDFS |
Cluster Placement Group:
aws ec2 create-placement-group \
--group-name hpc-cluster \
--strategy cluster
- ✅ 10 Gbps network between instances
- ❌ All instances fail if the rack fails
Spread Placement Group:
- ✅ Each instance on different rack — max 7 instances per AZ
- ✅ Ideal for critical services where one hardware failure must not take down more than one node
modify-instance-placement.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