Auto Scaling Group(ASG)

도은호·2025년 10월 7일
0

AWS SAA

목록 보기
21/46

ASG는 EC2 용량을 자동으로 늘리고 줄이며(스케일링), 고가용성을 유지. 핵심은 Launch Template, Min/Max/Desired, Health Check, Scaling Policy 네 가지 축


1) 핵심 개념 요약

  • Launch Template(권장): AMI/Instance Type/Security Group/UserData 등 인스턴스 청사진.
  • Min / Max / Desired: 그룹의 최소/최대/목표 인스턴스 수.
  • Subnet(여러 AZ): 다중 AZ 분산으로 내결함성↑.
  • Health Check: EC2 또는 ELB 기준으로 비정상 인스턴스 자동 교체(+ Grace Period).
  • Scaling Policy: Target Tracking(권장), Step/Simple, Scheduled, Predictive.
  • 운영 필수 옵션: Instance Refresh, Mixed Instances Policy, Capacity Rebalance(Spot), Lifecycle Hooks, Warm Pools, Scale-In Protection.

2) 구성요소 & 동작 흐름

  1. Launch Template로 인스턴스 정의
  2. ASGDesired 수를 맞추도록 인스턴스 생성(다중 AZ 분산)
  3. Target Group(ELB) 에 자동 등록 → Health Check 실패 시 교체
  4. Scaling PolicyCloudWatch 지표로 자동 증감
Client → ALB/NLB → Target Group ↔ ASG(EC2들)

3) 스케일링 정책⭐⭐⭐

3-1. Target Tracking (가장 단순/권장)

  • 목표 지표를 자동 추종: 예) CPUUtilization = 50%, ALB RequestCountPerTarget = 100.
  • Instance Warmup(예: 60–300s)으로 새 인스턴스 안정화 시간 반영 → 진동(핑퐁) 감소.

3-2. Step / Simple Scaling

  • 임계 초과 정도에 따라 단계적 증감(Step) 또는 쿨다운 기반 단순 증감(Simple).
  • 쿨다운(default cooldown) 설정을 세밀히 잡아야 함.

3-3. Scheduled / Predictive

  • Scheduled: “매일 09:00에 Desired=20” 같은 예약 증감.
  • Predictive: 과거 패턴 기반 예측 스케일 아웃(변동 패턴이 뚜렷할 때 유리).

4) 고급 운영 기능

  • Instance Refresh: 롤링 방식으로 Launch Template 변경분(AMI 패치, 커널 교체 등) 무중단 교체.

    • 파라미터: MinHealthyPercentage, Warmup 등.
  • Mixed Instances Policy: 여러 Instance Type을 섞고 On-Demand/Spot 비율을 정의.

    • 전략: OnDemandBaseCapacity, OnDemandPercentageAboveBaseCapacity, Spot Allocation Strategy(capacity-optimized 권장).
  • Capacity Rebalance(Spot): Spot 회수 신호 감지 시 미리 보충 → 중단 내성↑.

  • Lifecycle Hooks: Launching/Terminating 단계에서 초기화/드레인 스크립트 실행(예: ALB Deregistration Delay 이후 종료).

  • Warm Pools: 미리 예열된 인스턴스를 풀에 보관(Stopped/Running) → 급격한 스케일 아웃 지연 감소.

  • Scale-In Protection & Standby: 특정 인스턴스를 축소에서 보호하거나, Standby로 빼서 유지보수.


5) 헬스·가용성 설계 포인트

  • ELB Health Check 사용 시 실제 서비스 기준으로 교체가 정확.
  • Health Check Grace Period(예: 300s)로 부팅/앱 기동 시간을 반영.
  • AZ 균형: ASG는 AZ별 균형을 유지하려고 함(Subnet 다중 지정 권장).
  • Max Instance Lifetime로 오래된 인스턴스를 주기적으로 교체해 드리프트 최소화.

6) 배포/무중단 운영 팁

  • ALB Weighted Target Group + 두 개 ASG로 Blue/Green/Canary(점진 전환·롤백 쉬움).
  • Deregistration Delay(기본 300s) + 앱 /healthz로 부드러운 교체.
  • Stateless하게 설계하고, 세션은 외부 스토어(ElastiCache/DynamoDB) 사용 → Stickiness 의존도↓.

7) 관측(CloudWatch) & 알람

  • 그룹 지표: GroupDesiredCapacity, GroupInServiceInstances, GroupTotalInstances.
  • 스케일 지표 예시: CPUUtilization, RequestCountPerTarget, TargetResponseTime, SQS ApproximateNumberOfMessagesVisible.
  • 경보: 스케일 아웃/인 트리거, 비정상 증가(5xx), 헬스 급감.

8) 트러블슈팅 체크리스트

  • 인스턴스가 바로 종료: Health Check 실패(포트/SG/NACL/Target Group 경로 확인) or UserData 오류.
  • 스케일 인 과도: Target Tracking의 목표/워밍업 재조정, Scale-In Protection 일부 적용.
  • 용량 미확보(Insufficient Capacity): Instance Type 다변화(Mixed Instances), 인접 AZ/리전 고려.
  • 배포가 느림: Instance Refresh 설정(분할 비율↑, Warmup↓), 드레인 시간 최적화.

9) 필수 CLI 스니펫

# (1) Launch Template 생성
aws ec2 create-launch-template \
  --launch-template-name lt-web \
  --launch-template-data '{
    "ImageId":"ami-xxxxxxxx",
    "InstanceType":"t3.medium",
    "SecurityGroupIds":["sg-xxxx"],
    "UserData":"'"$(base64 -w0 userdata.sh)"'"
  }'

# (2) ASG 생성 (다중 AZ, TG 연결)
aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name asg-web \
  --launch-template LaunchTemplateName=lt-web,Version='$Latest' \
  --min-size 2 --max-size 20 --desired-capacity 4 \
  --vpc-zone-identifier "subnet-azA,subnet-azB" \
  --target-group-arns arn:aws:elasticloadbalancing:...:targetgroup/tg-web/...

# (3) Target Tracking 정책 (CPU 50%)
aws autoscaling put-scaling-policy \
  --auto-scaling-group-name asg-web \
  --policy-name cpu50-tt \
  --policy-type TargetTrackingScaling \
  --target-tracking-configuration '{
    "PredefinedMetricSpecification":{"PredefinedMetricType":"ASGAverageCPUUtilization"},
    "TargetValue":50.0,
    "DisableScaleIn":false
  }'

# (4) Instance Refresh 시작 (롤링 교체)
aws autoscaling start-instance-refresh \
  --auto-scaling-group-name asg-web \
  --preferences MinHealthyPercentage=90,InstanceWarmup=120 \
  --strategy Rolling

# (5) Mixed Instances (요약 설정 예)
aws autoscaling update-auto-scaling-group \
  --auto-scaling-group-name asg-web \
  --mixed-instances-policy '{
    "LaunchTemplate":{
      "LaunchTemplateSpecification":{"LaunchTemplateName":"lt-web","Version":"$Latest"},
      "Overrides":[{"InstanceType":"t3.medium"},{"InstanceType":"t3.large"}]
    },
    "InstancesDistribution":{
      "OnDemandBaseCapacity":2,
      "OnDemandPercentageAboveBaseCapacity":50,
      "SpotAllocationStrategy":"capacity-optimized"
    }
  }'

10) CloudFormation 예시

Resources:
  LT:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateData:
        ImageId: ami-xxxxxxxx
        InstanceType: t3.medium
        SecurityGroupIds: [sg-xxxx]
        UserData: {{ base64 of userdata }}

  ASG:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      VPCZoneIdentifier: [subnet-azA, subnet-azB]
      MinSize: '2'
      MaxSize: '20'
      DesiredCapacity: '4'
      LaunchTemplate:
        LaunchTemplateName: !Ref LT
        Version: $Latest
      TargetGroupARNs: [arn:aws:elasticloadbalancing:...:targetgroup/tg-web/...]
      HealthCheckType: ELB
      HealthCheckGracePeriod: 300

  CpuPolicy:
    Type: AWS::AutoScaling::ScalingPolicy
    Properties:
      AutoScalingGroupName: !Ref ASG
      PolicyType: TargetTrackingScaling
      TargetTrackingConfiguration:
        PredefinedMetricSpecification:
          PredefinedMetricType: ASGAverageCPUUtilization
        TargetValue: 50

11) 시험/실무 포인트

  • Target Tracking + Instance Warmup = 기본값처럼 기억.
  • ELB Health Check + Deregistration Delay무중단 교체.
  • Mixed Instances + capacity-optimized Spot = 안정적인 비용 절감.
  • Instance Refresh골든 AMI 롤링.
  • Capacity Rebalance로 Spot 회수 내성↑.
  • Lifecycle Hooks / Warm Pools / Scale-In Protection은 고급 운영에 필수.

요약

  • ASG = 용량 자동화 + 고가용성의 핵심.
  • Target Tracking으로 자연스러운 스케일링, Instance Refresh로 안전 배포.
  • Mixed Instances/Capacity Rebalance/Warm Pools비용·속도·안정성을 동시에!
profile
`•.¸¸.•´´¯`••._.• 🎀 𝒸𝓇𝒶𝓏𝓎 𝓅𝓈𝓎𝒸𝒽💞𝓅𝒶𝓉𝒽 🎀 •._.••`¯´´•.¸¸.•`

0개의 댓글