[K8S] Deployments, ReplicaSet, StatefulSets

행복한 콩🌳·2023년 6월 7일
0

K8S

목록 보기
3/3

개요

kubernetes pod를 삭제하면 replicaset 설정 때문에 pod가 계속 살아남
deployment를 삭제하여 해결
deployment 삭제는 kubectl delete deploy [삭제할 deploy 이름] 인데
이게 deployment인지 뭔지 어떻게 알지?하는 물음으로 Deployment, ReplicaSet, StatefulSet 개념을 잡고자 작성함

Deployments

동작원리

  1. Deployment가 생성되면, 컨트롤 플레인은 Deployment의 목표 상태를 계산합니다
  2. 컨트롤 플레인은 현재 상태와 목표 상태의 차이를 확인하고, Pod를 생성, 삭제, 복제하여 목표 상태를 달성합니다.
  3. 컨트롤 플레인은 Deployment의 상태를 지속적으로 모니터링하고, 목표 상태와 일치하지 않으면 Pod를 생성, 삭제, 복제하여 목표 상태를 달성합니다.

controllers/nginx-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

run

  1. 다음 명령으로 Deployment를 생성
kubectl apply -f https://k8s.io/examples/controllers/nginx-deployment.yaml
  1. kubectl get deployments를 실행하여 생성되었는지 확인.

생성 되었다면 아래와 같이 출력됩니다.

NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   0/3     0            0           1s

NAME : namespace의 deployments의 이름 나열
REDY: 사용가능한 replica들의 수를 나타냄 [준비된 것 / 희망하는 준비 수]
UP-TO-DATE: 레플리카의 수가 희망하는 상태에 얼마나 업데이트 되었는지 보여줌 AVAILABLE: users들이 사용할 수 있는 replica의 수를 보여줌
AGE: application이 얼마나 많은 시간동안 running 중인지 보여줌

  1. Deployment 상세 내역 확인 명령
kubectl describe deployment

아래와 같은 결과 출력

Name:           nginx-deployment
Namespace:      default
CreationTimestamp:  Tue, 15 Mar 2016 14:48:04 -0700
Labels:         app=nginx
Selector:       app=nginx
Replicas:       3 desired | 1 updated | 4 total | 3 available | 1 unavailable
StrategyType:       RollingUpdate
MinReadySeconds:    0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx:1.161
    Port:         80/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    ReplicaSetUpdated
OldReplicaSets:     nginx-deployment-1564180365 (3/3 replicas created)
NewReplicaSet:      nginx-deployment-3066724191 (1/1 replicas created)
Events:
  FirstSeen LastSeen    Count   From                    SubObjectPath   Type        Reason              Message
  --------- --------    -----   ----                    -------------   --------    ------              -------
  1m        1m          1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled up replica set nginx-deployment-2035384211 to 3
  22s       22s         1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled up replica set nginx-deployment-1564180365 to 1
  22s       22s         1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled down replica set nginx-deployment-2035384211 to 2
  22s       22s         1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled up replica set nginx-deployment-1564180365 to 2
  21s       21s         1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled down replica set nginx-deployment-2035384211 to 1
  21s       21s         1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled up replica set nginx-deployment-1564180365 to 3
  13s       13s         1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled down replica set nginx-deployment-2035384211 to 0
  13s       13s         1       {deployment-controller }                Normal      ScalingReplicaSet   Scaled up replica set nginx-deployment-3066724191 to 1

K8S docs: Deployment

ReplicaSet

동작원리

레플리카 셋은 필드, 레플리카 수, Pod 템플릿으로 정의됨
레플리카셋은 Pod의 metadata.ownerReferences 필드에 의해 Pod에 연결됩니다.
이 필드는 현재 개체가 소유하고 있는 리소스를 지정합니다.
레플리카셋에 의해 가져온 모든 Pod는 ownerReferences 필드에 소유하고 있는 레플리카셋의 식별 정보를 포함하고 있습니다.
이 연결을 통해 레플리카셋은 유지하고 있는 Pod의 상태를 파악하고 그에 따라 계획을 세웁니다.
예를 들어, 레플리카셋이 replicas: 3으로 정의된 경우, 레플리카셋은 3개의 Pod를 유지합니다. 만약 2개의 Pod가 실행 중이고 1개의 Pod가 종료된 경우, 레플리카셋은 새로운 Pod를 생성하여 Pod의 개수를 3으로 유지합니다.

code

controllers/frontend.yaml

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: frontend
  labels:
    app: guestbook
    tier: frontend
spec:
  # modify replicas according to your case
  replicas: 3
  selector:
    matchLabels:
      tier: frontend
  template:
    metadata:
      labels:
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: gcr.io/google_samples/gb-frontend:v3

run

kubectl apply -f https://kubernetes.io/examples/controllers/frontend.yaml

현재 deploy된 replicaset 확인

kubectl get rs

아래와 같이 표시됨

NAME       DESIRED   CURRENT   READY   AGE
frontend   3         3         3       6s

K8S docs: replicaset

StatefulSets

컴퓨터 과학(CS)에서는 관계의 상태를 유지하는 것을 stateful이라고 부릅니다. 반대로, 관계를 유지 않으면 stateless라고 부릅니다.
쿠버네티스 관계 유지 설정 해주는 것이 바로 statefulset입니다.

동작원리

스테이트풀셋은 애플리케이션의 스테이트풀을 관리하는데 사용하는 워크로드 API 오브젝트입니다.
파드 집합의 디플로이먼트와 스케일링을 관리하며, 파드들의 순서 및 고유성을 보장합니다.

스테이트풀셋은 다음 중 하나 또는 이상이 필요한 애플리케이션에 유용합니다.

  1. 안정된, 고유한 네트워크 식별자.
  2. 안정된, 지속성을 갖는 스토리지.
  3. 순차적인, 정상 배포(graceful deployment)와 스케일링.
  4. 순차적인, 자동 롤링 업데이트.

Deployment 와의 주요 차이점

  • Service vs Headless Service
    Deployment는 Service를 통해서 외부에 노출이 되고, Service로 request를 하면 random 하게 Pod가 선택됩니다.
  • StatefulSet은 Headless Service를 통해 외부에 노출이 되고, 각 Pod별 고유한 DNS를 가지며 원하는 Pod를 지정해서 request를 해야 합니다. (Service에 request 하는것은 불가능)
  • Rollback 및 ReplicaSet
    Deployment 는 내부적으로 ReplicaSet을 생성하여 Pod를 관리하며, rollback 이 가능합니다.(rolling update시에 새로운 replicaset이 생성되며 기존 ReplicaSet의 개수는 줄고, 새로운 ReplicaSet의 개수가 늘어나는 방식)
  • StatefulSet은 내부적으로 ReplicaSet을 생성하지 않으며 rollback이 불가합니다.
  • Deployment 의 경우 Stateless 방식으로 Pod을 배포, StatefulSet은 Stateful 방식으로 Pod을 관리합니다.
apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  ports:
  - port: 80
    name: web
  clusterIP: None
  selector:
    app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  selector:
    matchLabels:
      app: nginx # .spec.template.metadata.labels 와 일치해야 한다
  serviceName: "nginx"
  replicas: 3 # 기본값은 1
  minReadySeconds: 10 # 기본값은 0
  template:
    metadata:
      labels:
        app: nginx # .spec.selector.matchLabels 와 일치해야 한다
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: nginx
        image: registry.k8s.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "my-storage-class"
      resources:
        requests:
          storage: 1Gi

K8S docs: statefulset

요약

deployment -> 배포용
replica set -> 프로세스 개수를 여러 개 만들어줌
stateful set -> db에서 많이 사용, ss이 지워져도 PV or PVC를 사용하여 state를 PV에 보존

profile
매일매일 조금씩 모여 숲이 되자🐣

0개의 댓글