☁️ 클라우드

EC2

Elastic Compute Cloud

AWS 가상 서버 서비스. 다양한 인스턴스 타입. 온디맨드, 스팟, 예약 인스턴스.

상세 설명

Amazon EC2(Elastic Compute Cloud)는 AWS의 핵심 IaaS(Infrastructure as a Service) 서비스로, 클라우드에서 가상 서버를 온디맨드로 프로비저닝하고 관리할 수 있게 해줍니다. 2006년 AWS 최초 서비스 중 하나로 출시되어 현재 클라우드 컴퓨팅의 표준이 되었습니다.

EC2 인스턴스 타입은 용도에 따라 구분됩니다:

  • 범용(General Purpose, M/T 계열): 웹 서버, 개발 환경에 적합. t3.micro는 프리 티어 무료
  • 컴퓨팅 최적화(Compute Optimized, C 계열): 고성능 컴퓨팅, 배치 처리
  • 메모리 최적화(Memory Optimized, R/X 계열): 인메모리 DB, 대용량 캐시
  • 스토리지 최적화(Storage Optimized, I/D 계열): 고속 I/O, 데이터 웨어하우스
  • 가속 컴퓨팅(Accelerated Computing, P/G 계열): GPU/ML 워크로드, 그래픽 렌더링

요금제는 온디맨드(시간당 과금), 예약 인스턴스(1-3년 약정, 최대 72% 할인), 스팟 인스턴스(미사용 용량 입찰, 최대 90% 할인), Savings Plans(유연한 약정)으로 나뉩니다.

코드 예제

# 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()

실무 대화 예시

비용 최적화 회의
"EC2 비용이 월 500만원인데 어떻게 줄일 수 있을까요?" "현재 온디맨드로 24시간 돌리고 있는데, 운영 서버는 1년 예약 인스턴스로 전환하면 40% 절감됩니다. 개발 서버는 업무 시간만 실행하면 70% 절감 가능하고, CI/CD 빌드는 스팟 인스턴스로 90%까지 줄일 수 있어요. Savings Plans도 검토해 보세요."
아키텍처 리뷰
"t3.micro 단일 인스턴스로 서비스 중인데 문제없을까요?" "당장은 괜찮지만 SPOF(단일 장애점)가 됩니다. ALB 뒤에 Auto Scaling Group으로 최소 2개 인스턴스를 AZ 분산 배치하세요. t3.micro는 버스트 크레딧 소진되면 느려지니까 트래픽 늘면 t3.small 이상으로 올려야 합니다."
보안 점검
"EC2 보안 설정 체크리스트 알려주세요." "첫째, Security Group에서 22번 포트 전체 오픈(0.0.0.0/0) 제거하고 VPN이나 Session Manager 사용하세요. 둘째, IMDSv2 필수로 설정해서 SSRF 공격 방어하세요. 셋째, EBS 암호화 활성화하고, IAM Role은 최소 권한만 부여하세요."
면접 질문
"스팟 인스턴스는 언제 사용하나요?" "스팟은 AWS 미사용 용량을 할인된 가격에 사용하는 건데, 2분 전 종료 알림이 올 수 있어서 Stateless 워크로드에 적합합니다. 배치 처리, CI/CD 빌드, 빅데이터 분석, ML 학습에 활용하고, 스팟 중단 시 다른 인스턴스 타입으로 전환하는 전략을 구현하면 안정적으로 사용할 수 있습니다."

주의사항

⚠️
인스턴스 스토어 데이터 손실: 인스턴스 스토어(ephemeral storage)는 인스턴스 종료 시 데이터가 삭제됩니다. 영구 데이터는 반드시 EBS 또는 S3에 저장하세요.
⚠️
Elastic IP 요금: 연결된 실행 중인 인스턴스에는 무료지만, 연결 안 된 Elastic IP는 시간당 $0.005 과금됩니다. 사용 안 하면 해제하세요.
⚠️
t 계열 버스트 크레딧: t2/t3 인스턴스는 CPU 크레딧 기반입니다. 크레딧 소진 시 베이스라인(t3.micro는 10%)으로 성능이 제한됩니다. 지속적 고부하 워크로드는 M/C 계열 사용하세요.
⚠️
Public IP 변경: 인스턴스 재시작 시 Public IP가 변경됩니다. 고정 IP가 필요하면 Elastic IP를 할당하거나, Route 53 + Private DNS 조합을 사용하세요.

관련 용어

더 배우기