시험 준비를 하며

 

- udemy 동영상 유료 강좌 수강

udemy(https://www.udemy.com/course/certified-kubernetes-administrator-with-practice-tests/learn/lecture/14296562#overview)

-- 섹션별로 강의가 진행되고 섹션이 완료되면 섹션별 테스트가 제공됩니다.

 

강의에 대한 내용이 정리되어 있는 사이트

https://github.com/kodekloudhub/certified-kubernetes-administrator-course

- "따라하며 배우는 쿠버네티스" 유투브 동영상 시청

 

시험시간 : 2 hours

 

참고 사이트 

KodeKloud(https://kodekloud.com)

쿠버네티스 사이트 : kubernetes.io document 참조

 

Certified Kubernetes Administrator: https://www.cncf.io/certification/cka/

Exam Curriculum (Topics): https://github.com/cncf/curriculum

Candidate Handbook: https://www.cncf.io/certification/candidate-handbook

Exam Tips: http://training.linuxfoundation.org/go//Important-Tips-CKA-CKAD

 

Use the code - ******* - while registering for the CKA or CKAD exams at Linux Foundation to get a 15% discount.

=> udemy 강의 수강 시 15% 할인을 받을 수 있는 코드를 제공

 

오픈북이기 때문에, 북마크 기능을 활용할 수 있습니다. ==> 2022.8 월에 북마크 기능 사용 불가로 변경됨. 북마크 사용 불가

아래는 차례대로 참고할 북마크입니다.

  1. kubectl Cheat Sheet
  2. kubectl Reference Docs

시험 링크

 

 

 

udemy 강의 내용

섹션1 : introduction

Certification Details

Below are some references:

Certified Kubernetes Administrator: https://www.cncf.io/certification/cka/

Exam Curriculum (Topics): https://github.com/cncf/curriculum

Candidate Handbook: https://www.cncf.io/certification/candidate-handbook

Exam Tips: http://training.linuxfoundation.org/go//Important-Tips-CKA-CKAD

 

 

섹션2 : 핵심개념

11. Cluster Architecture

* master node

- kube-apiserver

- kube-controller-manager

- kube-scheduler

- ETCD

 

* worker node

- kubelet

- kube-proxy

 

12. ETCD For Beginners(#D1D7DC)

 

ETCD is a distributed reliable key-value store that is Simple, Secure & Fast

 

13. ETCD in Kubernetes
etcd 데이터 저장소는 클러스터에 대한 정보를 저장합니다.
 
 

14. ETCD-command

ETCDCTL은 버전 2 및 버전 3의 2가지 API 버전을 사용하여 ETCD 서버와 상호 작용할 수 있습니다. 기본적으로 버전 2를 사용하도록 설정되어 있습니다.

API의  버전을 설정하려면 환경 변수 ETCDCTL_API 명령으로 설정

export ETCDCTL_API=3

 

 

15. Kube-API Server

kube-apiserver는 Kubernetes의 주요 관리 구성 요소입니다.
kubectl 명령을 실행할 때, kubectl 유틸리티는 실제로 명령을 kube-apiserver로 전달합니다.

kube-apiserver는 먼저 요청을 인증하고 확인합니다.
그런 다음 etcd에서 데이터를 검색하고 요청한 정보와 함께 응답합니다.
- authenticate user
- validate request

- retrieve data

- update ETCD

- scheduler

- kubelet

 

16. Kube Controller Manager

Kube Controller Manager Kubernetes의 다양한 컨트롤러를 관리합니다.

컨트롤러는 지속적으로 시스템 내의 다양한 구성 요소의 상태를 모니터링합니다.

- Node-controller : node를 모니터링하고 application이 지속될 수 있도록 조치

- Replication-controller : replicaset을 모니터링하고 pod의 개수를 유지

- deployment, namespace, endpoint, cronjob, job, pv-protection, service-account, stateful-set, replicaset 등이 있음

모든 컨트롤러는 kubernetes controller manager 프로세스 하나로 패키징되어 있음.

 

 

17. Kube Scheduler

kube scheduler는 어떤 node에 pod를 할당할지를 관리

할당기준 : resources, taint and tolerations, node selector/affinity 등

 

 

18. Kubelet

- register node

- create POD

- Monitor node & POD

worker node의 kubelet은  Kubernetes 클러스터에 노드를 등록합니다.
노드의 컨테이너 또는 포드를 로드하라는 지시를 받았을 때 컨테이너 런타임 엔진에 요청합니다.
그런 다음 kubelet은 포드의 상태를 계속 모니터링하고 컨테이너 및 pod에 대한 상태를 kube API 서버에 보고합니다.

 

19. Kube Proxy

Kube-proxy는 각 노드에서 실행되는 프로세스입니다.
Kubernetes 클러스터에서 그들의 임무는 새로운 서비스를 찾는 것이며, 새로운 서비스가 생성될 때마다
각 노드에 적절한 규칙을 생성합니다.
해당 서비스에 대한 트래픽을 백엔드 포드로 전달합니다.

- IPTABLES rules

 

21. POD with yaml

Kubernetes는 pod, replicas, deployment, service 와 같은 오브젝트를 생성할 때 yaml 파일을 사용합니다.
Kubernetes 정의 파일에는 항상 최상위 필드인 apiVersion, kind, metadata, spec을 포함합니다.

yaml 파일에서 사용하는 "-"(dash)는 목록의 첫 번째 항목임을 나타냅니다.

 

 

 

28. Recap - ReplicaSets

-- scale

replicationController과 다른점은 replicaSet은 selector가 있다. select는 pod를 구분하기 위한 것이다.

만일, 기존의 pod 중 label이 replicaset에 명시된 selector와 같은 것이 있을 경우, replicaset은 이 pod를 같은 replicaset의 pod로 간주한다. 즉 새로이 replicaset 생성 시 replicas=3으로 한 경우, 기존 pod를 포함하여 총 3개의 pod가 운영되도록한다. 즉 새롭게 2개 pod만 추가한다.

 

31. Deployments

replicaset이 있는데 deployment가 있는 이유는?

- pod를 upgrade를 할 경우, 한번에 전체를 업그레이드하는 것이 아니라 점전적으로 업그레이드를 하고자 할 때(rolling update)

- undo

 

35. Services

서비스는 애플리케이션 내부와 외부의 다양한 구성 요소 간의 통신을 가능하게 합니다.

노드의 포트를 수신 대기하고 해당 포트의 요청을 웹 애플리케이션을 실행하는 POD 포트로 전달하는 것입니다.
이 유형의 서비스는 서비스가 노드의 포트를 수신하기 때문에 NodePort service 라고 합니다.

서비스 종류

  • ClusterIP
  • NodePort
  • LoadBalancer

40. Namespaces

namespaces

isolation

resource limit(ResourceQuota)

DNS

-service-name.namespace.service.domain

예시) db-service.dev.svc.cluster.local

-> db-service:서비스명, dev:namespace, service:svc, cluster.local : domain

 

생성

kubectl create namespace dev

namespace switch

 

kubectl config set-context --current --namespace=<insert-namespace-name-here>

 

43. Imperative vs Declarative

 

imperative : what & how

declarative : what 

 

- kubectl apply

Certification Tips - Imperative Commands with Kubectl

Before we begin, familiarize with the two options that can come in handy while working with the below commands:

--dry-run: By default as soon as the command is run, the resource will be created. If you simply want to test your command , use the --dry-run=client option. This will not create the resource, instead, tell you whether the resource can be created and if your command is right.

-o yaml: This will output the resource definition in YAML format on screen.

 

Use the above two in combination to generate a resource definition file quickly, that you can then modify and create resources as required, instead of creating the files from scratch.

 

 

 

 

Replication Controller vs RepliaSet

 

Labels vs Selectors

 

scale 

여러가지 방법이 있습니다.

1) yaml replica 수정 후 kubectl replace -f yaml-file

2) kubectl edit replicasets.apps <replicationset_name>

3) kubectl scale --replicas=6 -f rs.yaml

4) kubectl scale --replicas=2 replicaset <replicationset_name>

 

Link: https://uklabs.kodekloud.com/courses/labs-certified-kubernetes-administrator-with-practice-tests/

Apply the coupon code udemystudent151113

 

Practice Test - ReplicaSets

Practice Test Link: https://uklabs.kodekloud.com/topic/practice-test-replicasets-2/

 

kubectl explain replicaset

 

57. Taints and Tolerations

 

60. Node Selectors

 

61. Node Affinity

 

70. DaemonSets

- 하나의 node에 하나의 pod를 할당. node가 추가되면 pod도 추가된 node에 자동으로 할당

Monitoring Solution, Logs Viewer 등에 적합

replicaset과 거의 비슷

예) kube-proxy, weave-net(CNI 네트워크) 등

 

73. Static Pods

 

master node 가 없는 경우에도 kubelet 만으로 pod 생성할 수 있다.

/etc/kubernetes/manifest 디렉토리에 yaml 파일을 생성하면 된다. pod만 생성 가능.

pod명은 "pod명 - node명"으로 생성됨.(예시. pod명이 static-pod이고 node명이 worker-1인경우 -> static-pod-worker-1 로 pod가 생성됨)

 

파일을 삭제하면 pod 도 삭제됨.

/var/lib/kubelet/config.yaml 파일에 staticPodPath 에 위치가 설정되어 있음.

이걸 변경하고 kubelet 을 재기동(systemctl restart kubelet) 하면 변경되 path가 적용됨

 

76. Multiple Schedulers

 

79. Configuring Kubernetes Scheduler

 

 

 

deployments

유용한 명령어 : kubectl get all

 

Certification Tip!

https://kubernetes.io/docs/reference/kubectl/conventions/

 

Create an NGINX Pod

kubectl run nginx --image=nginx

Generate POD Manifest YAML file (-o yaml). Don't create it(--dry-run)

kubectl run nginx --image=nginx --dry-run=client -o yaml

Create a deployment

kubectl create deployment --image=nginx nginx

Generate Deployment YAML file (-o yaml). Don't create it(--dry-run)

kubectl create deployment --image=nginx nginx --dry-run=client -o yaml

Generate Deployment YAML file (-o yaml). Don't create it(--dry-run) with 4 Replicas (--replicas=4)

kubectl create deployment --image=nginx nginx --dry-run=client -o yaml > nginx-deployment.yaml

Save it to a file, make necessary changes to the file (for example, adding more replicas) and then create the deployment.

kubectl create -f nginx-deployment.yaml

OR

In k8s version 1.19+, we can specify the --replicas option to create a deployment with 4 replicas.

kubectl create deployment --image=nginx nginx --replicas=4 --dry-run=client -o yaml > nginx-deployment.yaml

 

Practice Test - Deployments

 

 

 

 

 

POD

Create an NGINX Pod

kubectl run nginx --image=nginx

 

Generate POD Manifest YAML file (-o yaml). Don't create it(--dry-run)

kubectl run nginx --image=nginx --dry-run=client -o yaml

 

Deployment

Create a deployment

kubectl create deployment --image=nginx nginx

 

Generate Deployment YAML file (-o yaml). Don't create it(--dry-run)

kubectl create deployment --image=nginx nginx --dry-run=client -o yaml

 

Generate Deployment with 4 Replicas

kubectl create deployment nginx --image=nginx --replicas=4

 

You can also scale a deployment using the kubectl scale command.

kubectl scale deployment nginx --replicas=4

Another way to do this is to save the YAML definition to a file and modify

kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx-deployment.yaml

 

You can then update the YAML file with the replicas or any other field before creating the deployment.

 

Service

Create a Service named redis-service of type ClusterIP to expose pod redis on port 6379

kubectl expose pod redis --port=6379 --name redis-service --dry-run=client -o yaml

(This will automatically use the pod's labels as selectors)

Or

kubectl create service clusterip redis --tcp=6379:6379 --dry-run=client -o yaml (This will not use the pods labels as selectors, instead it will assume selectors as app=redis. You cannot pass in selectors as an option. So it does not work very well if your pod has a different label set. So generate the file and modify the selectors before creating the service)

 

Create a Service named nginx of type NodePort to expose pod nginx's port 80 on port 30080 on the nodes:

kubectl expose pod nginx --type=NodePort --port=80 --name=nginx-service --dry-run=client -o yaml

(This will automatically use the pod's labels as selectors, but you cannot specify the node port. You have to generate a definition file and then add the node port in manually before creating the service with the pod.)

Or

kubectl create service nodeport nginx --tcp=80:80 --node-port=30080 --dry-run=client -o yaml

(This will not use the pods labels as selectors)

Both the above commands have their own challenges. While one of it cannot accept a selector the other cannot accept a node port. I would recommend going with the kubectl expose command. If you need to specify a node port, generate a definition file using the same command and manually input the nodeport before creating the service.

 

Practice Test - Imperative Commands

Practice Test Link: https://uklabs.kodekloud.com/topic/practice-test-imperative-commands-3/

 

Create a service redis-service to expose the redis application within the cluster on port 6379.Use imperative commands.

kubectl expose pod redis --port=6379 --name redis-service

 

kubectl apply

 

scheduling

Practice Test - Manual Scheduling

 

Labels  &  Selectors

label : 

예시) 동물 분류, 색깔 분류 등

 

selector

label로 filter

 

selector 사용법

kubectl get pod --selector bu=finance

kubectl get all --selector env=prod

 

 

✔ Taints and Tolerations (Optional)

  • taint : 노드마다 설정가능. 설정한 노드에는 pod이 스케줄되지 않음
  • toleration : pod에 설정. taint를 무시할수있음

kubectl taint nodes node-name key=value:taint-effect

=> taint-effect : NoScheduler, PreferNoScheduler, NoExcute

 

Node Selectors

node 생성 시 label 지정

kubectl label node node-name key=value

pod 생성 시  nodeSelector 사용

 

Affinity란?

Pod가 특정 Worker Node에 배치되도록 하는 정책.

Node를 기준으로 Scheduling 하는 Node Affinity와

Pod를 기준으로 Scheduling 하는 Pod Affinity가 있음.

Node Affinity

 

Resource Limit

Resource Requests

- Resource CPU : 1vCpu defaut

- Resource Memory : 512Mi default

 

 

 

Multiple schedulers

 

https://kubernetes.io/blog/2017/03/advanced-scheduling-in-kubernetes/

 

 

세션 4 : Logging & Monitoring

MetricS-Server, prometheus, Elastic Stack, Datadog, Dynatrace

kubelet 을 통해서(CAdvisor 또는 Container Advisor)

Metrics-Server 설치

- deploy metrics-server to monitor the PODs and Nodes

git clone https://github.com/kodekloudhub/kubernetes-metrics-server.git
cd kubernetes-metrics-server
kubectl create -f .

kubectl top node

 

Monitor cluster components

- node, pod 등(CPU, Memory, Disk 등)

 

모니터링 툴

- Metrics Server, Prometheus, Elastic Stack, DataDog, Dynatrace 등

 

- Metrics Server(IN-memory 모니터링)

yaml 파일로 설치

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

설치된 metrics-server deployment를 확인

kubectl get deployment metrics-server -n kube-system

 

 

 

 

 

86. Managing Application Logs

kubectl logs -f pod-name -c container-name

 

 

 

Managing logs

 

events

kubtctl logs -f events <pod-name>

pod안에 multi-container 가 있을 경우 container-name을 지정

 

 

 

섹션5: Application Lifecycle Management

91. Rolling Updates and Rollbacks

명령어 : kubectl  apply 또는 kubectl set image 

- deployment strategy

1) 전체를 삭제하고 새롭게 생성 : application downtime 발생.

2) pod 하나씩 삭제/생성 : rolling update라고 함

 

- deployment upgrade 과정

deployment를 생성하면 replicaset을 생성함.

pod upgrade 방식은 새로운 replicaset을 생성하고 기존의 replicaset에서 pod 하나를 삭제하고 새롭게 만든 replicaset에 새로운 pod를 생성하는 방식으로 upgrade 함. 즉 하나씩 삭제와 생성을 반복하면서 upgrade 진행

upgrade가 완료되면 기본의 replicaset과 새로운 replicaset이 존재하는 것을 확인할 수 있음.

 

deployment rollback 과정

명령어 : kubectl rollout undo deployment/deployment-name

upgrade 방식과 동일한 방식으로 rollback 함. 단 replicaset은 기존의 replicaset을 이용

 

 

 

deployment-definition.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
  app: myapp
  type: front-end
spec:
  template:
    metadata:
      name: myapp-pod
      labels:
        app: myapp
        type: front-end
    spec:
      containers:
      - name: nginx-container
        image: nginx
  replicas: 3
  selector:
    matchLabels:
      type: front-end

1) kubectl apply 로 rolling update

kubectl apply -f deployment-definition.yml

2) kubectl set image로 rolling update

kubectl set image deployment/myapp-deployment nginx=nginx:1.9.1

 

recreate vs rolling update

 

Rollback

 

* create 

kubectl create

 

* update 

kubectl apply

kubectl set image

 

* status 

kubectl rollout status 

 

rollback

kubectl rollout history 

kubectl rollout undo

 

Configure Applications

  • Configuring Command and Arguments on applications
  • Configuring Environment Variables
  • Configuring Secrets

 

95. Application Commands

docker comand 

CMD, ENTRYPOINT : CMD는 argument로 받은 인수로 overwrite하고 ENTRYPOINT는 인수를 append 한다.

entrypoint를 변경하려면  docker run --entrypoint sleep image-name arg 형식으로 하면된다.

 

96. Commands and Arguments

 

 

99. configuration environment variables in application

- plain key-value

env:
  - name: APP_NAME
    value:

- configMap

env:
  - name: APP_NAME
    valueFrom: 
      configMapKeyRef:

- secrets

env:
  - name: APP_NAME
    valueFrom: 
      secretKeyRef:

100. configuration CongifMap in application

envFrom:
  - configMapRef:
      name:

- configMap 생성

kubectl create configMap <config-name> --from-literal=<key>=<value>

 

kubectl create configMap <config-name> --from-file=<configfile-name>

 

103. configure secrets in application

- create secret

1) imperative

kubectl create secret generic <secret-name> --from-literal=<key>=<value> --from-literal=<key>=<value>

kubectl create secret generic <secret-name> --from-from=<key>=<path-to-file>

* 파일에 암호화 데이터를 넣는 방법

echo -n 'password' | base64

* 암호 디코딩

echo -n 'encoded-password' | base64 --decode

2) declarative

kubectl create -f <file-name>

- inject into pod

  envFrom:
    - secretRef:
        name: <secret-name>

 

A note about Secrets!

Remember that secrets encode data in base64 format. Anyone with the base64 encoded secret can easily decode it. As such the secrets can be considered as not very safe.

The concept of safety of the Secrets is a bit confusing in Kubernetes. The kubernetes documentation page and a lot of blogs out there refer to secrets as a "safer option" to store sensitive data. They are safer than storing in plain text as they reduce the risk of accidentally exposing passwords and other sensitive data. In my opinion it's not the secret itself that is safe, it is the practices around it. 

Secrets are not encrypted, so it is not safer in that sense. However, some best practices around using secrets make it safer. As in best practices like:

  • Not checking-in secret object definition files to source code repositories.
  • Enabling Encryption at Rest for Secrets so they are stored encrypted in ETCD. 

 

Also the way kubernetes handles secrets. Such as:

  • A secret is only sent to a node if a pod on that node requires it.
  • Kubelet stores the secret into a tmpfs so that the secret is not written to disk storage.
  • Once the Pod that depends on the secret is deleted, kubelet will delete its local copy of the secret data as well.

Read about the protections and risks of using secrets here

 

Having said that, there are other better ways of handling sensitive data like passwords in Kubernetes, such as using tools like Helm Secrets, HashiCorp Vault. I hope to make a lecture on these in the future.

 

107. Scale Applications
Deployments and Rolling updates and Rollback sections. 참조
 
108. Multi Container PODs

Web Server 와 Log Agent는 연관성이 깊다. 같은 pod로 관리하는 것이 효율적임.

Network, Storage 를 같이 공유. Lifecycle가 같다.

 

sidecar container

 sidecar container for the application to send logs to Elastic Search.

 

kubectl replace 문법 확인

 

 

111. Multi-container PODs Design Patterns

sidecar, adapter, ambassador pattern

 

But these fall under the CKAD curriculum and are not required for the CKA exam. So we will be discuss these in more detail in the CKAD course.

112. initContainers

다중 컨테이너 포드에서 각 컨테이너는 POD의 수명 주기 동안 활성 상태를 유지하는 프로세스를 실행해야 합니다. 예를 들어 웹 애플리케이션과 로깅 에이전트가 있는 앞에서 이야기한 다중 컨테이너 포드에서 두 컨테이너는 항상 활성 상태를 유지해야 합니다. 로그 에이전트 컨테이너에서 실행 중인 프로세스는 웹 애플리케이션이 실행되는 한 계속 활성 상태를 유지해야 합니다. 그 중 하나라도 실패하면 POD가 다시 시작됩니다.

But at times you may want to run a process that runs to completion in a container. For example a process that pulls a code or binary from a repository that will be used by the main web application. That is a task that will be run only  one time when the pod is first created. Or a process that waits  for an external service or database to be up before the actual application starts. That's where initContainers comes in.

그러나 때때로 컨테이너에서 완료된 후에 실행되는 프로세스를 실행해야 하는 경우가 있습니다. 예를 들어 웹 애플리케이션에서 사용할 리포지토리에서 코드 또는 바이너리를 가져오는 프로세스입니다. pod가 처음 생성될 때 한 번만 실행되는 작업입니다. 또는 실제 응용 프로그램이 시작되기 전에 외부 서비스나 데이터베이스가 작동될 때까지 기다리는 프로세스입니다. 그것이 initContainers 이 필요한 이유입니다.

initContainer는 initContainers 섹션 내에 지정된다는 점을 제외하고 다른 모든 컨테이너와 마찬가지로 포드에 구성됩니다.

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers:
  - name: init-myservice
    image: busybox
    command: ['sh', '-c', 'git clone <some-repository-that-will-be-used-by-application> ; done;']
 

POD가 처음 생성되면 initContainer가 실행됩니다. initContainer 생성이 완료되면 다음 컨테이너가 실행됩니다.
다중 포드 컨테이너에 대해 수행한 것과 같이 이러한 initContainer를 여러 개 구성할 수도 있습니다. 이 경우 각 init 컨테이너는 순차적으로 한 번에 하나씩 실행됩니다.
initContainer 중 하나라도 완료되지 않으면 Kubernetes는 Init Container가 성공할 때까지 Pod를 반복적으로 다시 시작합니다.

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers:
  - name: init-myservice
    image: busybox:1.28
    command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;']
  - name: init-mydb
    image: busybox:1.28
    command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']

Read more about initContainers here. 

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

 

115. Self Healing Applications

Kubernetes는 ReplicaSet 및 ReplicationController를 통해 자가 치유 애플리케이션을 지원합니다. 복제 컨트롤러는 POD 내의 애플리케이션이 충돌할 때 POD가 자동으로 다시 생성되도록 합니다.

Kubernetes는 POD 내에서 실행되는 애플리케이션의 상태를 확인하고 활성 및 준비 상태 프로브를 통해 필요한 조치를 취하기 위한 추가 지원을 제공합니다. 그러나 이들은 CKA 시험에 필요하지 않으므로 여기에서 다루지 않습니다.  CKAD(Certified Kubernetes Application Developers) 시험의 주제이며 CKAD 과정에서 다룹니다.

 

 

section6 : Cluster Maintenance

'쿠버네티스' 카테고리의 다른 글

쿠버네티스 보충  (0) 2022.06.08
CKA 자격증 취득하기 #2  (0) 2022.05.23
쿠버네티스 - secret  (0) 2022.05.18
쿠버네티스 - configmap  (0) 2022.05.18
쿠버네티스 - configmap  (0) 2022.05.18

+ Recent posts