본문 바로가기

Container/Kubernetes

[K8S] Autoscaling - HPA

Manually scale기존의 Manual Scaling  방식은 실시간으로 리소스 사용량을 모니터링해야하고, 스케일 업/다운을 위해 매뉴얼로 명령을 실행해야 한다. 하지만 이는 트래픽 급증에 빠르게 대응하지 못할 가능성이 존재한다.

이를 해결하기 위해 AutoScaling을 사용하기 시작했다.

# kubectl scale 명령어
$ kubectl scale deployment my-app --replicas=3
  • kubectl scale 명령어는 Deployment와 Statefulset을 모두 scaling하는 데 사용할 수 있다. 

 

🍀 AutoScaling

AutoScaling은 클러스터의 리소스 사용량과 트래픽 변화에 따라 자동으로 Pod 또는 노드를 확장하거나 축소하는 기능이다. 

 

Horizontal Pod Autoscaler (HPA)

Metrics를 지속적으로 모니터링하고 CPU, 메모리 등  리소스 사용량 변화에 대응하여 Pod 개수를 동적으로 조절한다.

  • 💡 트래픽 증가 → Pod 추가 / 트래픽 감소 → Pod 감소
  • v1.23부터 kubernetes에 built-in되며, Metrics Server에 의존적이다.
  • HPA는 크기 조절이 불가능한 오브젝트(ex: DaemonSet)에는 적용할 수 없다.

HorizontalPodAutoscaler

$ kubectl autoscale deployment my-app --cpu-percent=50 --min=2 --max=10

 

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: my-app-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-app
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50

 

[ 실습 ] resources.limit 가 지정되지 않았을 때 상황

 

1. maximum of 3 replicas 과 CPU utilization target of 80% 조건의  autoscaler 만들기

controlplane ~ ➜  kubectl autoscale deploy nginx-deployment --max=3 --cpu-percent=80
horizontalpodautoscaler.autoscaling/nginx-deployment autoscaled

controlplane ~ ➜  kubectl get deploy
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           4m14s

  or 해당 yaml을 적용해줘도 된다.

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  creationTimestamp: null
  name: nginx-deployment
spec:
  maxReplicas: 3
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: nginx-deployment
  targetCPUUtilizationPercentage: 80
status:
  currentReplicas: 0
  desiredReplicas: 0

2. hpa 확인

controlplane ~ ➜  kubectl get hpa
NAME               REFERENCE                     TARGETS              MINPODS   MAXPODS   REPLICAS   AGE
nginx-deployment   Deployment/nginx-deployment   cpu: <unknown>/80%   1         3         3          8m14s
#  <unknown>/80% 상태인 것 확인 가능하다

controlplane ~ ➜  kubectl describe hpa nginx-deployment 
Name:                                                  nginx-deployment
Namespace:                                             default
Labels:                                                <none>
Annotations:                                           <none>
CreationTimestamp:                                     Wed, 26 Feb 2025 01:49:43 +0000
Reference:                                             Deployment/nginx-deployment
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  <unknown> / 80%
Min replicas:                                          1
Max replicas:                                          3
Deployment pods:                                       3 current / 3 desired
Conditions:
  Type           Status  Reason                   Message
  ----           ------  ------                   -------
  AbleToScale    True    SucceededGetScale        the HPA controller was able to get the target's current scale
  ScalingActive  False   FailedGetResourceMetric  the HPA was unable to compute the replica count: failed to get cpu utilization: missing request for cpu in container nginx of Pod nginx-deployment-d556bf558-ftdhq
  # -> deployment의 resource field가 정의되어 있지 않아서 그렇다.

 

 👉🏻 hpq가 잘 작동하려면 resource field를 가지고 있어야 한다.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 7
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
        resources:   # 여기 설정
         requests: 
           cpu: 100m
         limits:
           cpu: 200m
           
# 적용 후, hpa cpu값이 잘 나오는 것 확인 가능하다.
controlplane ~ ➜  kubectl get hpa
NAME               REFERENCE                     TARGETS       MINPODS   MAXPODS   REPLICAS   AGE
nginx-deployment   Deployment/nginx-deployment   cpu: 0%/80%   1         3         1          16m

 

hpa events log 확인

controlplane ~ ➜  kubectl events hpa nginx-deploy | grep -i "ScalingReplicaSet"
23m                     Normal    ScalingReplicaSet              Deployment/nginx-deployment                Scaled up replica set nginx-deployment-d556bf558 to 7
19m                     Normal    ScalingReplicaSet              Deployment/nginx-deployment                Scaled down replica set nginx-deployment-d556bf558 to 3 from 7
# hpa가 pod 수 조정하는 것 확인 가능

controlplane ~ ➜  kubectl events hpa nginx-deploy | grep -i "FailedGetResourceMetric"
21m (x2 over 21m)       Warning   FailedGetResourceMetric        HorizontalPodAutoscaler/nginx-deployment   failed to get cpu utilization: missing request for cpu in container nginx of Pod nginx-deployment-d556bf558-d8nlj
19m (x9 over 21m)       Warning   FailedGetResourceMetric        HorizontalPodAutoscaler/nginx-deployment   failed to get cpu utilization: missing request for cpu in container nginx of Pod nginx-deployment-d556bf558-5k5g8
# resource field missing 확인 가능
  • resource constraints 으로 인해 클러스터가 지원할 수 있는 것보다 더 많은 replicas으로 deployments를 scale up하면 Kubernetes는 사용 가능한 리소스 내에서 가능한 한 많은 replicas를 생성한다. 하지만 남은 replicas는 충분한 리소스가 확보되거나 클러스터에 추가될 때까지 Pending 상태에 있는다. 이러한 동작을 통해 Kubernetes는 원하는 상태를 최대한 가깝게 유지하면서 동적으로 리소스를 관리할 수 있다.

 

 

참고:

반응형

'Container > Kubernetes' 카테고리의 다른 글

[K8S] Gateway API  (0) 2025.02.26
[K8S] Autoscaling - VPA  (0) 2025.02.26
[K8S] Mutating/Validating Admission Controller  (0) 2025.02.24
[K8S] Admission Controller  (0) 2025.02.24
[K8S] Kustomize Overlay/Components  (0) 2025.02.24