Controller이란?
- 특정 application을 운영하는데 있어서 pod의 개수를 보장하는 역할을 하는 컴포넌트
https://devops.com.vn/using-replica-set-and-daemon-set-deploying-managing-pod-in-k8s/
1. ReplicationController란?
- k8s 프로젝트 초장기부터 있었던 가장 기본적인 컨트롤러
- 지정한 숫자만큼의 Pod의 개수를 보장하며 파드 집합의 실행을 안정적으로 보장하기 위한 컴포넌트
- 현재 구동중인 Pod 개수가 요구된 pod 개수보다 부족한경우 template를 이용하여 pod를 생성
- 요구된 pod의 수 보다 현재 구동중인 pod가 많다면 최근에 생성된 pod를 삭제
- 기본구성
- selector
- Controller는 오직 selector만을 기준으로만 동작한다
- replicas
- Pod의 개수를 보장
- template
- RC는 pod 생성/삭제에 대해서 해당 template를 참조한다
- selector
- 현재는 비슷한 역할을 수행하는 ReplicaSet을 사용하는 추세
ReplicationController Test
apiVersion: v1
kind: ReplicationController
metadata:
name: rc-nginx
spec:
replicas: 3
selector:
app: nginx
template:
metadata:
name: nginx-pod
labels: #해당 labels는 반드시 상단의 selector의 값들을 전부 포함해야한다.
app: nginx
test: test
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
- # kubectl apply -f ./replicationController.yaml
- # kubectl describe rc rc-nginx
- 현재 Replicas의 current와 disired가 같다면 pod를 추가 할 수 없다
- # kubectl scale rc rc-nginx --replicas=2
- # kubectl scale rc http-go --replicas=5
- pod의 label 확인
- # kubectl get pods --show-labels
2. ReplicaSet이란?
- ReplicationController와 같은 역할을 수행하는 컨트롤러
- selector를 통해서 ReplicationController보다 다양한 표현이 가능하다
- ReplicationController와 동일하게 selector만을 기준으로 pod를 관리한다
ReplicationController.yaml | ReplicaSet.yaml |
apiVersion: v1 kind: ReplicationController metadata: name: rc-nginx spec: replicas: 3 selector: app: nginx note: "12" abc: "2" template: metadata: name: nginx-pod labels: app: nginx note: "12" abc: "2" test: test spec: containers: - name: nginx image: nginx ports: - containerPort: 80 |
apiVersion: apps/v1 kind: ReplicaSet metadata: name: rs-nginx spec: replicas: 3 selector: matchLabels: app: nginx note: "12" abc: "2" template: metadata: name: nginx-pod labels: app: nginx note: "12" abc: "2" test: test spec: containers: - name: nginx image: nginx ports: - containerPort: 80 |
matchExpressions 연산자 | 설명 |
In | key와 values를 지정하여 동일한 key, value가 일치하는 Pod 매칭 |
NotIn | Key는 일치하고 value는 일치하지 않는 Pod 매칭 |
Exists | key에 맞는 label의 Pod 매칭 |
DoesNotExist | Key와 다른 label의 Pod 매칭 |
matchExpressions | In | Exists |
표현 | spec: replicas: 3 selector: matchExpressions: - {key: version, operator: In, values: ["1.14",1.15]} |
spec: replicas: 3 selector: matchExpressions: - {key: version, operator: Exists} |
설명 | key가 version이면서 해당값이 1.14이거나 1.15인 경우에만 Pod 매칭 | key가 version이 존재하는 pod 매칭 |
matchExpressions | NotIn | DoesNotExist |
표현 | spec: replicas: 3 selector: matchExpressions: - {key: version, operator: NotIn, values: ["1.14",1.15]} |
spec: replicas: 3 selector: matchExpressions: - {key: version, operator: Exists} |
설명 | key가 version이면서 해당값이 1.14이거나 1.15인 아닌 경우에만 Pod 매칭 | key가 version이 존재하는 않는 pod 매칭 |
ReplicaSet Test
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: rs-nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
test: test
template:
metadata:
name: nginx-pod
labels:
app: nginx
test: test
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
- # kubectl apply -f ./rs-nginx.yaml
- # kubectl scale rs rs-nginx --replicas=2
- scale in
- # kubectl delete rs rs-nginx --cascade=orphan
- 현재 구동중인 pod는 삭제하지 않고 rs만 삭제
3. Deployment란?
- stateless 앱을 배포하기 위해서 사용하는 가장 기본적인 컨트롤러
- ReplicaSet을 관리하여 앱 배포를 세밀하게 관리한다
- 단순 실행시켜야하는 pod를 유지하는것 뿐만 아니라 롤링 업데이트(Rolling Update) & Rolling Back 지원
- Rolling Update
- pod 인스턴스를 점진적으로 새로운 것으로 업데이트하여 디플로이먼트 업데이트가 서비스 중단 없이 이루어 질 수 있도록 한다
ReplicaSet.yaml | Deployment.yaml |
apiVersion: apps/v1 kind: ReplicaSet metadata: name: rs-nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: name: nginx-pod labels: app: nginx test: test spec: containers: - name: nginx image: nginx ports: - containerPort: 80 |
apiVersion: apps/v1 kind: Deployment metadata: name: deployment-nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: name: nginx-pod labels: app: nginx test: test spec: containers: - name: nginx image: nginx ports: - containerPort: 80 |
Deployment Test
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
name: nginx-pod
labels:
app: nginx
test: test
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
- delpoyment -> rsplicaSet -> pod 생성
- # kubectl apply -f ./deployment-nginx.yaml
- # kubectl get deployments.apps,rs,pod
Rolling Update
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-nginx
spec:
replicas: 3
selector:
matchLabels:
app: webserver
template:
metadata:
name: nginx-pod
labels:
app: webserver
test: test_branch
spec:
containers:
- name: webserver
image: nginx:1.14
ports:
- containerPort: 80
- # kubectl apply -f ./deployment-nginx.yaml --record
- # kubectl set image deployment deployment-nginx webserver=nginx:1.15 --record
- pod 버전 update 확인
- # kubectl rollout status deployment deployment-nginx
- rolling update 동작확인
- # kubectl rollout pause deployment deployment-nginx
- rolling update 중단
- # kubectl rollout status deployment deployment-nginx
- rolling update 다시시작
- # kubectl rollout history deployment deployment-nginx
- rolling update history 확인
- default값은 최대 10개
- rolling update history 확인
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-nginx
kubernetes.io/change-cause: version 1.14
spec:
progressDeadlineSeconds: 600
revisionHistoryLimit: 10
strategy:
rollingUpdate:
maxSurge: 50%
maxUnavailable: 25%
type: RollingUpdatae
replicas: 3
selector:
matchLabels:
app: webserver
template:
metadata:
name: nginx-pod
labels:
app: webserver
test: test_branch
spec:
containers:
- name: webserver
image: nginx:1.14
ports:
- containerPort: 80
Rolling update 전략 | 의미 |
progressDeadlineSeconds | deployment 진행 중 실패했을경우, 실패했을때까지의 대기시간(default: 600초) |
revisionHistoryLimit | rolling update command history 저장 개수(default :10개) |
maxSurge | 업데이트 진행 중 최대로 생성할 수 있는 pod 수(default: 25%) 예시: maxSurge: 50% - 현재 replicas 3개 기준(1.5(50%) = 2) 3+2(반올림)--> 업데이트 중 최대 pod 5개까지 생성 가능 |
maxUnavailable | 업데이트 진행 중 사용 할 수 없는 최대 pod 수(default: 25%) - 75% pod는 항상 가용중임을 의미 |
annotations: |
annotations: kubernetes.io/change-cause: version 1.15 ... spec: containers: - name: webserver image: nginx:1.15 |
annotations: kubernetes.io/change-cause: version 1.16 ... spec: containers: - name: webserver image: nginx:1.16 |
|
annotations: kubernetes.io/change-cause: version 1.17 ... spec: containers: - name: webserver image: nginx:1.17 |
|
![]() - annotations를 추가하여 rollout history에 Change-cause 정보를 변경 할 수 있다 - Rolling update는 container의 이미지변경시에 적용된다 |
Rollback
- # kubectl rollout undo deployment deployment-nginx --to-revision=1
- --to-revision 생략시 바로 전단계로 rollback
- rollback 이후 rollout history의 1번이 삭제되고 3번으로 변경
4. DaemonSet이란?
- 전체 노드에서 Pod가 한 개씩 실행하도록 보장하는 컴포넌트
- 클러스터 전체 노드에 특정 Pod를 실행할 때 사용
- 클러스터에 노드가 추가되면 DaemonSet이 해당 노드에 Pod 실행
- 노드가 클러스터에서 빠지면 해당 노드의 Pod는 사라짐
- 사용 케이스
- 로그수집기
- 모니터링 에이전트
DaemonSet Test
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: daemonset-nginx
spec:
selector:
matchLabels:
app: nginx
template:
metadata:
name: nginx-pod
labels:
app: nginx
test: test
spec:
containers:
- name: nginx-container
image: nginx
ports:
- containerPort: 80
- 현재 Ready 중인 w1-k8s node와 w2-k8s node에 각각 1개의 pod가 생성된다
- # kubectl delete nodes w2-k8s
- w2-k8s node 삭제
- 일정시간 경과 후 w2-k8s에서 구동중이던 daemonSet pod가 삭제됨을 확인
- 현재 w2-k8s node가 없는 상황 -> daemonSet pod는 w1-k8s에만 구동중이다
- w2-k8s node를 join하여 w2-k8s node에 daemonSet pod가 자동 생성됨을 확인해보자
- 준비사항
- api server ip/port
- # kubectl config view | grep server
- token
- # kubeadmon token list로 확인
- 만약 token 값이 없으면 생성한다.
- # kubeadm token create --tth 시간
- 만약 token 값이 없으면 생성한다.
- # kubeadmon token list로 확인
- Hash값
- # openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'
- api server ip/port
- 준비사항
- kubeadm join <Kubernetes API Server:PORT> --token <2. Token 값> --discovery-token-ca-cert-hash sha256: Hash 값
- # kubeadm join 192.168.1.10:6443 --token 123456.1234567890123456 --discovery-token-ca-cert-hash sha256:ca382767cc3a2d5fba351381f454b3afaa9dad53d8271a602ea95abe8b2268d6
DaemonSet Rolling-Update
- # kubectl edit daemonsets.apps daemonset-nginx
- edit를 통해서 container의 이미지 버전변경
- 기존에 구동중인 daemonSet Pod가 terminate -> Running됨을 확인
- Rollback
- # kubectl rollout undo daemonset daemonset-nginx
StatefulSet이란?
- Pod의 상태를 유지해주는 역할을 하는 컴포넌트
- 특정 데이터를 볼륨에 저장한 후 Pod를 재시작하였을때 해당 데이터를 유지할 수 있게 한다
- Pod 재시작 시 pod의 이름을 유지시킬 수 있다
- 여러 Pod 사이의 순서를 지정하여 실행되게 할 수 있다
StatefulSet test
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: statefulset-nginx
spec:
replicas: 3
serviceName: statefulset-nginx-service
# podManagementPolicy: OrderedReady 순차적으로 pod 생성
# podManagementPolicy: Parallel 병렬적으로 pod 생성
selector:
matchLabels:
app: nginx
template:
metadata:
name: nginx-pod
labels:
app: nginx
spec:
containers:
- name: nginx-container
image: nginx
ports:
- containerPort: 80
- scale out 수행 시
- # kubectl scale statefulset statefulset-nginx --replicas=5
- statefulset-nginx-3, statefulset-nginx-4가 생성
- # kubectl scale statefulset statefulset-nginx --replicas=5
- scale in 수행 시
- # kubectl scale statefulset statefulset-nginx --replicas=2
- statefulset-nginx-2, statefulset-nginx-3, statefulset-nginx-4가 삭제
- # kubectl scale statefulset statefulset-nginx --replicas=2
- # kubectl edit statefulsets.apps statefulset-nginx
- rolling-update는 pod이름의 역순으로 Terminating -> Running 수행한다
- # kubectl rollout undo statefulset statefulset-nginx
- rollback은 pod이름의 역순으로 Terminating -> Running 수행한다
Job이란?
- 실행된 후 종료해야하는 성격의 작업을 실행시킬 때 사용하는 컴포넌트
- Batch 성 작업에 용이
- 비정상 종료 -> 다시실행
- 정상 종료 -> 완료
- Batch 성 작업에 용이
Job Test
apiVersion: batch/v1
kind: Job
metadata:
name: job-test
spec:
# completions: 5 //정상적으로 실행 종료되어야하는 pod 개수 지정
# parallelism: 2 //동시에 수행되는 pod 개수 지정
# activeDeadlineSeconds: 5 //정상적으로 종료되는 시간 지정
template:
spec:
containers:
- name: ubuntu-container
image: ubuntu
command: ["bash"]
args:
- "-c"
- echo "job test"; sleep 50; echo "'end'"
restartPolicy: Never # //비정상 종료시 pod를 재시작
# restartPolicy: OnFailure //비정상 종료시 container를 재시작
# backoffLimit: 3 //restartPolicy가 OnFailure인 경우 3번까지 container를 재시작
- completed된 pod는 재시작되지 않고 Pod가 정상적으로 실행돼 종료됐음을 의미하는 Completed 상태가 된다
CronJob이란?
- Job을 시간을 기준으로 관리하는 컴포넌트
- CronJob Schedule
매월 1일 1시 15분에 수행
주중: 요일 = 1-5
주말: 요일 = 0,6
*/10 * * * * = 10분마다 한번씩 수행
* * 1,3,5,6 * * = 매월 1, 3, 5, 6일에 한번 수행
CronJob Test
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: cronjob-test
spec:
schedule: "14 * * * *"
startingDeadlineSeconds: 500 //지정된 시간에 job이 실행되지 못한경우 설정한 시간까지 지나면 cronjob을 실행하지 않도록 지정
# concurrencyPoilcy: Allow //job 여러개를 동시에 실행(default)
# concurrencyPoilcy: Forbid // job을 동시에 실행하지 않고 기다림(처음 실행된 작업이 끝난 후 실행)
jobTemplate:
spec:
template:
spec:
containers:
- name: ubuntu-container
image: ubuntu
command: ["bashs"]
args:
- "-c"
- echo "job test"; sleep 3; echo "'end'"
restartPolicy: Never
# backoffLimit: 3
'클라우드 > K8s' 카테고리의 다른 글
K8s label (0) | 2022.03.17 |
---|---|
K8s Network (0) | 2022.03.17 |
K8s namespaces (0) | 2022.03.17 |
K8s Pod 구성패턴 (0) | 2022.03.17 |
POD (0) | 2022.03.17 |