클라우드 + DevOps/Kubernetes (k8s)

Kubernetes 쿠버네티스 :: StatefulSet 활용

gamjadori 2024. 4. 22. 16:10
728x90

<Kubernetes 쿠버네티스 :: StatefulSet 활용>

<statefulSet>

  • 애플리케이션의 statefulSet을 관리하는 workload 리소스
  • Stateless 애플리케이션은 Deployment로 배포하고, Stateful인 DB 같은 경우는 statefulSet으로 배포
  • 특징
    1. StatefulSet의 각 포드들은 동일 스펙으로 생성되지만, 서로 교체 불가 (re-scheduling이 되어도 지속적으로 동일 식별자 유지)
    2. StatefulSet 애플리케이션은 서버, 클라이언트, 애플리케이션에서 사용할 수 있도록 영구 볼륨에 데이터 저장 > StorageClass를 사용한 PVC 사용
    3. StatefulSet은 Headless Service를 사용
    4. 이유: StatefulSet에 연결된 Service는 Service를 통하지 않고 논리적으로 포드 집합을 만들어 주는 Service만 있으면 되기 때문
    5. IP가 없어도 DNS에 등록되므로 nslookup을 통해 포드의 주소 확인해 연결

 

1. StatefulSet 정의 및 서비스 생성

<visit-cnt-stfs.yaml>

  • StatefulSet: 애플리케이션의 상태를 유지하고 관리
    • 두 개의 볼륨 클레임 템플릿 정의
    • 1Gi의 스토리지를 요청하며 ReadWriteOnce 액세스 모드
    • ******/mynode:fc.stfs" 이미지를 사용하며 포트 8080 노출
    • "openebs-hostpath"라는 스토리지 클래스 사용
  • Service: StatefulSet에 대한 네트워크 트래픽을 관리
    • visit-cnt-stfs-svc
    • 포트 8080을 노출
    • 클러스터 IP를 가지지 않아 외부로 노출되지 않고 내부적으로만 사용
apiVersion: v1
kind: Service
metadata:
  name: visit-cnt-stfs-svc
  labels:
    app: visit-cnt-stfs
spec:
  ports:
  - port: 8080
    protocol: TCP
  selector:
    app: visit-cnt-stfs
  clusterIP: None
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: visit-cnt-stfs
spec:
  selector:
    matchLabels:
      app: visit-cnt-stfs
  serviceName: visit-cnt-stfs-svc
  replicas: 2
  template:
    metadata:
      labels:
        app: visit-cnt-stfs
    spec:
      containers:
      - name: stfs-container
        image: *******/mynode:fc.stfs
        ports:
        - name: http
          containerPort: 8080
        volumeMounts:
        - name: data
          mountPath: /var/data
volumeClaimTemplates:
- metadata:
    name: data
  spec:
    resources:
      requests:
        storage: 1Gi
    accessModes:
    - ReadWriteOnce
    storageClassName: "openebs-hostpath"

<적용>

[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl apply -f visit-cnt-stfs.yaml
service/visit-cnt-stfs-svc created
statefulset.apps/visit-cnt-stfs created

<생성 확인>

 

2. 레플리카 수 조정

[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl scale sts visit-cnt-stfs --replicas 4
statefulset.apps/visit-cnt-stfs scaled

<적용 확인>

 

<HPA> Horizon Pod Autoscaler

  • 수평적 포드 자동 조정기
  • 쿠버네티스 시스템의 가동 상황에 맞춰 시스템 조정 가능
  • CPU 및 메모리 사용량을 관찰하여 Deployment, ReplicaSet, StatefulSet의 포드 개수를 자동으로 확인 (DaemonSet 제외)
  • 컨트롤러는 관찰된 평균 CPU 사용률이 사용자가 지정한 대상과 일치하도록 Deployment에서 레플리카 개수를 주기적으로 조정
  • 워크로드의 크기를 수요에 맞게 자동으로 스케일링하는 것이 목표
  • 적정 포드 개수 지정 알고리즘
[PS C원하는 레플리카 수 = ceil [현재 레플리카 수 * (현재 Metric 값 / 원하는 Metric 값)]
  • 예시: 온라인 쇼핑몰의 접속자 수가 적은 날에는 애플리케이션 인스턴스 2개 운영 / 수요가 몰리는 날에는 동적으로 10개 증가
kubectl apply -f <https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml>

 

1. Metrics Server 설치하고 구성

  • Metrics Server: Kubernetes에서 클러스터 리소스 사용량 및 성능 지표를 수집하고 제공
[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl get deployment.apps metrics-server -n kube-system

<설치 확인>

(문제점)

  • READY가 1/1이어야 하는데 0/1로 되어 디플로이먼트 설정에 오류 확인

(문제점)

[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl top po
error: Metrics API not available

 

2. 해결 방법

[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl edit -n kube-system deployments.apps metrics-server
  • --kubelet-insecvure-tls 추가: Kubernetes API 서버가 kubelet에 연결할 때 TLS 인증서 유효성을 검사하지 않도록 하는 옵션

<확인>

A. kubectl get deployment.apps

B. kubectl top

  • Kubernetes 클러스터 내의 모든 Pod의 리소스 사용량을 보여주는 명령

 

[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl top node

 

1. Horizontal Pod Autoscaler(HPA) 생성

  • CPU 사용량이 50%를 초과할 때 Pod를 자동으로 확장
  • 최소 1개의 Pod에서 시작하여 최대 10개의 Pod까지 확장
[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl autoscale deployment smoke-deploy --cpu-percent=50  \\
--min=1 --max=10 --dry-run=client -o yaml > hpa2.yaml

<hpa2.yaml>

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: smoke-deploy
spec:
  maxReplicas: 10
  minReplicas: 1
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: smoke-deploy
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
status:
  currentReplicas: 0
  desiredReplicas: 0

>> apiVersion 버전 확인

<파일 적용>

[PS C:\\Users\\admin\\Desktop\\k8s-pods> kubectl apply -f hpa2.yaml
horizontalpodautoscaler.autoscaling/smoke-deploy created

 

2. CPU 사용량 증가

  • CPU 사용량이 50%를 초과하면 레플리카 생성

(결과물 캡쳐하지 못함)

ubuntu@k8s-master:~$ while true; do curl 10.109.131.18:8080/hostname; sleep 0.05; done