본문 바로가기
Compute/kubernetis

[따배씨] 6. Deployment & Pod Scale / CKA 시험 문제 학습

by 조청유곽 2025. 1. 30.
반응형

이 포스팅은 아래의 유튜브 채널 "따배"를 따라서 학습한 내용입니다.  

 

 

[관련 이론]

 

✅ Kubernetes에서 Deployment를 사용하는 이유
1️⃣ 안정적인 애플리케이션 배포 및 업데이트
Deployment는 애플리케이션을 배포할 때 서비스 중단 없이 새 버전으로 점진적으로 업데이트
(롤링 업데이트)할 수 있도록 지원합니다.
새 버전 배포 중 문제가 발생하면 자동으로 이전 버전으로 롤백할 수 있습니다.
📌 예제:
kubectl set image deployment/my-app my-container=my-app:v2
kubectl rollout undo deployment/my-app  # 롤백

2️⃣ 자동화된 복구(Self-healing)
Pod 장애 발생 시 자동으로 재시작하여 원하는 개수(Replicas)를 유지합니다.
특정 노드 장애 시, 정상 노드에서 자동으로 Pod을 재배포합니다.
📌 예제:
kubectl delete pod my-app-abcde  # 삭제해도 Deployment가 자동으로 새 Pod 생성

3️⃣ 확장성(Scaling) 관리
트래픽 증가 시 간단한 명령으로 애플리케이션을 수평 확장(Scale-out) 가능
자동 스케일링(HPA) 설정을 통해 CPU/메모리 사용량에 따라 자동 확장할 수도 있음.
📌 예제 (수동 확장):
kubectl scale deployment my-app --replicas=5

📌 예제 (자동 확장 - HPA 설정):
kubectl autoscale deployment my-app --cpu-percent=50 --min=2 --max=10

4️⃣ 일관된 상태 유지 (Desired State 유지)
Deployment는 사용자가 정의한 상태(Desired State)를 유지하도록 Kubernetes가 지속적으로 감시합니다.
관리자가 직접 개입하지 않아도 자동으로 원하는 상태를 유지할 수 있음.
📌 예제:
spec:
  replicas: 3  # 항상 3개의 Pod을 유지하도록 설정
  
5️⃣ 배포 전략 관리 (Rolling Update & Blue-Green 배포 가능)
Rolling Update 방식으로 점진적 업데이트 가능 (기본값)
Blue-Green 배포 또는 Canary 배포를 통해 특정 트래픽만 새 버전으로 전송할 수도 있음.
📌 Rolling Update 적용:
kubectl set image deployment my-app my-container=my-app:v2
kubectl rollout status deployment my-app

6️⃣ 멀티 컨테이너 관리 (Sidecar 패턴 지원)
Deployment는 여러 개의 컨테이너를 하나의 Pod 안에서 함께 실행 가능
Sidecar 패턴을 이용해 로깅, 모니터링, 데이터 동기화 등의 기능을 추가할 수 있음.
📌 예제 (Sidecar 추가):
spec:
  containers:
    - name: main-container
      image: my-app
    - name: logging-sidecar
      image: busybox
      command: ["/bin/sh", "-c", "tail -f /var/log/app.log"]
      
7️⃣ 선언적 관리 (YAML 기반의 Infrastructure as Code)
Kubernetes Deployment는 YAML 파일로 선언적으로 관리할 수 있어 버전 관리, 자동화가 용이합니다.
kubectl apply -f를 사용하여 GitOps 방식의 지속적 배포(CD) 가능
📌 예제 (YAML 파일 적용):
kubectl apply -f my-deployment.yaml

 

 

[Precondition]

(1) 테스트 환경

(1.1) Rocky Linux Cluster 

: 직접 구성

[root@k8s-master ~]# k get nodes -o wide
NAME         STATUS   ROLES           AGE   VERSION   INTERNAL-IP     EXTERNAL-IP   OS-IMAGE                            KERNEL-VERSION                  CONTAINER-RUNTIME
k8s-master   Ready    control-plane   30d   v1.27.2   192.168.56.30   <none>        Rocky Linux 8.10 (Green Obsidian)   4.18.0-553.33.1.el8_10.x86_64   containerd://1.6.32
k8s-node1    Ready    <none>          30d   v1.27.2   192.168.56.31   <none>        Rocky Linux 8.8 (Green Obsidian)    4.18.0-477.10.1.el8_8.x86_64    containerd://1.6.21
k8s-node2    Ready    <none>          30d   v1.27.2   192.168.56.32   <none>        Rocky Linux 8.8 (Green Obsidian)    4.18.0-477.10.1.el8_8.x86_64    containerd://1.6.21
[root@k8s-master ~]#

 

(1.2) Ubuntu Cluster 

: kodekloud 테스트 환경 활용

controlplane ~ ➜  kubectl get nodes -o wide
NAME           STATUS   ROLES           AGE     VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION   CONTAINER-RUNTIME
controlplane   Ready    control-plane   9m6s    v1.31.0   192.6.94.6    <none>        Ubuntu 22.04.4 LTS   5.4.0-1106-gcp   containerd://1.6.26
node01         Ready    <none>          8m31s   v1.31.0   192.6.94.9    <none>        Ubuntu 22.04.4 LTS   5.4.0-1106-gcp   containerd://1.6.26

https://learn.kodekloud.com/user/courses/udemy-labs-certified-kubernetes-administrator-with-practice-tests

 

 

(2) 사전 필요 설정 

: 테스트에 사용할 namespace "devops"와 context "k8s"를 미리 생성해 둔다.  

controlplane ~ ➜  k config get-contexts 
CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE
*         kubernetes-admin@kubernetes   kubernetes   kubernetes-admin   

controlplane ~ ➜  k config get-users 
NAME
kubernetes-admin

controlplane ~ ➜  k config set-context k8s --cluster kubernetes --user kubernetes-admin
Context "k8s" created.

controlplane ~ ➜  k create namespace devops
namespace/devops created

controlplane ~ ➜

 

 

[Question#1]

k8s

Expand the number of running Pods in "eshop-order" to 5
namespace : devops
deployment : eshop-order

 

 

[Solve]

(1) deployment 생성 

controlplane ~ ➜  k create deployment eshop-order --replicas=5 --dry-run=client --image=nginx -n devops -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: eshop-order
  name: eshop-order
  namespace: devops
spec:
  replicas: 5
  selector:
    matchLabels:
      app: eshop-order
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: eshop-order
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}

controlplane ~ ➜  k create deployment eshop-order --replicas=5 --image=nginx -n devops 
deployment.apps/eshop-order created

 

 

(2) 생성된 deployment 확인 

 

 

(3) 생성되어 있는 deployment의 scale 변경 

: deployment가 이미 생성되어 있는 경우라면 scale로만 replicas를 조정. 

controlplane ~ ➜  k scale deployment -n devops eshop-order --replicas=2
deployment.apps/eshop-order scaled

controlplane ~ ➜  k get deployments.apps -n devops eshop-order 
NAME          READY   UP-TO-DATE   AVAILABLE   AGE
eshop-order   2/2     2            2           14m

controlplane ~ ➜  k scale deployment -n devops eshop-order --replicas=5
deployment.apps/eshop-order scaled

controlplane ~ ➜  k get deployments.apps -n devops eshop-order 
NAME          READY   UP-TO-DATE   AVAILABLE   AGE
eshop-order   5/5     5            5           14m

controlplane ~ ➜

 


 

 

[사용 커맨드 정리]

k config use-context k8s

k create deployment eshop-order --replicas=5 --image=nginx -n devops --dry-run=client -o yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: eshop-order
  name: eshop-order
  namespace: devops
spec:
  replicas: 5
  selector:
    matchLabels:
      app: eshop-order
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: eshop-order
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}

k create deployment eshop-order --replicas=5 --image=nginx -n devops 

k get deployments.apps -n devops eshop-order 

k describe deployments.apps -n devops eshop-order

k scale deployment -n devops eshop-order --replicas=5


 

 

[Question#2]

Create a deployment as follows:
Task:
- name : webserver
- 2 replicas
- label : app_env_stage=dev
- container name : webserver
- container image : nginx:1.14

Scale Out Depolyment
- Scale the deployment webserver to 3 pods

 

 

[Solve]

(1) deployment 생성 

controlplane ~ ➜  k create deployment webserver --image=nginx:1.14 --replicas=2 --dry-run=client -o yaml > 6-deploy.yaml
controlplane ~ ➜  vi 6-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app_env_stage: dev
  name: webserver
spec:
  replicas: 2
  selector:
    matchLabels:
      app_env_stage: dev
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app_env_stage: dev
    spec:
      containers:
      - image: nginx:1.14
        name: webserver
        resources: {}
status: {}

 

 

(2) deployment scale out

controlplane ~ ➜  k get deployments.apps webserver 
NAME        READY   UP-TO-DATE   AVAILABLE   AGE
webserver   2/2     2            2           37s

controlplane ~ ➜  k scale deployment webserver --replicas=3
deployment.apps/webserver scaled

 

반응형