What Is Amazon EC2? AWS Virtual Machines Explained | CloudWebSchool
Amazon EC2 (Elastic Compute Cloud) is AWS’s virtual machine service. It lets you rent a server in the cloud, choose an operating system, configure how much CPU and RAM you need, and have software running within minutes. You get full control over the environment. The trade-off is that you are also responsible for managing it.
Simple explanation
An EC2 instance is a virtual machine running on AWS hardware in one of their data centres. From your perspective it behaves exactly like a regular server: it has an IP address, an operating system, a file system, and a network interface. You can SSH into it, install software, and keep it running for as long as you need.
The key differences from owning a physical server:
- You can launch one in under two minutes from the AWS console or CLI.
- You pay per second while it runs. Stop it and the compute charge stops.
- You can change the hardware spec (instance type) at any time by stopping and restarting.
- AWS handles the physical hardware, power, and hypervisor. You handle everything inside the OS.
AWS Free Tier includes 750 hours per month of t2.micro or t3.micro usage for the first 12 months. That is enough to run one small instance continuously. Use it to learn the basics without spending anything.
Why EC2 matters
Before cloud computing, running a server meant purchasing hardware, shipping it to a data centre, and waiting weeks. EC2 made that process two minutes long. That shift changed what was economically viable: small teams could suddenly run infrastructure that previously required significant capital expenditure.
EC2 is also the foundation of a large amount of AWS infrastructure. Services like EKS, Elastic Beanstalk, and RDS often run EC2 instances under the hood. Understanding EC2 helps you understand how AWS works at a fundamental level, even when you use higher-level services that abstract it away.
For teams migrating from on-premises infrastructure, EC2 is the most familiar entry point into AWS. For teams starting in the cloud, EC2 fills the gaps that serverless and containers do not cover. These include long-running background workers, stateful applications, workloads that need full OS access, and anything that does not fit the event-driven Lambda model.
How EC2 works
When you launch an EC2 instance, AWS provisions a virtual machine on physical hardware inside your chosen AWS region and Availability Zone. Each instance is isolated from other customers by a hypervisor. Here is the full launch sequence:
- Choose an AMI. An Amazon Machine Image (AMI) is a pre-built OS image such as Amazon Linux 2023 or Ubuntu 22.04. AWS copies the AMI onto a virtual disk and boots from it. You can use public AMIs, AWS Marketplace AMIs, or your own custom AMIs.
- Pick an instance type. The instance type defines the hardware profile: vCPU count, RAM, network throughput, and whether you get a local NVMe SSD. For example,
t3.microhas 2 vCPUs and 1 GB RAM, whilem6i.4xlargehas 16 vCPUs and 64 GB RAM. - Choose a VPC and subnet. EC2 instances launch inside a VPC (Virtual Private Cloud) in a specific subnet. The subnet determines which Availability Zone the instance runs in and whether it receives a public IP automatically.
- Configure a security group. A security group is a stateful firewall that controls inbound and outbound traffic. You define rules such as “allow port 22 from my IP” for SSH, or “allow port 443 from anywhere” for HTTPS.
- Attach storage. By default, your instance gets a root EBS volume. EBS persists independently of the instance. Stop the instance and your data is still there when you restart. You can attach additional volumes at any time.
- Set an access method. Attach an SSH key pair (a
.pemfile) to connect via SSH, or use Session Manager to connect without managing key pairs or opening port 22. - Launch. AWS provisions the instance, typically within 60 to 90 seconds. You can pass a user data script that runs automatically on first boot to install software and configure the instance.
- Monitor, stop, or terminate. Stop an instance to pause compute billing while keeping the EBS volume intact. Start it again when you need it. Terminate it to permanently delete the instance and its root EBS volume.
Use a user data script to automate software setup on first boot. Instead of SSH-ing in to manually install packages every time, the script runs automatically and your instance is ready to serve traffic within seconds of launching.
EC2 vs Lambda in one analogy
EC2 is like renting a car. You pick the model (instance type), pay by the hour, and drive it yourself. AWS supplies the vehicle and keeps the engine running, but you are at the wheel. Lambda is more like a taxi. You say where you want to go and pay per trip. You never touch the steering wheel, but you also have no say in the route or when the car is available.
Key concepts
AMI (Amazon Machine Image)
An AMI is a snapshot of an operating system, configuration, and optionally pre-installed software. When you launch an instance, AWS copies the AMI to a new EBS volume and boots from it. You can use hundreds of public AMIs, create your own from a running instance, or build a golden AMI: a pre-hardened image with your software already installed so new instances are ready to serve traffic immediately. See AMIs explained for the full picture.
Instance type
The instance type sets the hardware profile. The letter prefix signals the workload family: t for burstable general purpose, m for balanced, c for compute-intensive, r for memory-intensive, g and p for GPU workloads. t3.micro is a small burstable instance; c6i.8xlarge is a large compute-optimised instance. The EC2 instance types guide covers every family in detail.
Security group
A security group acts as a stateful firewall around your instance. Rules are additive. If no rule explicitly allows traffic, it is blocked. You can reference other security groups in rules, which is useful for allowing traffic only from your load balancer or from other instances in the same group. The security groups explained page covers rule design and common patterns.
Never open port 22 (SSH) to 0.0.0.0/0 in your security group. This exposes SSH to the entire internet and your instance will receive brute-force login attempts within minutes. Restrict SSH to your specific IP, or use Session Manager and skip port 22 entirely.
Key pair and Session Manager
The traditional way to access EC2 is SSH with a key pair: AWS stores the public key and you keep the private key (.pem file). Lose the private key and you lose SSH access. A better alternative for most teams is AWS Systems Manager Session Manager, which gives you browser-based and CLI shell access without managing key pairs or opening port 22 in your security group.
EBS volume
Every instance has a root EBS volume containing the OS. EBS volumes are network-attached persistent block storage. They survive instance stops and can be detached and reattached to other instances. You can take point-in-time EBS snapshots to back up volumes and restore them later. See the EBS volumes guide for volume types, sizing, and performance tiers.
VPC and subnet
Every EC2 instance runs inside a VPC in a specific subnet. Public subnets have a route to an internet gateway, so instances can receive a public IP. Private subnets have no direct internet route; instances use a NAT gateway for outbound calls. Which subnet you choose determines your instance’s network exposure.
Elastic IP
By default, the public IP assigned to an EC2 instance changes every time you stop and start it. An Elastic IP is a static public IP that stays yours until you explicitly release it. It is free while attached to a running instance. If you leave it unattached, it costs money. Release Elastic IPs you are not actively using.
Availability Zone
Each EC2 instance runs in a specific Availability Zone (AZ) within a region: a physically separate data centre with independent power and networking. Running instances across multiple AZs protects against a single AZ failure. Auto Scaling Groups handle multi-AZ distribution automatically.
When to use EC2
EC2 is the right choice when your workload needs any of the following:
- Long-running processes. Background workers, daemons, or jobs that run for more than 15 minutes.
- Full OS access. Installing custom packages, kernel modules, or running processes that need root-level control.
- Stateful applications. Applications that maintain in-memory state or require persistent local storage between requests.
- Web or application servers. Hosting Nginx, Apache, Node.js, Python, or Java APIs behind a load balancer.
- Self-managed databases. Running PostgreSQL, MySQL, or MongoDB directly when RDS does not offer the configuration or extensions you need.
- CI/CD build runners. Running Jenkins agents or GitLab runners that need a full build environment and arbitrary tool installation.
- Machine learning training. GPU-accelerated workloads on
p3,g4dn, org5instance families where Lambda or containers are impractical. - Lift-and-shift migrations. Moving existing on-premises applications to the cloud without refactoring them first.
When not to use EC2
EC2 is the highest-overhead compute option in AWS. There are many situations where a managed service is cheaper, simpler, and more reliable:
- Short, event-driven tasks. Use Lambda. No server to manage, scales to zero, pay only per invocation.
- Containerised workloads without OS management. Use ECS with Fargate or EKS if you want container orchestration without provisioning and patching EC2 nodes yourself.
- Relational databases. Use RDS or Aurora. You get automated backups, patching, replication, and failover without running a database on EC2 yourself.
- Workloads that need to scale to zero. EC2 instances keep running and billing even when idle. Lambda and Fargate can scale to zero; EC2 cannot.
- Simple web apps or APIs with variable traffic. Unless you need OS-level control, App Runner or Fargate may be easier to operate and scale with less management overhead.
If you find yourself asking “how do I deploy this to EC2?” before you have tried Lambda or a managed service, pause and reconsider. Many beginners default to EC2 because it feels familiar, and end up managing servers for workloads that would run better and cheaper on a managed service.
The full decision framework is in the EC2 vs Lambda vs containers guide.
EC2 vs Lambda vs containers
AWS offers multiple compute models. Here is how EC2 compares on the dimensions that matter most:
| Question | EC2 | Lambda | ECS / EKS (Fargate) |
|---|---|---|---|
| Who manages the OS? | You | AWS | AWS (Fargate mode) |
| Max runtime per task? | Unlimited | 15 minutes | Unlimited |
| Scales to zero? | No | Yes | Yes (task count to 0) |
| Good for long-running daemons? | Yes | No | Yes |
| Billing when idle? | Yes | No | No (Fargate) |
| Cold start latency? | None (always running) | 100ms to a few seconds | 10 to 90 seconds (container start) |
| Operational overhead | High | Very low | Medium |
Short, stateless, event-triggered code: use Lambda. Containers without managing servers: use Fargate. Full OS control, persistent processes, or stateful workloads: use EC2. On a greenfield project, start with Lambda or Fargate and move to EC2 only when you hit a specific limitation that managed services cannot solve.
Pricing models and cost traps
AWS offers five ways to pay for EC2. The right model depends on how predictable and interruptible your workload is:
| Model | Best for | Potential savings |
|---|---|---|
| On-Demand | Development, variable workloads, short-lived instances | Baseline, no discount |
| Savings Plans | Flexible commitment across instance families and regions | Up to 66% |
| Reserved Instances | Steady-state production workloads, 1 to 3 year commitment | Up to 72% |
| Spot Instances | Batch processing, fault-tolerant and interruptible workloads | Up to 90% |
| Dedicated Hosts | Compliance requirements, bring-your-own-license (BYOL) | Varies |
Use on-demand while you are learning and experimenting. Once your usage patterns are stable and predictable, switch your baseline to Savings Plans. This typically cuts costs by 40 to 66% with low commitment risk and without needing to predict exact instance types. See the AWS billing guide for more on how compute costs accumulate.
Common cost traps
- Forgotten development instances. EC2 is billed per second with a 60-second minimum. An instance left running every weeknight for a month adds up to over 200 hours of compute billing.
- EBS volumes outliving instances. When you stop an instance, its EBS volumes continue to incur storage charges. Deleting unused volumes and snapshots is important for cost hygiene.
- Unattached Elastic IPs. Elastic IPs allocated but not attached to a running instance cost money. Audit and release any you are not actively using.
- Data transfer costs. Transferring data out of AWS to the internet is charged per GB. Moving large volumes of data out of EC2 regularly can be a significant and surprising cost driver.
Common use cases
- Web servers. Run Nginx or Apache behind an Application Load Balancer, with Auto Scaling Groups adding capacity under load and removing it during quiet periods.
- Application servers. Host Node.js, Python, Java, or .NET APIs that need persistent connections, long-running threads, or tasks that exceed Lambda’s 15-minute limit.
- Self-managed databases. Run PostgreSQL, MySQL, or Redis when you need specific extensions, OS-level tuning, or configurations that RDS does not expose.
- CI/CD build agents. Run Jenkins agents or GitLab runners on EC2, scaling in and out based on build queue depth. Launch templates make this repeatable.
- Machine learning training. Use GPU-accelerated instance families (
p3,g4dn,g5) for training large models where Lambda or containers are impractical. - Gaming servers. Host dedicated multiplayer game servers that need persistent in-memory state and consistent low latency.
- Legacy application hosting. Run software with specific OS dependencies, kernel requirements, or custom configurations that cannot easily be containerised.
EC2 is billed per second with a 60-second minimum. A test instance launched and immediately terminated still costs one minute of compute time. Set up billing alerts so unexpected charges are caught before they become a real problem.
Stopping an instance pauses compute billing and preserves the EBS volume. You can restart it later with all your data intact. Terminating an instance permanently deletes it, and the root EBS volume is deleted by default. This cannot be undone. Enable termination protection on production instances to prevent accidental deletion.
Common mistakes
- Leaving instances running when not needed. Development and test instances left on overnight or over weekends accumulate significant charges. Use AWS Instance Scheduler, set calendar reminders, or automate stop/start in your workflow.
- Opening port 22 to 0.0.0.0/0. Exposing SSH to the entire internet makes your instance a brute-force target within minutes of launch. Restrict SSH to your specific IP address, or use Session Manager to remove the need to open port 22 at all.
- Confusing stop with terminate. Stopping is reversible. Terminating is permanent and the root volume is deleted by default. Read the confirmation prompt carefully. Enable termination protection on any instance you cannot afford to lose accidentally.
- Choosing the wrong instance size. Starting oversized wastes money; starting undersized causes performance problems. Start with a reasonable mid-range size, watch CloudWatch CPU and memory metrics for a week, then right-size based on actual usage.
- Not creating an AMI before major changes. If you modify a running instance and something breaks, you want a snapshot to roll back to. Create an AMI before significant changes and before terminating instances with data or configuration you might need again.
- Skipping EBS snapshots. EBS volumes are durable but not immune to accidental deletion or corruption. Set up regular automated EBS snapshots using AWS Data Lifecycle Manager.
- Using the root account to launch instances. Always use an IAM user or role with least-privilege permissions. See the IAM overview for how to set this up correctly.
- Using EC2 when a managed service would be simpler. Running your own database, message queue, or cache on EC2 means you own patching, backups, failover, and monitoring. Evaluate RDS, ElastiCache, and other managed services before defaulting to EC2 for every data store.
Summary
- EC2 provides virtual machines in AWS. You control the OS, CPU, RAM, storage, and networking. AWS manages the physical hardware and hypervisor.
- Core concepts: AMI (OS image), instance type (hardware profile), security group (firewall), key pair or Session Manager (access method), EBS volume (persistent storage), VPC and subnet (network placement), Availability Zone (physical location).
- Five pricing models: on-demand, Savings Plans, Reserved Instances, Spot, and Dedicated Hosts. Each suits a different mix of predictability and interruption tolerance.
- Use EC2 for long-running, stateful, or OS-dependent workloads. Use Lambda for short event-driven tasks. Use Fargate for containers without node management.
- Key hygiene: restrict SSH access, set billing alerts, understand stop vs terminate, take regular AMI and EBS snapshots.
Frequently asked questions
What is Amazon EC2 in simple terms?
Amazon EC2 is AWS's virtual machine service. You rent a server in the cloud, choose the operating system and hardware specs, and run whatever software you need. You pay by the second while the instance is running, and you can stop or terminate it when you are done.
Is EC2 just a virtual machine?
Essentially, yes. An EC2 instance is a virtual machine running on AWS hardware. You get a full OS, root access, persistent storage, and a network interface, the same as a physical server but hosted by AWS. The "elastic" part means you can launch, stop, resize, and terminate instances programmatically at any time.
When should I use EC2 instead of Lambda?
Use EC2 when your workload runs for longer than 15 minutes, needs persistent state, requires full OS access, or involves long-running background processes. Use Lambda for short, event-driven tasks that can scale to zero and where you prefer not to manage infrastructure.
Do I still manage the operating system on EC2?
Yes. AWS manages the physical hardware and hypervisor, but you are responsible for the OS: applying security patches, managing software, configuring services, and monitoring health. More control means more responsibility.
What do I pay for with EC2?
You pay for instance runtime (per second, with a 60-second minimum), EBS storage (per GB per month), data transfer out of AWS, and any Elastic IPs left unattached. Stopped instances do not incur compute charges, but EBS volumes continue to cost money while they exist.