☁️ Cloud

EC2

Elastic Compute Cloud

AWS's virtual server service. Various instance types. On-demand, spot, and reserved instances.

Detailed Explanation

Amazon EC2 (Elastic Compute Cloud) is AWS's core IaaS (Infrastructure as a Service) offering, which lets you provision and manage virtual servers in the cloud on demand. Launched in 2006 as one of the first AWS services, it has become the standard of cloud computing today.

EC2 instance types are divided by use case:

  • General Purpose (M/T families): Suitable for web servers and development environments. t3.micro is free under the Free Tier
  • Compute Optimized (C family): High-performance computing, batch processing
  • Memory Optimized (R/X families): In-memory databases, large-capacity caches
  • Storage Optimized (I/D families): High-speed I/O, data warehouses
  • Accelerated Computing (P/G families): GPU/ML workloads, graphics rendering

Pricing models are divided into On-Demand (hourly billing), Reserved Instances (1–3-year commitment, up to 72% discount), Spot Instances (bidding on unused capacity, up to 90% discount), and Savings Plans (flexible commitment).

Code Example

# EC2 인스턴스 생성 aws ec2 run-instances \ --image-id ami-0c55b159cbfafe1f0 \ --instance-type t3.micro \ --key-name my-key-pair \ --security-group-ids sg-903004f8 \ --subnet-id subnet-6e7f829e \ --count 1 \ --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=WebServer}]' # 인스턴스 상태 확인 aws ec2 describe-instances \ --filters "Name=tag:Name,Values=WebServer" \ --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]' # 인스턴스 중지/시작 aws ec2 stop-instances --instance-ids i-1234567890abcdef0 aws ec2 start-instances --instance-ids i-1234567890abcdef0 # 스팟 인스턴스 요청 (최대 90% 비용 절감) aws ec2 request-spot-instances \ --spot-price "0.03" \ --instance-count 1 \ --type "one-time" \ --launch-specification file://spot-spec.json
# Terraform EC2 인스턴스 구성 resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 instance_type = "t3.micro" # 프리 티어: t2.micro/t3.micro 월 750시간 무료 key_name = "my-key-pair" vpc_security_group_ids = [aws_security_group.web_sg.id] subnet_id = aws_subnet.public.id # EBS 루트 볼륨 설정 root_block_device { volume_type = "gp3" # 최신 SSD 타입 volume_size = 20 # GB delete_on_termination = true encrypted = true } # 사용자 데이터 (인스턴스 시작 시 실행) user_data = <<-EOF #!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd echo "Hello from EC2" > /var/www/html/index.html EOF tags = { Name = "web-server" Environment = "production" } } # Auto Scaling Group (고가용성) resource "aws_autoscaling_group" "web_asg" { desired_capacity = 2 max_size = 10 min_size = 2 vpc_zone_identifier = [aws_subnet.az1.id, aws_subnet.az2.id] target_group_arns = [aws_lb_target_group.web.arn] launch_template { id = aws_launch_template.web.id version = "$Latest" } tag { key = "Name" value = "web-asg" propagate_at_launch = true } }
import boto3 from botocore.exceptions import ClientError # EC2 클라이언트 생성 ec2 = boto3.client('ec2', region_name='ap-northeast-2') ec2_resource = boto3.resource('ec2', region_name='ap-northeast-2') def create_instance(name: str, instance_type: str = 't3.micro'): """EC2 인스턴스 생성""" instances = ec2_resource.create_instances( ImageId='ami-0c55b159cbfafe1f0', # Amazon Linux 2 InstanceType=instance_type, MinCount=1, MaxCount=1, KeyName='my-key-pair', SecurityGroupIds=['sg-903004f8'], TagSpecifications=[{ 'ResourceType': 'instance', 'Tags': [{'Key': 'Name', 'Value': name}] }], # IMDSv2 필수 (보안 권장) MetadataOptions={ 'HttpTokens': 'required', 'HttpEndpoint': 'enabled' } ) instance = instances[0] instance.wait_until_running() instance.reload() print(f"인스턴스 생성: {instance.id}") print(f"Public IP: {instance.public_ip_address}") return instance def get_spot_price(instance_type: str): """스팟 인스턴스 현재 가격 조회""" response = ec2.describe_spot_price_history( InstanceTypes=[instance_type], ProductDescriptions=['Linux/UNIX'], MaxResults=5 ) for price in response['SpotPriceHistory']: print(f"AZ: {price['AvailabilityZone']}, " f"가격: ${price['SpotPrice']}/시간") def list_running_instances(): """실행 중인 인스턴스 목록""" response = ec2.describe_instances( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) for reservation in response['Reservations']: for instance in reservation['Instances']: name = next( (t['Value'] for t in instance.get('Tags', []) if t['Key'] == 'Name'), 'N/A' ) print(f"{instance['InstanceId']}: {name} " f"({instance['InstanceType']}) - " f"{instance.get('PublicIpAddress', 'No Public IP')}") # 사용 예시 if __name__ == "__main__": # instance = create_instance("my-web-server") get_spot_price('t3.medium') # 스팟 가격 확인 list_running_instances()

Practical Conversation Example

Cost Optimization Meeting
"Our EC2 cost is 5 million KRW per month. How can we reduce it?" "Right now we're running On-Demand 24 hours a day, but if you switch production servers to 1-year Reserved Instances, you'll save 40%. Development servers can save 70% if you run them only during business hours, and CI/CD builds can be cut by up to 90% with Spot Instances. Please also look into Savings Plans."
Architecture Review
"We're running the service on a single t3.micro instance. Will that be a problem?" "It's fine for now, but it becomes a SPOF (single point of failure). Place at least 2 instances behind an ALB in an Auto Scaling Group, distributed across AZs. A t3.micro slows down once its burst credits run out, so as traffic grows you'll need to move up to t3.small or larger."
Security Review
"Could you give me an EC2 security configuration checklist?" "First, remove the fully open port 22 (0.0.0.0/0) in the Security Group and use a VPN or Session Manager. Second, require IMDSv2 to defend against SSRF attacks. Third, enable EBS encryption, and grant the IAM Role only the minimum necessary permissions."
Interview Question
"When do you use Spot Instances?" "Spot means using AWS's unused capacity at a discounted price, and since a 2-minute termination notice can arrive, it's suitable for stateless workloads. Use it for batch processing, CI/CD builds, big data analysis, and ML training, and if you implement a strategy to switch to a different instance type when a Spot interruption occurs, you can use it reliably."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Cautions

⚠️
Instance store data loss: Instance store (ephemeral storage) data is deleted when the instance is terminated. Always store persistent data on EBS or S3.
⚠️
Elastic IP charges: It is free for a running instance it is attached to, but an Elastic IP that is not attached is billed at $0.005 per hour. Release it if you are not using it.
⚠️
T-family burst credits: t2/t3 instances are based on CPU credits. When credits run out, performance is limited to the baseline (10% for t3.micro). For sustained high-load workloads, use the M/C families.
⚠️
Public IP changes: The Public IP changes when an instance is restarted. If you need a fixed IP, allocate an Elastic IP or use a combination of Route 53 + Private DNS.

Related Terms

Learn More