도커 & 쿠버/CKA를 취득하자

쿠버강의 hands-on _ 2

dudung__ 2023. 10. 12. 20:09

오늘은 강의에서 제공해주어서 kodekloud를 통해서 해볼 수 있는 lab을 위주로 많이 해봤다

 

초반에는 명령어만 가져왔지만, 중간부터는 문제(상황 / 과제)

 

 

O
kubectl get nodes => 노드에 관련된 정보를 출력                                                                           
NAME           STATUS   ROLES                  AGE   VERSION
controlplane   Ready    control-plane,master   17m   v1.27.1+k3s1
클러스터 안에 노드 1개 

 


O
kubectl version => version 확인 


O
What is the flavor and version of Operating System on which the Kubernetes nodes are running?

kubectl get nodes -o wide => 노드에 관련된 정보를 더 상세하게 출력 



O
kubectl get pod => pod에 관련된 정보를 출력 
No resources found in default namespace.

=> 활성화된게 없을 때 출력되는 문구 


O
kubectl get replicaset
No resources found in default namespace.


O
kubectl get deployment
No resources found in default namespace.

O
ubectl get deployment => 배포된 것들에 관련된 정보를 출력 
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
frontend-deployment   0/4     4            0           12s



O
kubectl get replicaset => replicatset에 관련된 정보를 출력 
NAME                             DESIRED   CURRENT   READY   AGE
frontend-deployment-577494fd6f   4         4         0       74s


O
kubectl get pod
NAME                                   READY   STATUS             RESTARTS   AGE
frontend-deployment-577494fd6f-4h4h2   0/1     ImagePullBackOff   0          98s
frontend-deployment-577494fd6f-6fwfl   0/1     ImagePullBackOff   0          98s
frontend-deployment-577494fd6f-hbbwd   0/1     ImagePullBackOff   0          98s
frontend-deployment-577494fd6f-d878k   0/1     ImagePullBackOff   0          98s

=> 이 경우에는 활성화면 개수가 4개



O
 kubectl get pod -o wide
NAME                                   READY   STATUS             RESTARTS   AGE    IP           NODE           NOMINATED NODE   READINESS GATES
frontend-deployment-577494fd6f-4h4h2   0/1     ImagePullBackOff   0          3m1s   10.42.0.10   controlplane   <none>           <none>
frontend-deployment-577494fd6f-d878k   0/1     ImagePullBackOff   0          3m1s   10.42.0.11   controlplane   <none>           <none>
frontend-deployment-577494fd6f-6fwfl   0/1     ImagePullBackOff   0          3m1s   10.42.0.9    controlplane   <none>           <none>
frontend-deployment-577494fd6f-hbbwd   0/1     ImagePullBackOff   0          3m1s   10.42.0.12   controlplane   <none>           <none>


O
kubectl describe pod  => 더욱 상세한 정보를 출력할 떄 describe(묘사하다)를 사용함 

                                     
Name:             frontend-deployment-577494fd6f-4h4h2
Namespace:        default
Priority:         0
Service Account:  default
Node:             controlplane/192.6.200.9
Start Time:       Thu, 12 Oct 2023 04:32:06 +0000
Labels:           name=busybox-pod
                  pod-template-hash=577494fd6f
Annotations:      <none>
Status:           Pending
IP:               10.42.0.10
IPs:
  IP:           10.42.0.10
Controlled By:  ReplicaSet/frontend-deployment-577494fd6f
Containers:
  busybox-container:
    Container ID:  
    Image:         busybox888
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      echo Hello Kubernetes! && sleep 3600
    State:          Waiting
      Reason:       ImagePullBackOff
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-ttz2v (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  kube-api-access-ttz2v:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason     Age                    From               Message
  ----     ------     ----                   ----               -------
  Normal   Scheduled  4m1s                   default-scheduler  Successfully assigned default/frontend-deployment-577494fd6f-4h4h2 to controlplane
  Normal   Pulling    2m30s (x4 over 4m)     kubelet            Pulling image "busybox888"
  Warning  Failed     2m30s (x4 over 4m)     kubelet            Failed to pull image "busybox888": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/library/busybox888:latest": failed to resolve reference "docker.io/library/busybox888:latest": pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed
  Warning  Failed     2m30s (x4 over 4m)     kubelet            Error: ErrImagePull
  Warning  Failed     2m19s (x6 over 3m59s)  kubelet            Error: ImagePullBackOff
  Normal   BackOff    2m8s (x7 over 3m59s)   kubelet            Back-off pulling image "busybox888"


=> pod을 배포할때 사용한 이미지를 사용하기 위해서 describe 명령어를 사용
=> 추가적으로 event 부분을 통해서 이 배포가 어떻게 진행되고 있는지를 살필 수 있음

=> 어떤 이유때문에 실패가 되는지 / 잘 되고 있는지 등을 확인 할 수 있음



O
Create a new Deployment using the deployment-definition-1.yaml file located at /root/.

=> /root 밑에있는 eployment-definition-1.yaml 파일을 통해서 새로운 배포를 만들어라 

 


There is an issue with the file, so try to fix it.
Check
Complete
Incomplete

Name: deployment-1

=> 쿠버네티스 관련 명령어를 사용하면서 리눅시 관련 명령어를 쓸 생각을 제대로 못했는데 ... 그게 아니였다

==> 어지간한 리눅스 명령어는 다 먹는다고 생각하면 됨 
.yaml 파일을 수정하고 싶으면 그냥 kubectl 빼고 vi(m)으로 작업해주면 됨 

---
apiVersion: apps/v1
kind: Deployment
=> 소문자 d를 대문자 D로 바꿔줌

metadata:
  name: deployment-1
spec:
  replicas: 2
  selector:
    matchLabels:
      name: busybox-pod
  template:
    metadata:
      labels:
        name: busybox-pod
    spec:
      containers:
      - name: busybox-container
        image: busybox888
        command:
        - sh
        - "-c"
        - echo Hello Kubernetes! && sleep 3600



kubectl apply -f /root/deployment-definition-1.yaml 

=> 설정한 파일을 가지고 배포를 해라

deployment.apps/deployment-1 created


kubectl get deployment
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
frontend-deployment   0/4     4            0           9m31s
deployment-1          0/2     2            0           31s


=> 성공적으로 파일을 가지고 배포를 만든것을 볼 수 있었음




kubectl apply -f /root/deployment-definition-1.yaml 
Error from server (BadRequest): error when creating "/root/deployment-definition-1.yaml": deployment in version "v1" cannot be handled as a Deployment: no kind "deployment" is registered for version "apps/v1" in scheme "k8s.io/apimachinery@v1.27.1-k3s1/pkg/runtime/scheme.go:100"

=> 어떻게 할지 처음에는 감에 안왔는데.. 오류를 뜯어보다보니까 슬슬 감이 왔다 
==> 자세히 오류코드를 뜯어보니까 kind 가 deployment인것은 handle되어질 수 없다고 나와있네



O
Create a new Deployment with the below attributes using your own deployment definition file.

Name: httpd-frontend;
Replicas: 3;
Image: httpd:2.4-alpine



controlplane ~ ✖ pwd
/root

controlplane ~ ➜  ls
deployment-definition-1.yaml
sample.yaml



controlplane ~ ➜  vi httpd-frontend.yaml

controlplane ~ ➜  cat httpd-frontend.yaml 
Name: httpd-frontend;
Replicas: 3;
Image: httpd:2.4-alpine

=> 이따위로 하면 안됨 ㅇㅇ 

piVersion: apps/v1
kind: Deployment
metadata:
  name: httpd-frontend
spec:
  replicas: 3
  selector:
    matchLabels:
      name: httpd-pod
  template:
    metadata:
      labels:
        name: httpd-pod
    spec:
      containers:
      - name: httpd
        image: httpd:2.5-alpine
        command:
        - sh
        - "-c"
        - echo Hello Kubernetes! && sleep 3600

~                                                      
~                                                      
~                                         


controlplane ~ ➜  kubectl apply -f httpd-frontend.yaml deployment.apps/httpd-frontend created

controlplane ~ ➜  kubectl get deployment
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
frontend-deployment   0/4     4            0           21m
deployment-1          0/2     2            0           12m
httpd-frontend        0/3     3            0           14s



=> 와씨 쏘 감동쓰




controlplane ~ ✖ kubectl delete deployment httpd-frontend
deployment.apps "httpd-frontend" deleted

controlplane ~ ➜  kubectl get deploymentNAME                  

READY   UP-TO-DATE   AVAILABLE   AGE
frontend-deployment   0/4     4            0           23m
deployment-1          0/2     2            0           14m

는 설정 잘못해서 다시해야하지만, 그래도 실마리가 보였다


ontrolplane ~ ✖ cat httpd-frontend.yaml 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: httpd-frontend
spec:
  replicas: 3
  selector:
    matchLabels:
      name: httpd-pod
  template:
    metadata:
      labels:
        name: httpd-pod
    spec:
      containers:
      - name: httpd
        image: httpd:2.4-alpine
        command:
        - sh
        - "-c"
        - echo Hello Kubernetes! && sleep 3600



controlplane ~ ➜  kubectl apply -f httpd-frontend.yaml deployment.apps/httpd-frontend created

controlplane ~ ➜  kubectl get deployment
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
frontend-deployment   0/4     4            0           25m
deployment-1          0/2     2            0           16m
httpd-frontend        3/3     3            3           11s





O

info
We have deployed a simple web application. Inspect the PODs and the Services

Wait for the application to fully deploy and view the application using the link called Webapp Portal above your terminal.


ontrolplane ~ ✖ kubectl get podNAME                        

READY   STATUS    RESTARTS   AGE
frontend-58f7796bbb-ftw4p   1/1     Running   0          87s
frontend-58f7796bbb-4z55b   1/1     Running   0          87s
frontend-58f7796bbb-d7mv6   1/1     Running   0          87s
frontend-58f7796bbb-cwz7j   1/1     Running   0          87s


controlplane ~ ✖ kubectl describe pod frontend-58f7796bbb-cwz7j
Name:             frontend-58f7796bbb-cwz7j
Namespace:        default
Priority:         0
Service Account:  default
Node:             controlplane/192.18.55.3
Start Time:       Thu, 12 Oct 2023 10:02:41 +0000
Labels:           name=webapp
                  pod-template-hash=58f7796bbb
Annotations:      <none>
Status:           Running
IP:               10.42.0.11
IPs:
  IP:           10.42.0.11
Controlled By:  ReplicaSet/frontend-58f7796bbb
Containers:
  simple-webapp:
    Container ID:   containerd://859bed058b07f818051855748f810744779397226ef048c575654ef6e4a7bae2
    Image:          kodekloud/webapp-color:v1
    Image ID:       docker.io/kodekloud/webapp-color@sha256:27b1e0cbd55a646824c231c896bf77f8278f2d335c4f2b47cbb258edf8281ceb
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Thu, 12 Oct 2023 10:02:47 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-blnlv (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-blnlv:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  104s  default-scheduler  Successfully assigned default/frontend-58f7796bbb-cwz7j to controlplane
  Normal  Pulling    103s  kubelet            Pulling image "kodekloud/webapp-color:v1"
  Normal  Pulled     99s   kubelet            Successfully pulled image "kodekloud/webapp-color:v1" in 3.471850839s (3.471868179s including waiting)
  Normal  Created    99s   kubelet            Created container simple-webapp
  Normal  Started    98s   kubelet            Started container simple-webapp


O
info
Run the script named curl-test.sh to send multiple requests to test the web application. Take a note of the output.

Execute the script at /root/curl-test.sh.

ontrolplane ~ ➜  ./curl-test.sh 

Hello, Application Version: v1 ; Color: blue OK

x  n개


inspect => decribe => 상세정보봐봐라 



O
Inspect the deployment and identify the current strategy

 
controlplane ~ ✖ kubectl describe deploy frontend
Name:                   frontend
Namespace:              default
CreationTimestamp:      Thu, 12 Oct 2023 10:02:41 +0000
Labels:                 <none>
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               name=webapp
Replicas:               4 desired | 4 updated | 4 total | 4 available | 0 unavailable
StrategyType:           RollingUpdate
=> rolling update => 무중단배포

MinReadySeconds:        20
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  name=webapp
  Containers:
   simple-webapp:
    Image:        kodekloud/webapp-color:v1
    Port:         8080/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   frontend-58f7796bbb (4/4 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  6m22s  deployment-controller  Scaled up replica set frontend-58f7796bbb to 4




controlplane ~ ✖ alias kubectl to k
alias kubectl='k3s kubectl'
-bash: alias: to: not found
alias k='kubectl'



controlplane ~ ✖ k get deploy
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
frontend   4/4     4            4           13m

=> 일단 확인해보면 여러문장을 하는건 안되는거 같고
=> 잘 찾아봐야겟지만? 단어 하나를 알파벳 하나로 줄이는 정도로 일단 사용해야할듯?




O
Let us try that. Upgrade the application by setting the image on the deployment to kodekloud/webapp-color:v2

Do not delete and re-create the deployment. Only set the new image name for the existing deployment.



controlplane ~ ✖ k edit deployment frontend

=> 실행되고 있는 배포에 대한 yaml파일을 수정할 수 있음






O
Change the deployment strategy to Recreate

Delete and re-create the deployment if necessary. Only update the strategy type for the existing deployment.
Check
Complete
Incomplete

Deployment Name: frontend


Deployment Image: kodekloud/webapp-color:v2


Strategy: Recreate




hint
Run the command kubectl edit deployment frontend and modify the required field. Make sure to delete the properties of rollingUpdate as well, set at strategy.rollingUpdate
=> strategy라고 되어있는 부분에 대한 이름만 바꾸고 진행헸는데, 그게 아니라 관련된 것을 확실하게 지우고 실행하라 => 일단 문제 없이 edit이 잘 됐음


controlplane ~ ✖ k edit deploy frontend
deployment.apps/frontend edited