
Amazon EC2AuthorCloudBrum editorial teamLast reviewedReading time~12 minLevelBeginner to advanced
Amazon Elastic Compute Cloud · Compute · Virtual servers
Rent resizable virtual servers with full control over the OS, networking and storage. Choose it when managed or serverless options can’t give you the flexibility you need.
On this page (17 sections)
Mind map: Amazon EC2 at a glance
Free to share. The downloaded image includes the CloudBrum link.
Key features (summary)
- Wide choice of instance typesGeneral purpose, compute, memory and storage optimised, plus GPU and other accelerated types.
- AMIsLaunch from AWS, Marketplace or your own machine images.
- Flexible storageAmazon EBS block volumes for persistence, instance store for fast temporary data.
- Auto Scaling & load balancingAdd or remove instances automatically behind Elastic Load Balancing.
- Nitro System & GravitonModern virtualisation, plus Arm-based Graviton processors for price-performance.
- Several purchase optionsOn-Demand, Savings Plans, Reserved Instances and Spot.
- Network & access controlVPC, security groups, IAM roles for instances, optional dedicated hardware.
- Granular billingPer-second billing (60-second minimum) for most Linux instances.
Basic concepts
- Instance
- A virtual server running in AWS. You pay while it runs.
- AMI (Amazon Machine Image)
- A template with the OS and software used to launch instances.
- Instance type
- The hardware profile (vCPU, memory, network, storage), e.g. t3.micro, m7g.large.
- Region & Availability Zone
- A Region is a geographic area; an AZ is one or more isolated data centres inside it.
- VPC & subnet
- Your private network and the IP ranges inside it where instances live.
- Security group
- A stateful virtual firewall attached to an instance’s network interface.
- EBS volume
- Network-attached block storage that persists independently of the instance.
- Key pair & IAM role
- A key pair enables SSH login; an instance profile gives the instance AWS permissions without stored keys.
- User data
- A script that runs on first boot to configure the instance. Never put secrets in it.
- Instance metadata (IMDS)
- A local endpoint an instance uses to read its own details and temporary credentials.
How to create & configure it
Launch an instance in the AWS Console
- Open EC2 and choose the RegionSign in to the AWS Console, search for EC2, and pick the Region closest to your users in the top-right selector.
- Choose “Launch instance” and name itAdd a clear Name tag plus tags such as Env and Owner.
- Pick an AMIFor example Amazon Linux 2023. Prefer a current, maintained image.
- Select an instance typeStart small (e.g. t3.micro) and resize later based on metrics.
- Set up loginCreate or choose a key pair, or skip it and use Session Manager (recommended) with an IAM instance profile.
- Configure network settingsChoose the VPC and subnet, decide on a public IP, and create a security group. Allow SSH/RDP only from your own IP range, or none at all if using Session Manager.
- Configure storageUse a gp3 volume and tick Encrypted.
- Open “Advanced details”Attach the IAM instance profile, set Metadata version to V2 only (IMDSv2), and add user data if needed.
- Review and launch, then connectWait for the status checks to pass, then connect with Session Manager or EC2 Instance Connect.
Tip: once the steps work by hand, capture them as infrastructure as code (see the code references) so every environment is identical.
Common issues after configuration
| Symptom | Likely cause | What to check / fix |
|---|---|---|
| SSH/RDP times out | Network path blocked | Security group inbound rule, network ACL, route table to an internet gateway, and a public IP. |
| “Permission denied (publickey)” | Wrong key or user | Use the key pair chosen at launch and the right user (ec2-user, ubuntu, …); key file permissions 400. |
| Instance status check failed | OS-level problem | Review the system log and screenshot in the console; reboot, or attach the volume to a rescue instance. |
| App unreachable although instance runs | Port or service | Service listening on the right interface/port, and the security group allows that port. |
| InsufficientInstanceCapacity | No spare capacity | Retry later, try another AZ or a different instance type or size. |
| VcpuLimitExceeded | Service quota | Request a quota increase in Service Quotas. |
| Disk full | Volume too small | Increase the EBS volume, then grow the partition and file system. |
| Unexpected charges | Idle resources | Stopped instances still bill for EBS and Elastic IPs; delete unused volumes, snapshots and addresses. |
Use cases: when and where to use it
Good fit
- Web and application servers with custom runtimes
- Lift-and-shift of existing servers
- Batch, rendering and HPC workloads
- GPU workloads such as ML training
- Software needing OS-level control or licensing
- Dev/test environments you can switch off
Consider something else
- Static websites → S3 + CloudFront
- Short event-driven code → AWS Lambda
- Containers → ECS, EKS or Fargate
- Simple, fixed-price servers → Lightsail
- Managed databases → RDS or DynamoDB
Pros: why consider it?
Why teams choose it
- Full control over OS, network and storage
- Huge range of sizes and hardware
- Scale up, down or out on demand
- Global footprint of Regions and AZs
- Pay only for what you run
- Deep integration with the rest of AWS
Trade-offs to weigh
- You patch and manage the OS
- Idle instances still cost money
- More operational work than managed services
- Capacity and sizing decisions are yours
- Security is a shared responsibility
Common threats, vulnerabilities & risks
| Risk | Severity | Why it matters | Mitigation |
|---|---|---|---|
| SSH/RDP open to the internet | High | Constant brute-force and exploit attempts. | Restrict sources, or use Session Manager and no inbound admin ports. |
| IMDSv1 and SSRF | High | A web flaw can fetch instance role credentials from the metadata service. | Require IMDSv2 and a hop limit of 1. |
| Over-permissive instance role | High | A compromised host gets broad AWS access. | Least-privilege policies per role. |
| Unpatched OS and software | Medium | Known vulnerabilities stay exploitable. | Systems Manager Patch Manager, Amazon Inspector. |
| Public AMIs and snapshots | Medium | Data or credentials baked into images can leak. | Keep images private, scan before sharing. |
| Secrets in user data or on disk | Medium | User data is readable from the instance. | Use Secrets Manager or Parameter Store. |
| Unencrypted volumes | Low–Med | Exposure if snapshots are shared or copied. | Turn on EBS encryption by default. |
| No logging or monitoring | Low–Med | Attacks and misuse go unnoticed. | CloudTrail, VPC Flow Logs, GuardDuty. |
Performance optimisation
- Right-size from data. Use CloudWatch metrics and AWS Compute Optimizer rather than guessing.
- Use current-generation instances built on the Nitro System; consider Graviton (Arm) if your software supports it.
- Match storage to the workload. gp3 lets you set IOPS and throughput independently; use io2 for the most demanding databases; instance store NVMe for scratch data.
- Choose EBS-optimised, network-enhanced types for I/O or network-heavy applications.
- Use placement groups (cluster) for low-latency, high-throughput node-to-node traffic.
- Watch burst credits on T-family instances; move steady, busy workloads to fixed-performance types.
- Scale horizontally with Auto Scaling groups behind a load balancer, and cache content with CloudFront.
- Place workloads near users by choosing the right Region and AZ layout.
Reduce monthly cost
FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Amazon EC2.
- Commit for steady workloads. Savings Plans or Reserved Instances can cut cost substantially versus On-Demand (AWS advertises savings of up to about 72%).
- Use Spot for fault-tolerant work such as batch, CI and stateless workers (AWS advertises up to about 90% off On-Demand).
- Right-size. Downsize underused instances using Compute Optimizer recommendations.
- Switch off non-production outside working hours with Instance Scheduler or simple automation.
- Try Graviton where possible for better price-performance.
- Clean up. Delete unattached EBS volumes, old snapshots and unused Elastic IPs; public IPv4 addresses are billed hourly.
- Prefer gp3 over gp2 for lower cost per GB and tunable performance.
- Watch data transfer. Cross-AZ and internet egress add up; keep chatty services together.
- Tag everything and set Budgets and Cost Anomaly Detection alerts.
Discount figures are AWS’s published maximums and change over time. Always confirm on the official pricing pages (see Pricing).
Security optimisation
- Use IAM instance profiles, never long-lived access keys on the instance.
- Prefer Systems Manager Session Manager over open SSH/RDP ports.
- Require IMDSv2 and set the metadata hop limit to 1.
- Apply least-privilege security groups; reference other security groups instead of wide CIDR ranges.
- Put application servers in private subnets behind a load balancer or NAT.
- Turn on EBS encryption by default for the account and Region.
- Patch with Patch Manager; scan with Amazon Inspector.
- Enable CloudTrail, VPC Flow Logs and GuardDuty; ship OS logs to CloudWatch.
- Store secrets in Secrets Manager or Parameter Store, not in user data.
- Use hardened, approved AMIs only, rebuilt regularly.
Governance & compliance
Guardrails
- Mandatory tags: Owner, Environment, CostCenter
- AWS Organizations SCPs to limit Regions and instance types
- Service Quotas and Budgets to cap sprawl
- AWS Control Tower for a governed landing zone
Continuous checks (AWS Config)
- ec2-imdsv2-check
- encrypted-volumes
- restricted-ssh
- ec2-instance-no-public-ip
For audits, use AWS CloudTrail for who-did-what, AWS Backup for retention policies, and AWS Artifact to download compliance reports. EC2 is in scope for many programmes (for example SOC, ISO 27001, PCI DSS and HIPAA eligibility), but compliance is shared: you remain responsible for how you configure and operate your instances.
Reduce carbon footprint
- Right-size and switch off idle instances. The greenest server is the one that isn’t running.
- Use efficient hardware. Graviton instances deliver the same work with less energy.
- Pick lower-carbon Regions when latency and data rules allow.
- Autoscale to match demand instead of running at peak all day.
- Use Spot for flexible jobs: it makes use of spare capacity.
- Consider managed or serverless services for spiky workloads; they share infrastructure efficiently.
- Measure it. The AWS Customer Carbon Footprint Tool in the Billing console estimates your emissions.
Pricing
Purchase options
On-Demand Flexible
Pay per second (or hour, depending on OS) with no commitment. Best for new, short or unpredictable workloads.
Savings Plans Commit
Commit to a spend per hour for 1 or 3 years for lower rates, with flexibility across instance families (Compute plans).
Reserved Instances Commit
Reserve a specific configuration for 1 or 3 years. Standard and Convertible options.
Spot Instances Cheapest
Spare capacity at a deep discount that AWS can reclaim with short notice. For fault-tolerant jobs.
What you actually pay for
- Instance running time (by type, OS, Region and purchase option)
- EBS volumes, provisioned IOPS/throughput, and snapshots
- Data transfer out to the internet and across AZs/Regions
- Public IPv4 addresses, load balancers and NAT gateways
- Software licences such as Windows Server or RHEL, where applicable
Prices differ by Region and change over time. Use the official Amazon EC2 pricing page and the AWS Pricing Calculator for current numbers. Check current Free Tier terms for new accounts.
Important code references
Launch a small, encrypted instance with IMDSv2 required. Replace the placeholder IDs with your own.
# Launch one t3.micro instance
aws ec2 run-instances \
--image-id ami-0123456789abcdef0 \
--instance-type t3.micro \
--subnet-id subnet-0123456789abcdef0 \
--security-group-ids sg-0123456789abcdef0 \
--iam-instance-profile Name=MyInstanceProfile \
--metadata-options HttpTokens=required,HttpPutResponseHopLimit=1 \
--block-device-mappings 'DeviceName=/dev/xvda,Ebs={VolumeSize=20,VolumeType=gp3,Encrypted=true}' \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=demo},{Key=Env,Value=dev}]'
# List running instances
aws ec2 describe-instances \
--filters Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[].[InstanceId,InstanceType,PrivateIpAddress]' \
--output table
resource "aws_instance" "demo" {
ami = "ami-0123456789abcdef0"
instance_type = "t3.micro"
subnet_id = "subnet-0123456789abcdef0"
vpc_security_group_ids = ["sg-0123456789abcdef0"]
iam_instance_profile = "MyInstanceProfile"
metadata_options {
http_tokens = "required" # IMDSv2 only
http_put_response_hop_limit = 1
}
root_block_device {
volume_type = "gp3"
volume_size = 20
encrypted = true
}
tags = {
Name = "demo"
Env = "dev"
}
}
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
resp = ec2.run_instances(
ImageId="ami-0123456789abcdef0",
InstanceType="t3.micro",
MinCount=1,
MaxCount=1,
SubnetId="subnet-0123456789abcdef0",
SecurityGroupIds=["sg-0123456789abcdef0"],
MetadataOptions={"HttpTokens": "required", "HttpPutResponseHopLimit": 1},
TagSpecifications=[{
"ResourceType": "instance",
"Tags": [{"Key": "Name", "Value": "demo"}],
}],
)
print(resp["Instances"][0]["InstanceId"])
// dotnet add package AWSSDK.EC2
using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
var ec2 = new AmazonEC2Client(RegionEndpoint.USEast1);
var response = await ec2.RunInstancesAsync(new RunInstancesRequest
{
ImageId = "ami-0123456789abcdef0",
InstanceType = InstanceType.T3Micro,
MinCount = 1,
MaxCount = 1,
SubnetId = "subnet-0123456789abcdef0",
SecurityGroupIds = new List<string> { "sg-0123456789abcdef0" },
MetadataOptions = new InstanceMetadataOptionsRequest
{
HttpTokens = HttpTokensState.Required, // IMDSv2 only
HttpPutResponseHopLimit = 1
},
TagSpecifications = new List<TagSpecification>
{
new TagSpecification
{
ResourceType = ResourceType.Instance,
Tags = new List<Tag> { new Tag("Name", "demo") }
}
}
});
Console.WriteLine(response.Reservation.Instances[0].InstanceId);
Best videos to explore
Short walkthrough videos for this service are being prepared. They will appear here and load only when you press play. Until then, follow CloudBrum on YouTube for new videos.
Interview questions
BasicWhat is Amazon EC2?
EC2 (Elastic Compute Cloud) provides resizable virtual servers called instances. You choose the OS image, instance type, networking and storage, and pay for what you use.
BasicWhat is an AMI?
An Amazon Machine Image is a template containing the operating system and any pre-installed software. You launch instances from an AMI and can create your own from a configured instance.
BasicWhat is the difference between stop, terminate and hibernate?
Stop shuts the instance down but keeps its EBS volumes (you no longer pay for instance time). Terminate deletes the instance, and by default its root volume. Hibernate saves memory to the root volume so it can resume where it left off.
IntermediateEBS versus instance store: when would you use each?
EBS is network-attached and persists independently of the instance, so use it for OS disks and data you must keep. Instance store is physically attached, very fast, and its data is lost when the instance stops or fails, so use it for caches, buffers and scratch data.
IntermediateSecurity group versus network ACL?
Security groups are stateful and attached to network interfaces, with allow rules only. Network ACLs are stateless, apply at the subnet level, and support both allow and deny rules.
IntermediateCompare On-Demand, Reserved/Savings Plans and Spot.
On-Demand is flexible with no commitment. Savings Plans and Reserved Instances trade a 1 or 3-year commitment for lower rates. Spot uses spare capacity at deep discounts but can be interrupted, so it suits fault-tolerant work.
AdvancedHow do you make an EC2-based application highly available?
Run instances in an Auto Scaling group across multiple Availability Zones behind an Elastic Load Balancer, use health checks to replace failed instances, keep state outside the instance (RDS, DynamoDB, S3, EFS), and test failover regularly.
AdvancedWhy require IMDSv2?
IMDSv2 uses session tokens, which blocks common SSRF attacks that could otherwise read instance role credentials from the metadata service. Requiring it, with a hop limit of 1, is a standard hardening step.
AdvancedHow can you administer an instance without opening port 22?
Attach an IAM instance profile with the SSM agent permissions and connect with AWS Systems Manager Session Manager. Access is controlled by IAM and logged, with no inbound ports required.
Similar or alternative services on other clouds
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Service | Amazon EC2 | Azure Virtual Machines | Compute Engine |
| Auto scaling | Auto Scaling groups | Virtual Machine Scale Sets | Managed instance groups |
| Machine images | AMI | Managed images, Compute Gallery | Custom images |
| Discounted spare capacity | Spot Instances | Spot VMs | Spot VMs |
| Commitment discounts | Savings Plans, Reserved Instances | Reservations, Savings plan for compute | Committed use discounts |
| Arm-based options | Graviton | Ampere Altra-based VMs | Tau T2A, Axion-based C4A |
| Keyless admin access | Session Manager | Azure Bastion | Identity-Aware Proxy (IAP) TCP forwarding |
Not sure EC2 is the right level? Compare with AWS Lambda (serverless functions), Amazon ECS and Amazon EKS (containers).
Did you find this article helpful?
Your answer helps us improve this page for the next reader.
Sources and further reading
CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.
- Amazon EC2 documentationAmazon Web Services
- Amazon EC2 pricingAmazon Web Services
- Amazon EC2 instance typesAmazon Web Services
- AWS Well-Architected FrameworkAmazon Web Services
- Amazon Compute Service Level AgreementAmazon Web Services
- AWS CLI command reference: ec2Amazon Web Services
- Terraform AWS provider: aws_instanceHashiCorp
- Boto3 EC2 client referenceAmazon Web Services
