Amazon EC2

A practical guide to instances, networking, security, SSH, storage, IAM, deployment, and troubleshooting

Purpose: Use this document as a clear reference when creating and operating Linux EC2 servers.

1. What is EC2?

Amazon Elastic Compute Cloud (EC2) provides virtual servers in AWS. An instance is a server on which you choose the operating system, CPU, memory, storage, network, security rules, and permissions.

Simple mental model: EC2 is the server; the VPC is the network; security groups are the firewall; IAM roles provide AWS permissions; EBS is the disk; CloudWatch monitors the server.

2. Core architecture

User
  |
  v
Route 53 / Load Balancer
  |
  v
Public subnet
  |
  v
Private EC2 application instances
  |
  v
Private database
ComponentPurpose
RegionGeographic AWS location, such as us-east-1.
Availability ZoneIsolated data center inside a Region. Use more than one for availability.
AMITemplate containing an operating system and optional software.
VPCPrivate network containing subnets, routes, and network controls.
SubnetIP range inside a VPC; it is public or private according to its routes.
Security groupStateful firewall attached to the instance network interface.
IAM roleTemporary AWS permissions available to applications on the instance.

3. Instance types and pricing

An instance type determines vCPUs, memory, network performance, EBS bandwidth, and sometimes GPUs or local disks.

FamilyUseExamples
General purposeBalanced CPU and memory for web servers and APIs.t3, t4g, m7i
BurstableLow average CPU with occasional bursts; uses CPU credits.t3.micro, t4g.small
Compute optimizedCPU-heavy APIs, encoding, batch jobs.c7i, c7g
Memory optimizedIn-memory databases, caches, analytics.r7i, x2idn
Storage optimizedHigh local storage throughput and I/O.i4i, d3
AcceleratedGPU, machine learning, rendering, specialized processing.g, p, inf, trn

Common sizes progress from nano, micro, small, medium, large, and xlarge to larger multiples.

Pricing optionWhen to use it
On-DemandFlexible or short-lived workloads without commitment.
Reserved Instances / Savings PlansPredictable workloads running for a long period.
SpotInterruptible, fault-tolerant jobs such as batch processing.
Cost reminder: Also budget for EBS, snapshots, public IPv4 addresses, NAT Gateway, load balancers, data transfer, CloudWatch, and software licenses.

4. Launching an instance

Choose the AMI, instance type, key pair, VPC, subnet, public-IP behavior, security group, EBS volumes, IAM role, user data, and tags.

Example
AMI: Ubuntu Server LTS
Type: t3.micro
Subnet: public-subnet-a
Public IP: enabled for a temporary demo
Security group: SSH from my IP, HTTP from the Internet
Root volume: 20 GiB gp3
IAM role: application-role

User data

User data runs during first boot and is useful for repeatable setup. Do not put long-term secrets in it.

#!/bin/bash
apt-get update -y
apt-get install -y nginx
systemctl enable --now nginx
echo "Hello from EC2" > /var/www/html/index.html

Lifecycle

ActionResult
StartStarts a stopped instance. A normal public IP may change.
StopStops compute; EBS data normally remains.
RebootRestarts the operating system.
HibernateSaves memory to EBS, then stops.
TerminateDeletes the instance; root volume may also be deleted.

5. VPC, subnets, and IP addresses

VPC: 10.0.0.0/16
  Public subnet:  10.0.1.0/24  -- route to Internet Gateway
  Private subnet: 10.0.2.0/24  -- no direct inbound Internet route
  Database subnet:10.0.3.0/24

A public subnet has a route to an Internet Gateway. A private instance can make outbound connections through a NAT Gateway, but inbound Internet traffic is not directly routed to it.

AddressMeaning
Private IPv4Used inside the VPC, for example 10.0.2.25.
Public IPv4Internet address that may change after stop/start.
Elastic IPStatic public IPv4 address; use sparingly.
IPv6Optional address family requiring IPv6 routes and firewall rules.

6. Security groups and network ACLs

Security groups are stateful: if a connection is allowed in, its response is automatically allowed. They allow traffic; they do not provide deny rules.

ServiceProtocol / portRecommended source
SSHTCP 22Your IP, a VPN, or a bastion security group
HTTPTCP 80Internet only when the website is public
HTTPSTCP 443Internet only when the website is public
ApplicationTCP 8080Load balancer security group
PostgreSQLTCP 5432Application security group
Never expose SSH or a database to 0.0.0.0/0 unless there is a specific, controlled reason. Prefer security-group references instead of fixed private IP addresses.

Network ACLs apply at the subnet level and are stateless. Return traffic must be allowed explicitly, including ephemeral ports. Use security groups as the normal instance-level control.

7. SSH and Session Manager

For SSH you need a running instance, a reachable address, the correct AMI username, private key, port 22 access, routes, and network ACL rules.

AMITypical username
Amazon Linuxec2-user
Ubuntuubuntu
Debianadmin or debian
CentOScentos
chmod 400 my-key.pem
ssh -i my-key.pem ubuntu@PUBLIC_IP

Through a bastion

ssh -i private-key.pem \
  -J ubuntu@BASTION_PUBLIC_IP \
  ubuntu@PRIVATE_EC2_IP

Session Manager

Systems Manager Session Manager provides shell access without a public IP, inbound SSH, or a bastion. The instance needs SSM Agent, an IAM role containing AmazonSSMManagedInstanceCore, and connectivity to Systems Manager endpoints.

aws ssm start-session --target i-0123456789abcdef0

8. Ports and port forwarding

Opening a port requires the application, security group, operating-system firewall, routes, and NACL to agree.

sudo ss -tulpn
sudo ss -tulpn | grep :8080
sudo systemctl status nginx

An application bound to 127.0.0.1 is local-only. To accept network traffic it normally must bind to 0.0.0.0 (and be secured appropriately).

Local forwarding to a private database

ssh -i bastion.pem \
  -L 15432:10.0.3.25:5432 \
  ec2-user@BASTION_PUBLIC_IP

# Connect locally
psql -h 127.0.0.1 -p 15432 -U appuser appdb
Your computer:15432
        |
   encrypted SSH tunnel
        v
Bastion host ----> Private database:5432

Session Manager forwarding

aws ssm start-session \
  --target i-0123456789abcdef0 \
  --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["8080"],"localPortNumber":["8080"]}'

9. IAM roles

An instance profile provides an IAM role whose temporary credentials are available to applications through instance metadata. This is safer than storing AWS access keys on the server.

EC2 instance
    |
    v
Instance profile -> IAM role -> Least-privilege policies -> AWS services

Example policy allowing reads from one S3 bucket:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["s3:GetObject"],
    "Resource": "arn:aws:s3:::example-bucket/*"
  }]
}

Use Secrets Manager or Systems Manager Parameter Store for secrets. Require IMDSv2:

aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-tokens required \
  --http-endpoint enabled

10. Storage

EBS is persistent block storage. Common types are gp3 for general use, io2 for high I/O, and st1/sc1 for HDD workloads.

Attach and mount a volume

lsblk
sudo mkfs -t xfs /dev/nvme1n1
sudo mkdir /data
sudo mount /dev/nvme1n1 /data
df -h
sudo blkid /dev/nvme1n1

Use the UUID in /etc/fstab for a persistent mount:

UUID=your-volume-uuid /data xfs defaults,nofail 0 2

EBS snapshots are point-in-time backups and can create new volumes or AMIs. Instance store is fast but ephemeral; do not use it as the only copy of important data.

11. Web-server demo

  1. Launch Ubuntu with a public IP.
  2. Allow TCP 22 from your IP and TCP 80 from the Internet.
  3. Connect:
ssh -i my-key.pem ubuntu@PUBLIC_IP

Install Nginx and create a page:

sudo apt update
sudo apt install -y nginx
echo '<h1>Hello from EC2</h1>' | sudo tee /var/www/html/index.html
sudo systemctl status nginx
curl http://localhost

Open http://PUBLIC_IP in a browser. If local curl works but the browser does not, check the security group, route, NACL, OS firewall, and public IP.

12. Production design

Users
  |
  v
Route 53
  |
  v
Application Load Balancer (public subnets)
  |
  +-------------------+
  |                   |
  v                   v
EC2 A (private)    EC2 B (private)
  |                   |
  +---------+---------+
            v
       Database (private)

Use an Auto Scaling group to maintain instances across Availability Zones. Use a launch template to define the AMI, instance type, security groups, IAM role, storage, and user data.

Typical security rules are: ALB allows 80/443 from users; EC2 allows the application port from the ALB security group; the database allows its port from the EC2 security group.

13. Monitoring, backup, and troubleshooting

Monitoring

CloudWatch provides CPU, network, disk I/O, and status checks. Install the CloudWatch Agent for memory, disk-space, process, and application-log metrics. Useful alarms include high CPU, low disk space, failed status checks, and increased application errors.

Backups

Use automated EBS snapshots, AMIs, application-level database backups, encryption, retention rules, and restoration tests. A backup is not reliable until restoration has been tested.

Common problems

SymptomCheck first
SSH timeoutInstance state, address, route, security group, NACL, and local network.
SSH permission deniedUsername, private key, key permissions, and selected key pair.
Connection refusedWhether the service is running and listening on the expected port.
Works on localhost onlyApplication binding; change from 127.0.0.1 to an appropriate network binding.
Public IP changedUse DNS, a load balancer, or an Elastic IP where truly necessary.

14. Final production checklist

Remember: A working EC2 service depends on five layers: compute, operating system, network, security, and storage/operations. Troubleshoot in that order when something fails.