본문 바로가기
Programming/Kubernetes

Kubernetes HPA (Horizontal Pod Autoscaler)

by guru_k 2021. 10. 12.
728x90
반응형

HPA는 Horizontal Pod Autoscaler의 줄임말로 kubernetes 에서 auto scaling을 지원해주는 기능이라고 볼 수 있다.

HPA는 cpu 사용량이나 제공되는 metrics를 기반으로 replication controller, deployment, replica set 또는 stateful set을 scaling 해주는 역할을 수행한다. 단, replicas를 제어할 수 없는 오브젝트 (예로 데몬셋)는 지원되지 않는다.

HPA는 controller manager에 의해서 관리되며 --horizontal-pod-autoscaler-sync-period flag로 설정된 주기마다 컨트롤되는 형태의 컨트롤 루프로 구현된다. (기본 설정은 15초)

위에서 설정된 주기와 HPA 설정에 따라 controller manager는 metrics API로 부터 각 리소스의 metrics 정보를 얻어 온다.

metrics API를 통해 얻어온 metric을 통해 scale 여부를 결정하게 되며 아래와 같은 알고리즘을 통해 desired metric value 와 current metric value의 비율로 결정하게 된다.

desiredReplicas = ceil[currentReplicas * ( currentMetricValue / desiredMetricValue )]

예로 replicas가 1대일 때 current metric value가 200m 이고 desired metric value가 100m 일때 200.0 / 100.0 == 2.0 으로 replicas는 2대로 증설된다.

HPA 연습해보기

시작하기전 HPA는 metrics-server가 제공하는 metric API를 통해서 metrics를 수집하여 scaling을 수행함으로 kubernetes cluster에 metrics-server가 배포 되어있어야 한다. 

테스트를 위한 docker 이미지 생성

부하 생성을 위한 php 파일 생성

<?php
  $x = 0.0001;
  for ($i = 0; $i <= 1000000; $i++) {
    $x += sqrt($x);
  }
  echo "OK!";
?>

Dockerfile 생성

FROM php:5-apache
COPY index.php /var/www/html/index.php
RUN chmod a+rx index.php

Docker build

$ docker build -t hpa-test .
Sending build context to Docker daemon  3.072kB
Step 1/3 : FROM php:5-apache
5-apache: Pulling from library/php
5e6ec7f28fb7: Pull complete
cf165947b5b7: Pull complete
7bd37682846d: Pull complete
99daf8e838e1: Pull complete
ae320713efba: Pull complete
ebcb99c48d8c: Pull complete
9867e71b4ab6: Pull complete
936eb418164a: Pull complete
bc298e7adaf7: Pull complete
ccd61b587bcd: Pull complete
b2d4b347f67c: Pull complete
56e9dde34152: Pull complete
9ad99b17eb78: Pull complete
Digest: sha256:0a40fd273961b99d8afe69a61a68c73c04bc0caa9de384d3b2dd9e7986eec86d
Status: Downloaded newer image for php:5-apache
 ---> 24c791995c1e
Step 2/3 : COPY index.php /var/www/html/index.php
 ---> 767e00d554d2
Step 3/3 : RUN chmod a+rx index.php
 ---> Running in 21c35da0e7dd
Removing intermediate container 21c35da0e7dd
 ---> 89226ef07d25
Successfully built 89226ef07d25
Successfully tagged hpa-test:latest

docker image push

$ docker tag hpa-test docker.hub.io/test/hpa-test

$ docker push docker.hub.io/test/hpa-test
The push refers to repository [docker.hub.io/test/hpa-test]
b08f7a13591f: Pushed
416faf6d334b: Pushed
1aab22401f12: Pushed
13ab94c9aa15: Pushed
588ee8a7eeec: Pushed
bebcda512a6d: Pushed
5ce59bfe8a3a: Pushed
d89c229e40ae: Pushed
9311481e1bdc: Pushed
4dd88f8a7689: Pushed
b1841504f6c8: Pushed
6eb3cfd4ad9e: Pushed
82bded2c3a7c: Pushed
b87a266e6a9c: Pushed
3c816b4ead84: Pushed
latest: digest: sha256:5a8b6cda514a3bd5e90ebf6038180afc7072e5f2c9cc95562949a55d8bca67b2 size: 3449

deployment 및 service 배포

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: php-apache
spec:
  selector:
    matchLabels:
      run: php-apache
  replicas: 1
  template:
    metadata:
      labels:
        run: php-apache
    spec:
      containers:
      - name: php-apache
        image: hpa-test
        ports:
        - containerPort: 80
        resources:
          limits:
            cpu: 500m
          requests:
            cpu: 200m

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: php-apache
  labels:
    run: php-apache
spec:
  ports:
  - port: 80
  selector:
    run: php-apache

배포하기

$ kubectl apply -f deployment.yaml
deployment.apps/php-apache created

$ kubectl apply -f service.yaml
service/php-apache created

HPA 생성

다음 명령어를 사용해서 pod replicas를 1대에서 5대까지 scale 가능한 HPA를 생성한다. cpu 사용량은 70% 이상일 경우 scale out되도록 설정한다.

$ kubectl autoscale deployment php-apache --cpu-percent=70 --min=1 --max=5
horizontalpodautoscaler.autoscaling/php-apache autoscaled

$ kubectl get hpa
NAME                      REFERENCE                            TARGETS                        MINPODS   MAXPODS   REPLICAS   AGE
php-apache                Deployment/php-apache                10%/70%                        1         5         0          6s

부하 생성 (scale out)

busybox 이미지를 사용하여 생성된 service를 통해 pod에 부하를 준다.

kubectl run -i --tty load-generator --rm --image=busybox --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"

HPA가 정상적으로 동작하는지 확인

$ kubectl get hpa

NAME         REFERENCE                     TARGET      MINPODS   MAXPODS   REPLICAS   AGE
php-apache   Deployment/php-apache/scale   335% / 70%  1         5         1          3m

cpu 사용량이 증가하면서 pod replicas가 5대까지 scale out 되었다. deployment를 통해 확인 해보자.

$ kubectl get deploy php-apache
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
php-apache   5/5     5            5           14m

cpu 사용량이 설정된 70%를 넘어감에 따라 pod이 MAXPODS인 5대까지 증설되었다.

부하 중지 (scale in)

부하 중지 후 서비스가 정상적으로 scale in이 되는지 확인해보자.

기존에 실행했던 부하 생성을 중지하기 위해 <Ctrl> + c 로 이전에 띄웠던 컨테이너를 중지 후 확인을 해본다.

$ kubectl get hpa
NAME                      REFERENCE                            TARGETS                        MINPODS   MAXPODS   REPLICAS   AGE
php-apache                Deployment/php-apache                0%/70%                         1         5         1          10m

deployment도 정상적으로 scale in 되었는지 확인 해본다.

$ kubectl get deploy php-apache
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
php-apache   1/1     1            1           18m

cpu 사용량이 0%로 떨어졌으며 replicas의 개수도 MINPODS에 설정된 개수인 1대로 정상적으로 scale in이 되었다.

728x90
반응형

댓글