> For the complete documentation index, see [llms.txt](https://kde6260.gitbook.io/dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kde6260.gitbook.io/dev/k8s-replicaset.md).

# k8s 클러스터에 replicaset 생성하기

최초작성일 \[2020.03.14]

마이크로서비스에서는 여러 개의 동일한 컨테이너를 생성한 뒤 외부 요청이 각 컨테이너에 적절히 분배될 수 있어야 한다.쿠버네티스에서는 여러 개의 동일한 컨테이너를 생성하기 위해 리플리카셋(replicaset)이라는 오브젝트를 사용한다. replicaset은 항상 정해진 수 만큼의 pod를 유지하며 노드에 장애가 발생하여 pod를 사용할 수 없을 경우 다른 노드에서 pod를 다시 생성하는 등의 pod 관리를 책임진다.&#x20;

### 1. replicaset 생성하기

Nginx pod를 생성하는 replicaset을 만들어보자. 아래는 `nginx.yml` 파일의 내용이다.

```yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-nginx
spec:
  replicas: 3

  selector:
    matchLabels:
      app: nginx

  template:
    metadata:
      name: pod-nginx
      labels:
        # selector의 matchLabels과 동일함.
        app: nginx
    spec:
      containers:
        - name: pod-nginx
          image: nginx:latest
          ports:
            - containerPort: 80
```

| attribute           | role                                                                                                |
| ------------------- | --------------------------------------------------------------------------------------------------- |
| kind                | <p>리소스 종류.</p><p><code>$ kubectl api-resources</code> 명령어 결과의  <code>KIND</code> 필드에서 확인할 수 있다.</p> |
| metadata            | 리소스의 이름, 라벨 등의 부가정보.                                                                                |
| spec                | 리소스 생성을 위한 명세.                                                                                      |
| spec.relicas        | 유지할 pod의 수.                                                                                         |
| spec.selector       | 생성해야 할 pod의 라벨.                                                                                     |
| spec.template       | pod를 생성할 때 사용할 템플릿. pod template으로도 불린다.                                                            |
| spec.containers     | <p>pod에 들어갈 컨테이너.</p><p>pod에는 1개 이상의 컨테이너가 생성될 수 있으므로 여러개 정의할 수 있다.</p>                             |
| ports.containerPort | 컨테이너가 사용하는 포트번호.                                                                                    |

작성한 리소스를 클러스터에 생성하고 확인해보자.

```
$ kubectl apply -f nginx.yml
replicaset.apps/replicaset-nginx created

$ kubectl get pods
replicaset-nginx-b2dsp        1/1     Running            0          10s
replicaset-nginx-j6zcj        1/1     Running            0          10s
replicaset-nginx-v2ztm        1/1     Running            0          10s
```

`spec.relicas` 에 정의된 갯수에 맞게 pod가 생성된 것을 볼 수 있다. 위의 pod 3개는 replicaset에 의해 만들어진 것이므로 replicaset을 삭제하거나 수정하면 pod에도 반영한다.

```
$ kubectl get pods
replicaset-nginx-b2dsp        1/1     Running            0          5m
replicaset-nginx-j6zcj        1/1     Running            0          5m
replicaset-nginx-v2ztm        1/1     Running            0          5m

$ kubectl delete replicaset replicaset-nginx
replicaset.apps "replicaset-nginx" deleted
```

### 2. label selector

replicaset은 pod와 '느슨한 연결'을 가지고 있는데, 이 느슨한 연결은 **label selector**로 이뤄져있다. label은 사용자 관점에서 리소스를 식별하는 데 쓰일 뿐만 아니라 오브젝트들이 서로를 찾아야 할 때 쓰기도 한다. replicaset은  `spec.selector.matchLabels` 속성에 정의된 라벨을 통해 생성해야하는 pod를  찾는다.

위에서 생성한 `replicaset-nginx`의 경우 `app: nginx` 라는 라벨을 가진 pod의 갯수가 `replicas` 속성에 정의된 숫자에 일치하지 않으면 `template`의 내용으로 pod를 생성한다. replicaset을 처음 생성했을 때는 라벨과 일치하는 pod가 아예 없었기 때문에 3개를 생성했다.&#x20;

`replicas`속성을 3에서 4로 바꾸고 다시 `$ kubectl apply -f nginx.yml`을 실행했다.

```
$ kubectl apply -f nginx.yml 
replicaset.apps/replicaset-nginx configured

$ kubectl get pods
NAME                     READY   STATUS              RESTARTS   AGE
replicaset-nginx-4zqvc   0/1     ContainerCreating   0          4s
replicaset-nginx-b2dsp   1/1     Running             0          40m
replicaset-nginx-j6zcj   1/1     Running             0          40m
replicaset-nginx-v2ztm   1/1     Running             0          40m
```

새로운 pod 1개가 만들어졌다.  `app: nginx` 라벨을 가진 pod 3개가 이미 있기 때문에 1개만 새로 생성된 것이다.&#x20;

반대로 replicaset에 의해 만들어진 pod를 직접 삭제하면 어떻게 될까?

```
$ kubectl get pods
NAME                     READY   STATUS              RESTARTS   AGE
replicaset-nginx-4zqvc   0/1     ContainerCreating   0          4s
replicaset-nginx-b2dsp   1/1     Running             0          40m
replicaset-nginx-j6zcj   1/1     Running             0          40m
replicaset-nginx-v2ztm   1/1     Running             0          40m

$ kubectl delete pods replicaset-nginx-b2dsp
pod "replicaset-nginx-b2dsp" deleted

$ kubectl get pods                          
NAME                     READY   STATUS    RESTARTS   AGE
replicaset-nginx-4zqvc   1/1     Running   0          12m
replicaset-nginx-bzg4z   1/1     Running   0          28s
replicaset-nginx-j6zcj   1/1     Running   0          53m
replicaset-nginx-v2ztm   1/1     Running   0          53m
```

`replicaset-nginx-b2dsp`라는 pod를 직접 삭제했더니 `replicaset-nginx-bzg4z`라는 pod를 새로 생성했다.

이번에는 pod의 라벨을 직접 수정하면 어떻게 될지 확인해보자. 아래 커맨드를 실행하여 `replicaset-nginx-4zqvc` 라는 pod의 `label` 속성을 삭제해보겠다. `$ kubectl edit` 을 실행하면 S3에서 관리하는 pod의 상태파일을 터미널에서 열어준다.&#x20;

```
$ kubectl edit pods replicaset-nginx-4zqvc
```

```yaml
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
  annotations:
    cni.projectcalico.org/podIP: 100.100.132.202/32
   kubernetes.io/limit-ranger: 'LimitRanger plugin set: cpu request for container
     pod-nginx'
 creationTimestamp: "2020-03-14T09:30:52Z"
 generateName: replicaset-nginx-
 name: replicaset-nginx-4zqvc
```

-`-show-labels` 옵션으로 pod들의 라벨을 확인해보자. `app=nginx` 라벨을 가진 pod가 1개 유실된만큼 새로운 pod 1개를 생성했다. 라벨이 삭제된 pod는 `<none>`이라는 라벨을 갖게 되고 `replicaset-nginx`의 `selector.matchLabels`의 값과 일치하지 않으므로 `replicaset-nginx`가 더 이상 관리하지 않는다. 따라서 `replicaset-nginx`를 수정하거나 삭제해도 라벨이 삭제된 pod는 아무런 영향을 받지 않는다.&#x20;

```
$ kubectl get pods --show-labels
NAME                     READY   STATUS    RESTARTS   AGE     LABELS
replicaset-nginx-4zqvc   1/1     Running   0          35m     <none>
replicaset-nginx-bzg4z   1/1     Running   0          23m     app=nginx
replicaset-nginx-j6zcj   1/1     Running   0          75m     app=nginx
replicaset-nginx-qwxxr   1/1     Running   0          3m39s   app=nginx
replicaset-nginx-v2ztm   1/1     Running   0          75m     app=nginx
```

출처

* [시작하세요! 도커/쿠버네티스](https://search.kyobobook.co.kr/web/search?vPstrKeyWord=%25EC%258B%259C%25EC%259E%2591%25ED%2595%2598%25EC%2584%25B8%25EC%259A%2594%21%2520%25EB%258F%2584%25EC%25BB%25A4%252F%25EC%25BF%25A0%25EB%25B2%2584%25EB%2584%25A4%25ED%258B%25B0%25EC%258A%25A4\&orderClick=LEA)
* [Labels and Selectors](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/)
