☁️ Cloud

Instance

Instance

A cloud virtual server. EC2 instance, Compute Engine instance.

📖 Detailed Explanation

Instance is a virtual server that runs in a cloud environment. It is called an EC2 instance on AWS, a Compute Engine instance on GCP, and a Virtual Machine on Azure. It virtualizes the resources of a physical server so that you are allocated and use as much CPU, memory, and storage as you need.

Instance types vary according to workload characteristics. General Purpose offers balanced computing and suits web servers, while Compute Optimized is used for batch processing that requires high CPU performance. Memory Optimized suits in-memory databases, and GPU instances suit AI/ML training.

Pricing models are also important. On-Demand means you pay only for what you use and offers high flexibility. Reserved Instances can receive discounts of up to 72% with a 1-3 year commitment. Spot Instances use spare capacity at prices discounted by up to 90%, but they can be reclaimed at any time. Savings Plans are a flexible model that offers discounts in exchange for committing to a certain amount of usage per hour.

In actual operations, it is used together with Auto Scaling to automatically adjust the number of instances according to traffic. In addition, information about a running instance can be queried through the Instance Metadata Service (IMDS), and this is used to build automation scripts.

💻 Code Example

# EC2 인스턴스 생성 - 웹 서버용 t3.medium
aws ec2 run-instances \
    --image-id ami-0c55b159cbfafe1f0 \
    --instance-type t3.medium \
    --key-name my-key-pair \
    --security-group-ids sg-0123456789abcdef0 \
    --subnet-id subnet-0123456789abcdef0 \
    --iam-instance-profile Name=WebServerRole \
    --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-server-01},{Key=Environment,Value=production}]' \
    --user-data file://setup-web.sh \
    --count 1

# 인스턴스 상태 확인
aws ec2 describe-instances \
    --instance-ids i-0123456789abcdef0 \
    --query 'Reservations[].Instances[].{ID:InstanceId,State:State.Name,Type:InstanceType,IP:PublicIpAddress}'

# 스팟 인스턴스 요청 (최대 90% 비용 절감)
aws ec2 request-spot-instances \
    --instance-count 2 \
    --type "one-time" \
    --launch-specification '{
        "ImageId": "ami-0c55b159cbfafe1f0",
        "InstanceType": "c5.xlarge",
        "KeyName": "my-key-pair",
        "SecurityGroupIds": ["sg-0123456789abcdef0"]
    }' \
    --spot-price "0.05"

# 인스턴스 타입 변경 (먼저 중지 필요)
aws ec2 stop-instances --instance-ids i-0123456789abcdef0
aws ec2 modify-instance-attribute \
    --instance-id i-0123456789abcdef0 \
    --instance-type "{\"Value\": \"t3.large\"}"
aws ec2 start-instances --instance-ids i-0123456789abcdef0
# Compute Engine 인스턴스 생성
gcloud compute instances create web-server-01 \
    --project=my-project \
    --zone=asia-northeast3-a \
    --machine-type=e2-medium \
    --network-interface=network-tier=PREMIUM,subnet=default \
    --maintenance-policy=MIGRATE \
    --service-account=123456789-compute@developer.gserviceaccount.com \
    --scopes=https://www.googleapis.com/auth/cloud-platform \
    --tags=http-server,https-server \
    --create-disk=auto-delete=yes,boot=yes,device-name=web-server-01,image=projects/debian-cloud/global/images/debian-11-bullseye-v20240213,mode=rw,size=50,type=projects/my-project/zones/asia-northeast3-a/diskTypes/pd-balanced \
    --labels=env=production,team=backend \
    --metadata-from-file=startup-script=setup-web.sh

# 프리엠터블 인스턴스 (최대 80% 할인, 24시간 제한)
gcloud compute instances create batch-worker \
    --zone=asia-northeast3-a \
    --machine-type=n2-standard-4 \
    --preemptible \
    --no-restart-on-failure \
    --maintenance-policy=TERMINATE

# 인스턴스 목록 및 상태 확인
gcloud compute instances list \
    --filter="zone:asia-northeast3-a" \
    --format="table(name,zone,machineType,status,networkInterfaces[0].accessConfigs[0].natIP)"

# 머신 타입 변경
gcloud compute instances stop web-server-01 --zone=asia-northeast3-a
gcloud compute instances set-machine-type web-server-01 \
    --zone=asia-northeast3-a \
    --machine-type=e2-standard-4
gcloud compute instances start web-server-01 --zone=asia-northeast3-a

# 스냅샷 생성 (백업)
gcloud compute disks snapshot web-server-01 \
    --zone=asia-northeast3-a \
    --snapshot-names=web-server-backup-$(date +%Y%m%d)
# AWS EC2 인스턴스 + Auto Scaling 구성
# variables.tf
variable "environment" {
  default = "production"
}

variable "instance_type" {
  default = "t3.medium"
}

# main.tf - Launch Template
resource "aws_launch_template" "web" {
  name_prefix   = "web-server-"
  image_id      = data.aws_ami.amazon_linux.id
  instance_type = var.instance_type

  iam_instance_profile {
    name = aws_iam_instance_profile.web.name
  }

  network_interfaces {
    associate_public_ip_address = true
    security_groups             = [aws_security_group.web.id]
  }

  monitoring {
    enabled = true
  }

  user_data = base64encode(templatefile("${path.module}/user-data.sh", {
    environment = var.environment
  }))

  tag_specifications {
    resource_type = "instance"
    tags = {
      Name        = "web-server"
      Environment = var.environment
    }
  }

  # 스팟 인스턴스 옵션 (비용 최적화)
  instance_market_options {
    market_type = "spot"
    spot_options {
      max_price                      = "0.05"
      spot_instance_type             = "one-time"
      instance_interruption_behavior = "terminate"
    }
  }
}

# Auto Scaling Group
resource "aws_autoscaling_group" "web" {
  name                = "web-asg"
  vpc_zone_identifier = data.aws_subnets.private.ids
  target_group_arns   = [aws_lb_target_group.web.arn]
  health_check_type   = "ELB"

  min_size         = 2
  max_size         = 10
  desired_capacity = 3

  mixed_instances_policy {
    launch_template {
      launch_template_specification {
        launch_template_id = aws_launch_template.web.id
        version            = "$Latest"
      }

      # 온디맨드 + 스팟 혼합 (비용 70% 절감)
      override {
        instance_type     = "t3.medium"
        weighted_capacity = "1"
      }
      override {
        instance_type     = "t3.large"
        weighted_capacity = "2"
      }
    }

    instances_distribution {
      on_demand_base_capacity                  = 1
      on_demand_percentage_above_base_capacity = 25
      spot_allocation_strategy                 = "capacity-optimized"
    }
  }

  instance_refresh {
    strategy = "Rolling"
    preferences {
      min_healthy_percentage = 75
    }
  }
}

💬 How It's Said in Practice

Cost Optimization Meeting

Team Lead: "This month's EC2 cost exceeded the budget by 40%. How can we reduce it?"

DevOps: "Currently all instances are running On-Demand, and according to the analysis, 70% of them run stably 24/7. If we switch that portion to Savings Plans, we can save 30%, and if we switch batch processing workloads to Spot Instances, we can save an additional 20%. If we configure On-Demand:Spot at a 25:75 ratio with an ASG mixed instance policy, we can significantly reduce costs while maintaining availability."

Interview Questions

Interviewer: "What criteria do you use when choosing an EC2 instance type?"

Candidate: "I analyze the workload characteristics first. If balanced resources are needed, like for a web server, I choose M series General Purpose instances, and for batch processing or video encoding, I choose C series Compute Optimized. For ML inference I use G series GPU instances, and for in-memory databases such as Redis I use R series Memory Optimized. In practice, I monitor CPU/memory utilization with CloudWatch metrics, and then adjust the instance type by referring to Right Sizing recommendations."

Incident Response

Developer: "The Spot Instance was suddenly terminated, and the data I was working on is gone."

SRE: "Spot Instances can receive a termination notice 2 minutes in advance. Set it up to poll instance-action from the EC2 metadata service, or to receive an SNS notification through an EventBridge rule. Also, you should save the job state as a checkpoint in S3 or DynamoDB, and apply a pattern where processing resumes when a new instance starts. Also set the SQS visibility timeout with some margin beyond the job duration."

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

⚠️ Cautions

❌

Storing Persistent Data on an Instance Store

Data on an instance store (ephemeral storage) is deleted when the instance is stopped or terminated. If you store logs or uploaded files here, they cannot be recovered when the instance fails. Use an EBS volume or S3.

❌

Using IMDS v1 and Not Configuring a Firewall

IMDSv1 is vulnerable to SSRF attacks. Be sure to allow only IMDSv2 (HttpTokens=required) and set the hop limit to 1. In container environments, also consider blocking access to 169.254.169.254 with iptables.

✅

Using an IAM Role via an Instance Profile

Do not store AWS access keys directly on an instance. Instead, if you attach an IAM role to an instance profile, temporary credentials are issued automatically. The SDK automatically retrieves the credentials from the metadata and uses them.

🔗 Related Terms

📚 Learn More