반응형

 

 

2023.10.03

드디어 작년부터 준비하던 CKA시험을 응시하고 취득을 완료했다.

22년 사이버 먼데이때 50% 할인을 받아서 신청을했다. 정가 $ 395달러 기준 ($ 197.50)

생각보다 어렵지 않았던거 같다.

 

 

  •  접수 사이트

https://training.linuxfoundation.org/certification/certified-kubernetes-administrator-cka/

 

 

 

 

 

 

공부 참고 사이트

1. 뭄샤드 강의

2. kubernets 공식 문서

3. KodeKloud(뭄샤드 실습)

4. Killer.sh (자격증 접수하면 2회 가능, 마지막 날 풀어보기 반복, 실제 시험보다 어려움)

 

 

 

중요하지않지만 간단한 꿀팁 !

1. 간단하게 배점 먹고들어갈 수 있는 jsonpath 사용법 배우기

2. kubectl cheat sheet 어느정도 배우고 가기

 - https://kubernetes.io/docs/reference/kubectl/cheatsheet/

3. 북마크를 이용해서 쿠버네티스 문서 yaml 파일 빨리 만들기

4. 시험 시작할때 무조건 context 수정하기 꼭! 꼭! 꼭!

5. 시험 원격화면이 굉장히 작으므로 해상도 큰거 사용하기

6. 시험환경은 많이 개선되어서 생각보다 빠르고 쾌적

 

 

시험에 나온 문제 (기억나는 부분만...)

1. 현재 사용가능한 Node들의 정보 출력 및 저장 ( Node Name, Taint=NoSchedule, 사용가능 list)

2. 현재 사용중인 Pods중에 특정 Label 가지고있는 Pods 출력 및 저장

3. Stateful Scale size 조절 

4. Deploy Scale Size 조절, Deploy된 Pods들의 image update

5. 현재 사용중인 Controlplane node만 Cluster upgrade 하기 (Kubeadm, Kubelet, Kubectl)

6. 하나의 Pod에서 2개 Container사용 (Sidecar, EmptyDir)

7. Deployment 생성, Pods 생성 간단한 생성 등등..

8. 사용자 Rule, Rulebinding, Serviceaccount 생성 및 binding 작업

9. ClusterRule, ClusterRulebinding 연동 설정

10. Storage 관련 Pod에 PV, PVC 생성 및 연동

11. 배점이 제일 높은 Node Troubleshooting 문제

 

 

 

다음 목표는 11월 말까지 CKAD 취득 !!

레쓰꼬  !!

 

 

 

반응형
반응형

 

2023.06.06

★ 클러스터에 몇 개의 clusterrole이 정의되어 있나요?

-> 69개

controlplane ~ ➜  kubectl get clusterrole --no-headers | wc -l
69

controlplane ~ ➜

 

 

클러스터에 몇 개의 clusterrolebindings이 존재하나요?

-> 54개

controlplane ~ ➜  kubectl get clusterrolebindings --no-headers | wc -l
54

controlplane ~ ➜

 

 

cluster-admin clusterrole은 어떤 네임스페이스에 속하나요?

-> 클러스터 역할은 클러스터 전체에 속하며 네임스페이스의 일부가 아니다.

controlplane ~ ➜  kubectl describe clusterrole cluster-admin 
Name:         cluster-admin
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
  *.*        []                 []              [*]
             [*]                []              [*]

controlplane ~ ➜

 

 

cluster-admin 역할은 어떤 사용자/그룹에 바인딩되나요?

-> Group  system:masters

controlplane ~ ➜  kubectl describe clusterrolebinding cluster-admin 
Name:         cluster-admin
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
Role:
  Kind:  ClusterRole
  Name:  cluster-admin
Subjects:
  Kind   Name            Namespace
  ----   ----            ---------
  Group  system:masters  

controlplane ~ ➜

 

 

cluster-admin 역할은 어떤 수준의 권한을 부여하나요?

-> 클러스터의 모든 리소스에 대해 모든 작업 수행

controlplane ~ ➜  kubectl describe clusterrole cluster-admin 
Name:         cluster-admin
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
  *.*        []                 []              [*]
             [*]                []              [*]

controlplane ~ ➜

 

 

새로운 사용자 미셸이 팀에 합류했습니다. 그녀가 노드에 액세스할 수 있도록 필요한 ClusterRoles 및 ClusterRoleBinding을 만듭니다.

-> 기존 cluster-admin 을 yaml 파일로 복사

controlplane ~ ➜ kubectl get clusterrole cluster-admin -o yaml > michelle.yaml
controlplane ~ ➜

-> 복사한 yaml 파일 확인

controlplane ~ ➜  cat michelle.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  creationTimestamp: "2023-06-06T07:08:22Z"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: cluster-admin
  resourceVersion: "68"
  uid: 0d93b435-10ba-475e-ae77-d46510f93d75
rules:
- apiGroups:
  - '*'
  resources:
  - '*'
  verbs:
  - '*'
- nonResourceURLs:
  - '*'
  verbs:
  - '*'

-> 복사한 yaml 파일 수정

controlplane ~ ➜  cat michelle.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: node-admin
rules:
- apiGroups: [""]
  resources: ["nodes"]
  verbs: ["get", "watch", "list", "create", "delete"]

controlplane ~ ➜

->  새로운 clusterrole 생성

controlplane ~ ➜  kubectl create -f michelle.yaml 
clusterrole.rbac.authorization.k8s.io/node-admin created

controlplane ~ ➜

-> clusterrolebinding 복사

controlplane ~ ➜  kubectl get clusterrolebinding system:basic-user -o yaml > michelle-binding.yaml

controlplane ~ ➜

-> 내용 확인

controlplane ~ ➜  cat michelle-binding.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  creationTimestamp: "2023-06-06T07:08:24Z"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: system:basic-user
  resourceVersion: "138"
  uid: 8ec82b9d-2758-4347-a0d2-25ac08eb17b6
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:basic-user
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: Group
  name: system:authenticated

controlplane ~ ➜

-> 내용 수정

controlplane ~ ➜  cat michelle-binding.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: michelle-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: node-admin
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: michelle

controlplane ~ ➜

-> clusterrolebinding 생성

controlplane ~ ➜  kubectl create -f michelle-binding.yaml 
clusterrolebinding.rbac.authorization.k8s.io/michelle-binding created

controlplane ~ ➜

 

 

미셸의 책임이 커지면서 이제 그녀는 스토리지도 담당하게 됩니다. 그녀가 스토리지에 액세스할 수 있도록 필요한 ClusterRoles과 clusterrolebinding을 생성한다.

-> stroage-admin 룰 생성

controlplane ~ ➜  kubectl create clusterrole storage-admin --resource=persistentvolumes,storageclasses --verb=get,list,create,delete,watch
clusterrole.rbac.authorization.k8s.io/storage-admin created

controlplane ~ ➜

-> 룰 확인

controlplane ~ ➜  kubectl describe clusterrole storage-admin 
Name:         storage-admin
Labels:       <none>
Annotations:  <none>
PolicyRule:
  Resources                      Non-Resource URLs  Resource Names  Verbs
  ---------                      -----------------  --------------  -----
  persistentvolumes              []                 []              [get list create delete watch]
  storageclasses.storage.k8s.io  []                 []              [get list create delete watch]

controlplane ~ ➜

-> michelle-stroage-admin 생성

controlplane ~ ➜  kubectl create clusterrolebinding michelle-storage-admin --user=michelle --clusterrole=storage-admin

clusterrolebinding.rbac.authorization.k8s.io/michelle-storage-admin created

controlplane ~ ➜

-> 룰 확인

controlplane ~ ➜  kubectl describe clusterrolebindings michelle-storage-admin 
Name:         michelle-storage-admin
Labels:       <none>
Annotations:  <none>
Role:
  Kind:  ClusterRole
  Name:  storage-admin
Subjects:
  Kind  Name      Namespace
  ----  ----      ---------
  User  michelle  

controlplane ~ ➜

 

반응형
반응형

 

 

2023.05.20

★ 클러스터에서 실행 중인 ETCD의 버전은 무엇인가요?

-> etcd-version : 3.5.6

controlplane ~ ➜  kubectl -n kube-system logs etcd-controlplane | grep -i 'etcd-version'
{"level":"info","ts":"2023-05-20T05:14:33.291Z","caller":"embed/etcd.go:306","msg":"starting an etcd server","etcd-version":"3.5.6","git-sha":"cecbe35ce","go-version":"go1.16.15","go-os":"linux","go-arch":"amd64","max-cpu-set":36,"max-cpu-available":36,"member-initialized":false,"name":"controlplane","data-dir":"/var/lib/etcd","wal-dir":"","wal-dir-dedicated":"","member-dir":"/var/lib/etcd/member","force-new-cluster":false,"heartbeat-interval":"100ms","election-timeout":"1s","initial-election-tick-advance":true,"snapshot-count":10000,"max-wals":5,"max-snapshots":5,"snapshot-catchup-entries":5000,"initial-advertise-peer-urls":["https://192.6.237.3:2380"],"listen-peer-urls":["https://192.6.237.3:2380"],"advertise-client-urls":["https://192.6.237.3:2379"],"listen-client-urls":["https://127.0.0.1:2379","https://192.6.237.3:2379"],"listen-metrics-urls":["http://127.0.0.1:2381"],"cors":["*"],"host-whitelist":["*"],"initial-cluster":"controlplane=https://192.6.237.3:2380","initial-cluster-state":"new","initial-cluster-token":"etcd-cluster","quota-backend-bytes":2147483648,"max-request-bytes":1572864,"max-concurrent-streams":4294967295,"pre-vote":true,"initial-corrupt-check":true,"corrupt-check-time-interval":"0s","compact-check-time-enabled":false,"compact-check-time-interval":"1m0s","auto-compaction-mode":"periodic","auto-compaction-retention":"0s","auto-compaction-interval":"0s","discovery-url":"","discovery-proxy":"","downgrade-check-interval":"5s"}

controlplane ~ ➜

 

 

★ controlplane node에서 ETCD 클러스터에 연결할 수 있는 주소는 어디인가요?

 ->  https://127.0.0.1:2379

controlplane ~ ➜  kubectl -n kube-system describe pod etcd-controlplane | grep -i 'listen-client-url'
      --listen-client-urls=https://127.0.0.1:2379,https://192.6.237.3:2379

controlplane ~ ➜

 

 

★ ETCD 서버 인증서 파일은 어디에 있나요?

 -> --cert-file=/etc/kubernetes/pki/etcd/server.crt

controlplane ~ ➜  kubectl -n kube-system describe pod etcd-controlplane | grep -i 'cert-file'
      --cert-file=/etc/kubernetes/pki/etcd/server.crt
      --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt

controlplane ~ ➜

 

 

★ ETCD CA 인증서 파일은 어디에 있나요?

 -> --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt

controlplane ~ ➜  kubectl -n kube-system describe pod etcd-controlplane | grep -i 'ca-file'
      --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
      --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt

controlplane ~ ➜

 

 

★ 클러스터의 master node는 오늘 밤에 재부팅이 예정되어 있습니다. 문제가 발생할 것으로 예상되지는 않지만 필요한 백업을 수행해야 합니다. 기본 제공 스냅샷 기능을 사용하여 ETCD 데이터베이스의 스냅샷을 만듭니다.

ETCDCTL_API=3 etcdctl --endpoints=https://[127.0.0.1]:2379 \
 --cacert=/etc/kubernetes/pki/etcd/ca.crt \
 --cert=/etc/kubernetes/pki/etcd/server.crt \
 --key=/etc/kubernetes/pki/etcd/server.key \
 snapshot save /opt/snapshot-pre-boot.db

controlplane ~ ➜ ETCDCTL_API=3 etcdctl --endpoints=https://[127.0.0.1]:2379 \
> --cacert=/etc/kubernetes/pki/etcd/ca.crt \
> --cert=/etc/kubernetes/pki/etcd/server.crt \
> --key=/etc/kubernetes/pki/etcd/server.key \
> snapshot save /opt/snapshot-pre-boot.db
Snapshot saved at /opt/snapshot-pre-boot.db

controlplane ~ ➜  ls /opt/
cni  containerd  snapshot-pre-boot.db

controlplane ~ ➜

 

 

★ 재부팅 후 마스터 노드가 다시 온라인 상태가 되었지만 애플리케이션에 액세스할 수 없습니다. 클러스터의 애플리케이션 상태를 확인하세요. 무슨 문제인가요?

- 배포가 없습니다.
- 서비스가 존재하지 않음
- 파드가 없음
 위의 모든 것

 

 

 

★ 백업 파일을 사용하여 클러스터의 원래 상태를 복원합니다.

controlplane ~ ➜  ETCDCTL_API=3 etcdctl  --data-dir /var/lib/etcd-from-backup \
> snapshot restore /opt/snapshot-pre-boot.db
2023-05-20 02:06:58.280313 I | mvcc: restore compact to 2461
2023-05-20 02:06:58.287347 I | etcdserver/membership: added member 8e9e05c52164694d [http://localhost:2380] to cluster cdf818194e3a8c32

 

 

반응형
반응형

 

 

 

 

 

 

 

2023.05.20

★ Cluster 버전 확인

 -> v1.25.0

controlplane ~ ➜  kubectl get nodes 
NAME           STATUS   ROLES           AGE    VERSION
controlplane   Ready    control-plane   116m   v1.25.0
node01         Ready    <none>          116m   v1.25.0

controlplane ~ ➜

 

 

★ Worker node인 node는 어떤 노드인가요 ?

 -> Taints 가 없으니 다 Worker node

controlplane ~ ➜  kubectl describe nodes controlplane | grep Taints
Taints:             <none>

controlplane ~ ➜  kubectl describe nodes node01 | grep Taints
Taints:             <none>

 

 

★ deploy되는 pods는 어떤 node에 올라가나요 ?

 -> node01, controlplane

controlplane ~ ➜  kubectl get pods -o wide
NAME                    READY   STATUS    RESTARTS   AGE   IP           NODE           NOMINATED NODE   READINESS GATES
blue-5db6db69f7-94bd2   1/1     Running   0          14m   10.244.1.4   node01         <none>           <none>
blue-5db6db69f7-d4ckd   1/1     Running   0          14m   10.244.1.2   node01         <none>           <none>
blue-5db6db69f7-fgrvp   1/1     Running   0          14m   10.244.1.3   node01         <none>           <none>
blue-5db6db69f7-fkvdv   1/1     Running   0          14m   10.244.0.5   controlplane   <none>           <none>
blue-5db6db69f7-kcnkl   1/1     Running   0          14m   10.244.0.4   controlplane   <none>           <none>

 

 

★ 클러스터를 업그레이드하는 작업을 수행해야 합니다. 애플리케이션에 접속하는 사용자에게 영향을 미치지 않아야 하며 새 VM을 프로비저닝할 수 없습니다. 클러스터를 업그레이드하기 위해 어떤 방법을 사용하시겠습니까?

 -> Worker node를 다른 노드로 이동하면서 한 번에 한 노드씩 업그레이드

 

 

★ 현재 쿠버네티스의 안정적인 최신 버전은 무엇인가요?

 -> v1.27.2

controlplane ~ ➜  kubeadm upgrade plan
[upgrade/config] Making sure the configuration is correct:
[upgrade/config] Reading configuration from the cluster...
[upgrade/config] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[preflight] Running pre-flight checks.
[upgrade] Running cluster health checks
[upgrade] Fetching available versions to upgrade to
[upgrade/versions] Cluster version: v1.25.0
[upgrade/versions] kubeadm version: v1.25.0
I0519 23:10:12.713401   17274 version.go:256] remote version is much newer: v1.27.2; falling back to: stable-1.25
[upgrade/versions] Target version: v1.25.10
[upgrade/versions] Latest version in the v1.25 series: v1.25.10

 

 

★ 현재 버전의 kubeadm 도구가 설치된 상태에서 업그레이드할 수 있는 최신 버전은 무엇인가요?

 -> v1.25.10

controlplane ~ ➜  kubeadm upgrade plan
[upgrade/config] Making sure the configuration is correct:
[upgrade/config] Reading configuration from the cluster...
[upgrade/config] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[preflight] Running pre-flight checks.
[upgrade] Running cluster health checks
[upgrade] Fetching available versions to upgrade to
[upgrade/versions] Cluster version: v1.25.0
[upgrade/versions] kubeadm version: v1.25.0
I0519 23:10:12.713401   17274 version.go:256] remote version is much newer: v1.27.2; falling back to: stable-1.25
[upgrade/versions] Target version: v1.25.10
[upgrade/versions] Latest version in the v1.25 series: v1.25.10

Components that must be upgraded manually after you have upgraded the control plane with 'kubeadm upgrade apply':
COMPONENT   CURRENT       TARGET
kubelet     2 x v1.25.0   v1.25.10

Upgrade to the latest version in the v1.25 series:

COMPONENT                 CURRENT   TARGET
kube-apiserver            v1.25.0   v1.25.10
kube-controller-manager   v1.25.0   v1.25.10
kube-scheduler            v1.25.0   v1.25.10
kube-proxy                v1.25.0   v1.25.10
CoreDNS                   v1.9.3    v1.9.3
etcd                      3.5.4-0   3.5.4-0

You can now apply the upgrade by executing the following command:

        kubeadm upgrade apply v1.25.10

Note: Before you can perform this upgrade, you have to update kubeadm to v1.25.10.

 

 

 

★ controlplane node를 업그레이드할 것입니다. 컨트롤 플레인 노드에서 워크로드를 비우고 예약 불가능으로 설정해주세요.

controlplane ~ ✖ kubectl drain controlplane --ignore-daemonsets 
node/controlplane already cordoned
Warning: ignoring DaemonSet-managed Pods: kube-flannel/kube-flannel-ds-qljgv, kube-system/kube-proxy-xkrtl
evicting pod kube-system/coredns-565d847f94-8ldgw
evicting pod default/blue-5db6db69f7-jhn5p
evicting pod default/blue-5db6db69f7-6pkjn
evicting pod kube-system/coredns-565d847f94-2bbdc
pod/blue-5db6db69f7-jhn5p evicted
pod/blue-5db6db69f7-6pkjn evicted
pod/coredns-565d847f94-2bbdc evicted
pod/coredns-565d847f94-8ldgw evicted
node/controlplane drained

controlplane ~ ➜

 

 

★ Controlplane node 업그레이드

controlplane ~ ➜  apt update
Get:1 https://packages.cloud.google.com/apt kubernetes-xenial InRelease [8,993 B]    
Hit:2 https://download.docker.com/linux/ubuntu focal InRelease
...

controlplane ~ ➜  apt-get install kubeadm=1.26.0-00
Reading package lists... Done
Building dependency tree       
Reading state information... Done
...

controlplane ~ ➜  kubeadm upgrade apply v1.26.0
[upgrade/config] Making sure the configuration is correct:
[upgrade/config] Reading configuration from the cluster...
...

controlplane ~ ➜  kubectl get nodes 
NAME           STATUS                     ROLES           AGE   VERSION
controlplane   Ready,SchedulingDisabled   control-plane   85m   v1.26.0
node01         Ready                      <none>          84m   v1.25.0

controlplane ~ ➜

 

 

★ Controlplane node에서 예약 가능으로 설정하세요.

controlplane ~ ✖ kubectl uncordon controlplane 
node/controlplane uncordoned

 

★ node01를 업그레이드할 것입니다. 워크로드를 비우고 예약 불가능으로 설정해주세요.

 -> drain하게되면 node에 있던 pod들은 이동한다.

controlplane ~ ➜  kubectl drain node01 --ignore-daemonsets 
node/node01 cordoned
Warning: ignoring DaemonSet-managed Pods: kube-flannel/kube-flannel-ds-2stnt, kube-system/kube-proxy-n5hmd
evicting pod kube-system/coredns-787d4945fb-lqjjv
evicting pod default/blue-5db6db69f7-225hb
evicting pod default/blue-5db6db69f7-c7ptb
evicting pod default/blue-5db6db69f7-gkbz4
evicting pod default/blue-5db6db69f7-r4rvt
evicting pod default/blue-5db6db69f7-tv2p9
evicting pod kube-system/coredns-787d4945fb-kr6xw
pod/blue-5db6db69f7-gkbz4 evicted
pod/blue-5db6db69f7-tv2p9 evicted
pod/blue-5db6db69f7-r4rvt evicted
pod/blue-5db6db69f7-225hb evicted
pod/blue-5db6db69f7-c7ptb evicted
pod/coredns-787d4945fb-kr6xw evicted
pod/coredns-787d4945fb-lqjjv evicted
node/node01 drained

controlplane ~ ➜  kubectl get pods -o wide
NAME                    READY   STATUS    RESTARTS   AGE   IP            NODE           NOMINATED NODE   READINESS GATES
blue-5db6db69f7-5sld2   1/1     Running   0          17s   10.244.0.7    controlplane   <none>           <none>
blue-5db6db69f7-9c4w2   1/1     Running   0          17s   10.244.0.12   controlplane   <none>           <none>
blue-5db6db69f7-9mhbr   1/1     Running   0          17s   10.244.0.9    controlplane   <none>           <none>
blue-5db6db69f7-j7tgx   1/1     Running   0          17s   10.244.0.11   controlplane   <none>           <none>
blue-5db6db69f7-p98g5   1/1     Running   0          17s   10.244.0.10   controlplane   <none>           <none>

controlplane ~ ➜

 

 

★ node01 업그레이드

controlplane ~ ➜  ssh node01

root@node01 ~ ➜  apt-get update
Get:2 http://archive.ubuntu.com/ubuntu focal InRelease [265 kB]                      
Get:3 https://download.docker.com/linux/ubuntu focal InRelease [57.7 kB]             
Get:1 https://packages.cloud.google.com/apt kubernetes-xenial InRelease [8993 B]
...
root@node01 ~ ➜  apt-get install kubeadm=1.26.0-00
Reading package lists... Done
Building dependency tree       
Reading state information... Done
...
oot@node01 ~ ➜  kubeadm upgrade node
[upgrade] Reading configuration from the cluster...
[upgrade] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[preflight] Running pre-flight checks
...
root@node01 ~ ➜  apt-get install kubelet=1.26.0-00
Reading package lists... Done
Building dependency tree       
Reading state information... Done
...
root@node01 ~ ➜  systemctl daemon-reload 
root@node01 ~ ➜  systemctl restart kubelet.service 

controlplane ~ ➜  kubectl get node
NAME           STATUS                        ROLES           AGE    VERSION
controlplane   Ready                         control-plane   118m   v1.26.0
node01         NotReady,SchedulingDisabled   <none>          117m   v1.26.0

controlplane ~ ➜

 

 

★ node01 노드를 예약 가능으로 설정하세요.

controlplane ~ ➜  kubectl uncordon node01
node/node01 uncordoned

 

반응형
반응형

 

 

 

2023.05.17

★ node 갯수 확인

controlplane ~ ➜  kubectl get nodes 
NAME           STATUS   ROLES           AGE   VERSION
controlplane   Ready    control-plane   17m   v1.26.0
node01         Ready    <none>          17m   v1.26.0

controlplane ~ ➜

 

 

★ namespace가 default인 deploy를 찾아라

controlplane ~ ➜  kubectl get deployments.apps --namespace default 
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
blue   3/3     3            3           33s

controlplane ~ ➜

 

 

★ node관리를 위해 node01을 제거해야 한다. 애플리케이션의 노드를 비우고 예약 불가능으로 표시해주세요.

controlplane ~ ➜  kubectl drain node01 --ignore-daemonsets 
node/node01 cordoned
Warning: ignoring DaemonSet-managed Pods: kube-flannel/kube-flannel-ds-bjcqz, kube-system/kube-proxy-l6ln5
evicting pod default/blue-987f68cb5-jt66v
evicting pod default/blue-987f68cb5-hw99q
pod/blue-987f68cb5-hw99q evicted
pod/blue-987f68cb5-jt66v evicted
node/node01 drained

controlplane ~ ➜

 

★ node관리 작업이 끝났다. 노드 node01을 다시 스케줄링할 수 있도록 구성

controlplane ~ ➜ kubectl uncordon node01 
node/node01 uncordoned

controlplane ~ ➜

 

 

★ uncordon으로 노드 node01을 스케줄링 했지만 pods가 생성되지 않습니다. 원인은?

 -> 노드에서 uncordon 명령을 실행해도 노드의 파드가 자동으로 스케줄링되지는 않습니다. 

 -> 새 파드가 생성되면 node01에 배치됩니다.

 

 

★ node01을 다시 drain 상태로 만들려고하는데 에러가 발생한다. 원인은?

 -> node01에 pod가 예약된 것을 볼 수 있다.
-> 해당 경우 drain 명령은 작동하지 않는다. 노드를 강제로 drain하려면 이제 --force 옵션을 사용해야 한다

controlplane ~ ➜  kubectl get pods -o wide
NAME                   READY   STATUS    RESTARTS   AGE     IP           NODE           NOMINATED NODE   READINESS GATES
blue-987f68cb5-gbbq8   1/1     Running   0          11m     10.244.0.5   controlplane   <none>           <none>
blue-987f68cb5-gwvqs   1/1     Running   0          11m     10.244.0.4   controlplane   <none>           <none>
blue-987f68cb5-njps9   1/1     Running   0          11m     10.244.0.6   controlplane   <none>           <none>
hr-app                 1/1     Running   0          3m29s   10.244.1.4   node01         <none>           <none>

controlplane ~ ➜

 

★ node01 강제로 drain 했을 경우 hr-app pod는 어떻게 될까?

 -> 사라져 버린다 ~

controlplane ~ ➜  kubectl drain node01 --ignore-daemonsets --force 
node/node01 already cordoned
Warning: deleting Pods that declare no controller: default/hr-app; ignoring DaemonSet-managed Pods: kube-flannel/kube-flannel-ds-xhg7x, kube-system/kube-proxy-96vtg
evicting pod default/hr-app
pod/hr-app evicted
node/node01 drained

controlplane ~ ➜
controlplane ~ ➜  kubectl get pods -o wide
NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE           NOMINATED NODE   READINESS GATES
blue-987f68cb5-gbbq8   1/1     Running   0          15m   10.244.0.5   controlplane   <none>           <none>
blue-987f68cb5-gwvqs   1/1     Running   0          15m   10.244.0.4   controlplane   <none>           <none>
blue-987f68cb5-njps9   1/1     Running   0          15m   10.244.0.6   controlplane   <none>           <none>

controlplane ~ ➜

 

★ hr-app pod는 굉장히 중요하므로 복구한다음 위험한 node01 노드에 배포되지 않게 설정해야합니다.

controlplane ~ ➜  kubectl get pods -o wide
NAME                      READY   STATUS    RESTARTS   AGE   IP           NODE           NOMINATED NODE   READINESS GATES
blue-987f68cb5-gbbq8      1/1     Running   0          16m   10.244.0.5   controlplane   <none>           <none>
blue-987f68cb5-gwvqs      1/1     Running   0          16m   10.244.0.4   controlplane   <none>           <none>
blue-987f68cb5-njps9      1/1     Running   0          16m   10.244.0.6   controlplane   <none>           <none>
hr-app-66c4c9c67f-78hm7   1/1     Running   0          47s   10.244.1.5   node01         <none>           <none>

controlplane ~ ➜  
controlplane ~ ➜  kubectl cordon node01 
node/node01 cordoned

controlplane ~ ➜

 

 

반응형
반응형

 

 

 

init 컨테이너

초기화 컨테이너는 파드의 앱 컨테이너들이 실행되기 전에 실행되는 특수한 컨테이너이다. 초기화 컨테이너는 앱 이미지에는 없는 유틸리티 또는 설정 스크립트 등을 포함할 수 있다.

초기화 컨테이너는 containers 배열(앱 컨테이너를 기술하는)과 나란히 파드 스펙에 명시할 수 있다.

 

init 컨테이너 이해하기

파드는 앱들을 실행하는 다수의 컨테이너를 포함할 수 있고, 또한 앱 컨테이너 실행 전에 동작되는 하나 이상의 초기화 컨테이너도 포함할 수 있다.

다음의 경우를 제외하면, 초기화 컨테이너는 일반적인 컨테이너와 매우 유사하다.

  • 초기화 컨테이너는 항상 완료를 목표로 실행된다.
  • 각 초기화 컨테이너는 다음 초기화 컨테이너가 시작되기 전에 성공적으로 완료되어야 한다.

만약 파드의 초기화 컨테이너가 실패하면, kubelet은 초기화 컨테이너가 성공할 때까지 반복적으로 재시작한다. 그러나, 만약 파드의 restartPolicy 를 절대 하지 않음(Never)으로 설정하고, 해당 파드를 시작하는 동안 초기화 컨테이너가 실패하면, 쿠버네티스는 전체 파드를 실패한 것으로 처리한다.

컨테이너를 초기화 컨테이너로 지정하기 위해서는, 파드 스펙에 initContainers 필드를 container 항목(앱 container 필드 및 내용과 유사한)들의 배열로서 추가한다. 컨테이너에 대한 더 상세한 사항은 API 레퍼런스를 참고한다.

초기화 컨테이너의 상태는 컨테이너 상태의 배열(.status.containerStatuses 필드와 유사)로 .status.initContainerStatuses 필드에 반환된다.

일반적인 컨테이너와의 차이점

초기화 컨테이너는 앱 컨테이너의 리소스 상한(limit), 볼륨, 보안 세팅을 포함한 모든 필드와 기능을 지원한다. 그러나, 초기화 컨테이너를 위한 리소스 요청량과 상한은 리소스에 문서화된 것처럼 다르게 처리된다.

또한, 초기화 컨테이너는 lifecycle, livenessProbe, readinessProbe 또는 startupProbe 를 지원하지 않는다. 왜냐하면 초기화 컨테이너는 파드가 준비 상태가 되기 전에 완료를 목표로 실행되어야 하기 때문이다.

만약 다수의 초기화 컨테이너가 파드에 지정되어 있다면, kubelet은 해당 초기화 컨테이너들을 한 번에 하나씩 실행한다. 각 초기화 컨테이너는 다음 컨테이너를 실행하기 전에 꼭 성공해야 한다. 모든 초기화 컨테이너들이 실행 완료되었을 때, kubelet은 파드의 애플리케이션 컨테이너들을 초기화하고 평소와 같이 실행한다

 

 

init 컨테이너를 이용하여 pod 생성

# YAML 파일을 이용하여 init 컨테이너 생성
master@master:~$ cat init-container.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: init-container
spec:
  containers: 
  - name: busybox
    image: k8s.gcr.io/busybox
    command: [ "ls" ]
    args: [ "/work-dir/moby" ]
    volumeMounts:
    - name: workdir
      mountPath: /work-dir
  initContainers:
  - name: git
    image: alpine/git
    command: ["sh"]
    args:
    - "-c"
    - "git clone https://github.com/moby/moby.git \
          /work-dir/moby"
    volumeMounts:
    - name: workdir
      mountPath: "/work-dir"
  volumes:
  - name: workdir
    emptyDir: {}
master@master:~$ 

master@master:~$ kubectl apply -f init-container.yaml 
pod/init-container created
master@master:~$ 

master@master:~$ kubectl get pod
NAME             READY   STATUS     RESTARTS   AGE
init-container   0/1     Init:0/1   0          10s
master@master:~$ 

master@master:~$ kubectl logs init-container 
Error from server (BadRequest): container "busybox" in pod "init-container" is waiting to start: PodInitializing

master@master:~$ kubectl logs init-container -c git
Cloning into '/work-dir/moby'...

master@master:~$ kubectl logs init-container -c git -f
Cloning into '/work-dir/moby'...
Updating files: 100% (7258/7258), done.
master@master:~$ 

master@master:~$ kubectl logs init-container 
AUTHORS
CHANGELOG.md
CONTRIBUTING.md
Dockerfile
Dockerfile.e2e
Dockerfile.simple
Dockerfile.windows
Jenkinsfile
LICENSE
MAINTAINERS
Makefile
NOTICE
README.md
ROADMAP.md
SECURITY.md
TESTING.md
VENDORING.md
api
builder
cli
client
cmd
codecov.yml
container
contrib
daemon
distribution
docker-bake.hcl
dockerversion
docs
errdefs
hack
image
integration
integration-cli
internal
layer
libcontainerd
libnetwork
oci
opts
pkg
plugin
profiles
project
quota
reference
registry
reports
restartmanager
rootless
runconfig
testutil
vendor
vendor.mod
vendor.sum
volume
master@master:~$

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/concepts/workloads/pods/init-containers/

 

 

반응형
반응형

 

 

 

 

 

 

파드안에 두개이상 컨테이너 생성 및 확인

YAML파일안에 sleep 5초를 준 이유는 Pod 안에 컨테이너가 동시에 시작되면 nginx 컨테이너에 오류가 발생할 수 있기에 mynginx 컨테이너 먼저 러닝상태가 되면 jinsunginx 컨테이너가 동작할 수 있게 옵션을 준 것입니다.

# 파드안에 두개의 컨테이너 생성하는 YAML파일 생성
master@master:~$ cat two-container.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: mynginx
spec:
  containers: 
  - name: mynginx
    image: nginx
  - name: jinsunginx
    image: curlimages/curl
    command: ["sh"]
    args: 
    - "-c"
    - "sleep 5 && curl localhost"
master@master:~$ 

master@master:~$ kubectl apply -f two-container.yaml 
pod/mynginx created
master@master:~$ 

master@master:~$ kubectl get pod
NAME      READY   STATUS    RESTARTS   AGE
mynginx   1/2     Running   0          18s
master@master:~$

# 그냥 pod의 logs를 조회하면 컨테이너를 선택하라는 문구가 나온다.
master@master:~$ kubectl logs mynginx 
error: a container name must be specified for pod mynginx, choose one of: [mynginx jinsunginx]

# 두개의 컨테이너가 있을떄는 -c 옵션을 사용한다.
master@master:~$ kubectl logs mynginx -c mynginx 
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/08/09 12:59:15 [notice] 1#1: using the "epoll" event method
2022/08/09 12:59:15 [notice] 1#1: nginx/1.23.1
2022/08/09 12:59:15 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2022/08/09 12:59:15 [notice] 1#1: OS: Linux 4.15.0-189-generic
2022/08/09 12:59:15 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/08/09 12:59:15 [notice] 1#1: start worker processes
2022/08/09 12:59:15 [notice] 1#1: start worker process 32
2022/08/09 12:59:15 [notice] 1#1: start worker process 33
2022/08/09 12:59:15 [notice] 1#1: start worker process 34
2022/08/09 12:59:15 [notice] 1#1: start worker process 35
127.0.0.1 - - [09/Aug/2022:12:59:28 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.84.0-DEV" "-"
127.0.0.1 - - [09/Aug/2022:12:59:36 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.84.0-DEV" "-"
127.0.0.1 - - [09/Aug/2022:12:59:58 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.84.0-DEV" "-"
master@master:~$

master@master:~$ kubectl logs mynginx 
error: a container name must be specified for pod mynginx, choose one of: [mynginx jinsunginx]
master@master:~$ kubectl logs mynginx -c jinsunginx 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   615  100   615    0     0  1002k      0 --:--:-- --:--:-- --:--:--  600k
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
master@master:~$

 

 

 

참고자료

https://kubernetes.io/ko/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume/

 

반응형

+ Recent posts