Compute: virtual machines, containers & serverless
The AWS chapter listed the compute services by job. This chapter gets hands-on: how to pick and launch an EC2 virtual machine and log in to it, what happens when you stop or terminate it, how containers run on ECS and EKS, and what a Lambda function looks like in practice, with its limits and cold starts.
Reading an EC2 instance type
An instance type decides the CPU, memory, network and storage your VM gets. The name is a code:
t3.micro t = family (burstable general purpose) 3 = generation micro = size
m7g.xlarge m = family (general purpose) 7 = generation g = Graviton (ARM) CPU xlarge = size
c7i.2xlarge c = compute optimised 7 = generation i = Intel CPU 2xlarge = size
Extra letters after the generation describe the variant: g AWS Graviton (ARM), a AMD, i Intel, d local NVMe instance-store disks, n extra network bandwidth, e extra memory or storage. Sizes go nano, micro, small, medium, large, xlarge, 2xlarge and up; from large upward each step roughly doubles CPU and memory, and the price with it. A newer generation is usually faster for the money, so prefer it when the choice is free.
- General purpose (M, T): web servers, small apps, dev machines. T types are "burstable": a low baseline CPU plus credits to burst above it.
- Compute optimised (C): CPU-heavy work such as CI builds and batch jobs.
- Memory optimised (R, X): databases and in-memory caches.
- Storage optimised (I, D): very fast local disks. Accelerated (P, G, Inf, Trn): GPUs and ML chips.
T3 and newer burstable types start in unlimited mode by default: if the CPU stays above the baseline for a long time you pay extra instead of being slowed down. A burstable instance running at 100% all day is a sign you want an M or C type.
The pieces of an EC2 instance
- AMI (Amazon Machine Image): the template the root disk is created from: operating system plus anything pre-installed. AMI IDs (
ami-…) are different in every region, and the AMI's CPU architecture (x86_64 or arm64) must match the instance type. - Key pair: AWS puts the public key on the instance; you keep the private key (
.pem), which you can download only once. The login user depends on the AMI:ec2-useron Amazon Linux,ubuntuon Ubuntu,adminon Debian. - Security group: the instance's stateful firewall. A new one allows no inbound traffic and all outbound. Open only what you need, and SSH only from your own IP.
- User data: a script that cloud-init runs as root on the first boot only, perfect for installing packages. It must start with a shebang like
#!/bin/bash; its output goes to/var/log/cloud-init-output.log. - EBS root volume: the network disk holding the OS, usually gp3 (general-purpose SSD). Its size and type are chosen at launch and can be increased later. Some types also have instance store: fast local disks whose data is lost when the instance stops.
Launching from the console
- Pick your region (top right), open EC2 → Instances → Launch instances, give it a name.
- Choose an AMI (Amazon Linux 2023 or Ubuntu Server LTS) and a type such as
t3.micro; the console marks types that are free-tier eligible for your account. - Create a key pair (ED25519) and save the
.pem. Under Network settings, keep the default VPC with "Auto-assign public IP" enabled, and allow SSH from My IP (plus HTTP for a web server). - Check the storage, optionally paste a script into Advanced details → User data, and click Launch instance.
The same launch with the AWS CLI
# 1. Key pair: the private key is printed once, so save it straight to a file
$ aws ec2 create-key-pair --key-name practice-key --key-type ed25519 \
--query 'KeyMaterial' --output text > practice-key.pem
$ chmod 400 practice-key.pem # ssh refuses keys that others can read
# 2. Security group in the default VPC: SSH from my IP only, HTTP from anywhere
$ aws ec2 create-security-group --group-name web-sg \
--description "SSH from my IP, HTTP from anywhere" --query 'GroupId' --output text
sg-0123456789abcdef0
$ aws ec2 authorize-security-group-ingress --group-id sg-0123456789abcdef0 \
--protocol tcp --port 22 --cidr 203.0.113.25/32
$ aws ec2 authorize-security-group-ingress --group-id sg-0123456789abcdef0 \
--protocol tcp --port 80 --cidr 0.0.0.0/0
# 3. user-data.sh (runs once, as root, on first boot)
#!/bin/bash
dnf install -y nginx
systemctl enable --now nginx
# 4. Launch. resolve:ssm: looks up the latest Amazon Linux 2023 AMI ID for this region
$ aws ec2 run-instances \
--image-id resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
--instance-type t3.micro \
--count 1 \
--key-name practice-key \
--security-group-ids sg-0123456789abcdef0 \
--user-data file://user-data.sh \
--metadata-options HttpTokens=required \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-01},{Key=Project,Value=practice}]' \
--query 'Instances[0].InstanceId' --output text
i-0abc1234def567890
# 5. Wait, find the public IP, connect
$ aws ec2 wait instance-running --instance-ids i-0abc1234def567890
$ aws ec2 describe-instances --instance-ids i-0abc1234def567890 \
--query 'Reservations[0].Instances[0].PublicIpAddress' --output text
198.51.100.7
$ ssh -i practice-key.pem [email protected]
$ curl http://198.51.100.7 # nginx welcome page once user data has finished
HttpTokens=required forces IMDSv2, the safer version of the instance metadata service that hands out the role's credentials. Without --subnet-id, the instance goes into a default subnet of the default VPC, which gives it a public IP. Instead of SSH you can use EC2 Instance Connect or Session Manager in the console; Session Manager needs no open port 22 at all, just the SSM agent (preinstalled on Amazon Linux) and an instance role with the AmazonSSMManagedInstanceCore policy.
Stop, terminate and Elastic IPs
| Stop | Terminate | |
|---|---|---|
| What happens | The VM is shut down but kept; start it again any time | The VM is deleted permanently |
| Compute charges | None while stopped | None |
| EBS volumes | Kept, and still billed | Root volume deleted by default; volumes attached later are kept by default (and still billed) |
| Public IPv4 | Released; a new one is given on start | Released |
| Instance store data | Lost | Lost |
The CLI equivalents are aws ec2 stop-instances, start-instances and terminate-instances, each with --instance-ids. Launch with --disable-api-termination (termination protection) for instances that must never be deleted by accident. An Elastic IP is a static public IPv4 address that stays in your account until you release it, so a server keeps the same address across stops:
$ aws ec2 allocate-address --domain vpc --query 'AllocationId' --output text
eipalloc-0a1b2c3d4e5f67890
$ aws ec2 associate-address --instance-id i-0abc1234def567890 --allocation-id eipalloc-0a1b2c3d4e5f67890
$ aws ec2 release-address --allocation-id eipalloc-0a1b2c3d4e5f67890 # when you no longer need it
AWS charges by the hour for every public IPv4 address, attached or idle, so release Elastic IPs you don't use. For real websites, a load balancer or DNS name in front of the servers usually beats pinning one IP.
Containers on AWS: ECR, ECS and EKS
Images live in ECR (Elastic Container Registry), which works like any registry after a login:
$ aws ecr create-repository --repository-name practice-app
$ aws ecr get-login-password --region eu-central-1 | docker login --username AWS \
--password-stdin 123456789012.dkr.ecr.eu-central-1.amazonaws.com
$ docker tag practice-app:1.0 123456789012.dkr.ecr.eu-central-1.amazonaws.com/practice-app:1.0
$ docker push 123456789012.dkr.ecr.eu-central-1.amazonaws.com/practice-app:1.0
To run them, AWS offers two orchestrators:
- ECS (Elastic Container Service): AWS's own, simpler orchestrator. A task definition (JSON) describes the containers: image, CPU and memory, ports, environment variables, log settings and an IAM task role. A task is a running copy; a service keeps N tasks running behind a load balancer and does rolling deployments.
- EKS (Elastic Kubernetes Service): real Kubernetes with AWS running the control plane. You use
kubectland everything from the Kubernetes topic; it's portable, but there's an hourly charge per cluster on top of the worker capacity, and more to learn.
Both need somewhere for the containers to run:
- Fargate: serverless. You set CPU and memory per task and AWS supplies the machine, with no instances to patch or scale; you pay per second for what each task requests, and can't reach the host.
- EC2 launch type: containers run on EC2 instances you manage (usually in an Auto Scaling group). More work, more control (GPUs, special types, per-host daemons), often cheaper for large steady workloads.
- ECS Managed Instances (launched in 2025) sits in between: EC2 instances in your account that AWS provisions, patches and scales for you. On EKS, Auto Mode plays a similar role.
Lambda in practice
A Lambda function is code plus a handler, the function Lambda calls for each event:
# lambda_function.py
import json
def lambda_handler(event, context):
name = event.get("name", "world")
return {"statusCode": 200, "body": json.dumps({"message": f"Hello, {name}!"})}
$ zip function.zip lambda_function.py
$ aws lambda create-function --function-name hello \
--runtime python3.13 --handler lambda_function.lambda_handler \
--zip-file fileb://function.zip \
--role arn:aws:iam::123456789012:role/hello-lambda-role \
--timeout 10 --memory-size 256
$ aws lambda invoke --function-name hello \
--cli-binary-format raw-in-base64-out --payload '{"name": "Demee"}' response.json
$ cat response.json
{"statusCode": 200, "body": "{\"message\": \"Hello, Demee!\"}"}
The handler setting is file_name.function_name. The execution role must at least allow writing logs (the AWS managed policy AWSLambdaBasicExecutionRole); output from print goes to CloudWatch Logs in the log group /aws/lambda/hello. A trigger decides what calls the function: an HTTP request through API Gateway or a function URL, a file landing in S3, a message on an SQS queue, a schedule in EventBridge Scheduler, a change in a DynamoDB table.
Limits worth knowing (check the Lambda quotas page, they change): the timeout defaults to 3 seconds and can be raised to at most 15 minutes (900 seconds); memory is set from 128 MB to 10,240 MB, and CPU power grows in proportion to it, so more memory often makes a function faster; /tmp gives 512 MB of scratch space by default, configurable up to 10,240 MB. New accounts start with lower concurrency and memory quotas that AWS raises with usage. You pay per request and per GB-second of run time.
A cold start happens when Lambda must create a new execution environment: download your code, start the runtime and run the code outside the handler. It adds latency to that one request; later requests reuse the warm environment. To reduce it: keep the package and its dependencies small, create clients (database connections, SDK clients) outside the handler so warm calls reuse them, and for latency-sensitive functions use provisioned concurrency (paid, pre-warmed environments) or SnapStart (available for Java, Python and .NET).
Which one to pick
| Option | Pick it when | Watch out for |
|---|---|---|
| EC2 | You need full control of the OS, run legacy or stateful software, or are learning Linux servers | You patch, secure, back up and scale it yourself |
| ECS on Fargate | You have containers and want the least operations work | Per-task pricing adds up for large steady fleets; no host access |
| EKS | Your team already runs Kubernetes, or needs its ecosystem and portability | Cluster fee, and Kubernetes' complexity |
| Lambda | Short, event-driven tasks, spiky or low traffic, glue between services | 15-minute limit, cold starts, harder local testing, cost at very high steady volume |
Common errors and fixes
- SSH hangs, then "Connection timed out": the security group doesn't allow port 22 from your current IP (it changes on home and mobile networks), or the instance has no public IP or its subnet has no route to an internet gateway.
- "Permission denied (publickey)": wrong user name for the AMI, or the wrong key. "UNPROTECTED PRIVATE KEY FILE!": run
chmod 400on the.pem. - User data did nothing: missing
#!/bin/bashfirst line, or you edited it after the first boot (it only runs once). Read/var/log/cloud-init-output.log. - An error that the instance type's architecture doesn't match the AMI's: an x86_64 AMI on a Graviton (
g) type or the reverse. Use thearm64AMI for Graviton. VcpuLimitExceeded: new accounts have low vCPU quotas. Use a smaller type or request an increase in Service Quotas.- Lambda "Task timed out after 3.00 seconds": the default timeout is 3 seconds; raise it with
aws lambda update-function-configuration --function-name hello --timeout 30, and check the function isn't waiting on a network call that can never succeed (for example a function in a private subnet with no NAT).