1. 

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

쿠버네티스 설치 - unbutu 22.04  (0) 2022.06.27
CKA 자격증 취득하기 - 시험예상 문제  (0) 2022.06.09
쿠버네티스 보충  (0) 2022.06.08
CKA 자격증 취득하기 #2  (0) 2022.05.23
CKA 자격증 취득하기 #1  (0) 2022.05.18

Install Kubernetes Cluster on Ubuntu 22.04 with kubeadm

[ 설치환경 ]

- OS : Ubuntu 22.04 LTS(2 CPU, 4GB Memory, 20GB Disk 이상)

- master node : 1대(hostname : master)

- worker node : 2대(hostname : worker-1, worker-2)

 

설치순서

✔  공통 설치(master node, worker node 에 설치)

1) CRI 설치

2) kubeadm, kubectl, kubelet 설치

3) CNI 설치

 

 master node

- kubeadm init 실행

 

 worker node

- kubeadm join 실행

 

 

1. 공통 설치(master node, worker node 에 설치)

1) CRI  설치(Container Runtime Interface)

도커 이미지를 관리해주는 CRI를 설치합니다. CRI는 많은 종류가 있는데 본 문서에서는 containerd 를 설치합니다.

sudo apt-get update
sudo apt-get install containerd

 

2) kubernetes 설치 전 환경설정

- br_netfilter 모듈을 로드합니다.  br_netfilter 모듈이 로드되었는지 확인하려면

lsmod | grep br_netfilter 를 실행하면 됩니다.(kubernetes documents 에서 "container runtimes"로 검색)

sudo modprobe br_netfilter

- iptables가 브리지된 트래픽을 보게 하기

cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
br_netfilter
EOF

cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sudo sysctl --system

- ip_forward 설정

echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward

 

- swap off

$ sudo swapoff -a

- port 확인

master node에 6443, 8080 port 가 사용중인지 확인합니다. 사용 중인 서비스가 없어야 합니다.

쿠버네티스 API 서버는 2개의 포트에서 HTTP를 서비스합니다.

- 8080 port : 스트 및 부트스트랩을 하기 위한 것이며 마스터 노드의 다른 구성요소 (스케줄러, 컨트롤러 매니저)가 API와 통신

- 6443 port : TLS를 사용

telnet 10.10.1.15(예시, master node IP Address) 6443

 

- 방화벽 open(서버 방화벽 disable)

방화벽이 설정을 확인한 다음 방화벽이 enable되어 있으면 방화벽을 disable 합니다. 

## 방화벽 설정 확인
sudo ufw status

## 방화벽 disable
sudo ufw disable

 

 

3) kubectl, kubeadm, kubelet 설치

sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl

sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg

echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list

sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl

sudo apt-mark hold kubelet kubeadm kubectl

 

2. master node  설치

1) control plane 구성

control plane은 master node에만 구성합니다.(multi master 구성시에는 multi master 에 구성)

contron plane을 구성한다는 것은 kube-apiserver, kube-controller-manager, kube-scheduler, etcd, coreDns 를 설치하는 것입니다. 사용자가 kubeadm init 명령어만 수행하면 kubeadm 이 알아서 구성을 해줍니다.

kubeadm init 명령어로 control plane 을 구성합니다. 명령어 수행 제일 하단에 아래와 같이 kubeadm join 으로 시작하는 정보가 표시됩니다. 이 명령어는 나중에 worker node 에서 수행하여 cluster를 구성하는 명령어입니다. 별도로 저장해 놓습니다.

$ kubeadm init

## 수행결과
...
Your Kubernetes control-plane has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

Alternatively, if you are the root user, you can run:

  export KUBECONFIG=/etc/kubernetes/admin.conf

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/
...
kubeadm join 10.10.1.20:6443 --token x8g6zc.1yb94eh1u1940rrj \
	--discovery-token-ca-cert-hash sha256:996f5ea00339533897cd991fb005349eeb366af000b13c8458f9743d5ada230c

 

root와 일반 user가 쿠버네티스 명령어를 사용할 수 있도록 환경 설정(master node에 설정)을 합니다.

 

root 유저로 kubectl 명령어를 수행하려면 root 유저로 아래를 설정합니다.

export KUBECONFIG=/etc/kubernetes/admin.conf

 

일반 유저로 kubectl 명령어를 수행하기 위해 일반 유저로 아래를 설정합니다.

mkdir -p $HOME/.kube

## admin.conf 파일은 kubelet 설치 시 생성
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

참고) 쿠버네티스 클러스터 구성 시 pod 의 네트워크 대역을 설정할 수 있습니다.

kubeadm init --pod-network-cidr=10.244.0.0/16;

 

2) CNI 설치(master node에 설정)

CNI(Container Network Interface)를 설치하여 Pod 간 통신을 할 수 있도록 합니다.

pod 네트워크 애드온 종류는 많습니다(calico, canal, flannel, romana, weave net 등).

원하는 네트워크 애드온을 마스터 노드에 설치합니다.

본 문서에서는 weave network add on 을 설치합니다. 

Weave Net을 설치하기 전에 TCP 6783 및 UDP 6783/6784 포트가 방화벽에 의해 차단되지 않았는지 확인해야 합니다.

아래 명령어로 weave network add-on을 설치합니다.

<weabenet 설치>

kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"

## 실행결과
serviceaccount/weave-net created
clusterrole.rbac.authorization.k8s.io/weave-net created
clusterrolebinding.rbac.authorization.k8s.io/weave-net created
role.rbac.authorization.k8s.io/weave-net created
rolebinding.rbac.authorization.k8s.io/weave-net created
daemonset.apps/weave-net created

2022.10.20 일 기준으로 kubectl 버전에 따라 위의 명령어가 수행되지 않을 경우, 아래 명령어를 수행한다

kubectl apply -f https://github.com/weaveworks/weave/releases/download/v2.8.1/weave-daemonset-k8s.yaml

<calico 설치>

1. operator 설치

kubectl apply -f https://github.com/coreos/flannel/raw/master/Documentation/kube-flannel.yml

2. calico 설정 파일 다운로드

curl https://raw.githubusercontent.com/projectcalico/calico/v3.24.3/manifests/custom-resources.yaml -O

3. calico 설치

kubectl create -f custom-resources.yaml

 

<flannel 설치>

주의할 점 : master node에서 컨트롤 플레인 설정 시 반드시 --pod-network-cidr=10.244.0.0/16 옵션으로 수행해야 한다

sudo kubeadm init --pod-network-cidr=10.244.0.0/16

아래 명령어로 flannel CNS를 설치한다.

kubectl apply -f https://github.com/coreos/flannel/raw/master/Documentation/kube-flannel.yml

 

3. worker node  Join

worker node를 master node에  join 시킵니다.

master node 에서 수행한 kubeadm init 명령어의 실행 결과창에서 보여진 kubeadm join으로 시작되는 부분을 실행해 줍니다.

kubeadm join 10.10.1.15:6443 --token 2gcmlw.zfvrc2b42j3q30zk \
	--discovery-token-ca-cert-hash sha256:aeb530a1ee53667a603d53d9d9abe12a32009b9f432b0fbca40fa1116c1fcc46

 

4. 쿠버네티스 구성 확인

마스터 노드(control-plane 노드)에서 kubectl get nodes 로 node 정보를 확인합니다. 아래와 같이 조회되면 정상입니다.

STATUS 가 모두 Ready 상태여야 합니다.

$ kubectl get nodes
NAME       STATUS   ROLES                  AGE     VERSION
master     Ready    control-plane,master   10h     v1.23.6
worker-1   Ready    <none>                 9h      v1.23.6
worker-2   Ready    <none>                 2m40s   v1.23.6

 

5.  kubectl 예제

kubectl get 명령어로 클러스터를 구성하고 있는 node 정보를 볼 수 있습니다.

## node 정보조회
$ kubectl get nodes

## node 정보 상세조회
$ kubectl get nodes -o wide

컨테이너를 실행하면서 kubectl 명령어 사용하기

아래 명령어는 nginx 최신 버전의 이미지로 webserver 라는 이름의 pod를 생성하고 실행하라는 내용입니다.

$ kubectl run webserver --image=nginx:latest --port 80
pod/webserver created

생성된 pod를 확인합니다. 아래 내용을 보면 현재 상태가 container creating 인 것을 확인할 수 있습니다. pod가 정상적으로 생성완료되면 running으로  상태가 변경됩니다. 현재 진행되는 상태를 보려면 kubectl describe pods 명령어를 수행합니다.

$ kubectl get pods
NAME        READY   STATUS              RESTARTS   AGE
webserver   0/1     ContainerCreating   0          23s

## pods 정보 확인
$ kubectl get pods webserver -o wide
NAME        READY   STATUS    RESTARTS   AGE   IP          NODE     NOMINATED NODE   READINESS GATES
webserver   1/1     Running   0          49m   10.44.0.1   node-1   <none>           <none>

## pods 상태 상세확인
$ kubectl describe pods webserver
## 실행결과
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  57s   default-scheduler  Successfully assigned default/webserver to node-1
  Normal  Pulling    56s   kubelet            Pulling image "nginx:latest"
  Normal  Pulled     48s   kubelet            Successfully pulled image "nginx:latest" in 8.496066344s
  Normal  Created    48s   kubelet            Created container webserver
  Normal  Started    48s   kubelet            Started container webserver

node-1에서 10.44.0.1 IP로 nginx 웹서버가 작동하고 있는 것을 확인할 수 있습니다.

 

 

컨테이너 확인하기

curl 명령어로 위에서 생성한 nginx pod 가 정상 동작하는지 확인해 봅니다.(참고. elinks(이링크스)라는 유닉스 기반 운영 체제를 위한 텍스트 기반 콘솔 웹 브라우저로 웹 페이지를 확인할 수 있습니다.)

curl 10.44.0.1

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
....

 

kubectl create 명령어

파일 또는 표준 입력에서 리소스를 생성합니다. JSON and YAML 형식의 파일을 사용할 수 있습니다.

 

usage:
  kubectl create deployment NAME --image=image -- [COMMAND] [args...] [options]

 

kubectl create deployment mainui --image=httpd:latest --replicas=3

생성된 pod를 확인합니다.

1) kubectl get deployment.apps 명령어로 확인

kubectl get deployments.apps 
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
mainui   3/3     3            3           46s

2) kubectl get pods 명령어로 확인

$ kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
mainui-7bdb5f79fb-4qvhc   1/1     Running   0          3m29s
mainui-7bdb5f79fb-btblc   1/1     Running   0          3m29s
mainui-7bdb5f79fb-nrdv5   1/1     Running   0          3m29s
webserver                 1/1     Running   0          128m

 

배포한 웹서버의 웹페이지 변경하기

kubectl exec  명령어로 위에서 생성한 webserver pod의 웹페이지를 변경해 봅니다.

kubectl exec  명령어는 동작중인 컨테이너의 셸에 접근할 수 있도록 해주는 명령어입니다.

kubectl exec --stdin --tty webserver -- /bin/bash
또는
kubectl exec -it webserver -- /bin/bash

## 실행결과(컨테이너에 접속됨)
root@webserver:/#

 

nginx 웹페이지는 /usr/share/nginx/html 디렉토리에 있습니다. index.html 파일이 웹서버의 첫 웹페이지입니다.이 웹페이지를 원하는 내용으로 변경하고 curl이나 elinks 로 변경된 내용을 확인합니다.

# cat > index.html
NGINX 웹서버입니다.
ctrl + D 를 클릭하여 저장합니다.
# exit

$ curl 10.44.0.1
NGINX 웹서버입니다.

 

nginx log도 확인해 봅니다. nginx log는 컨테이너의 /var/log/nginx 밑에 access.log, error.log 파일입니다.

$ kubectl logs webserver

...
10.32.0.1 - - [05/May/2022:16:27:14 +0000] "GET / HTTP/1.1" 200 615 "-" "ELinks/0.13.1 (textmode; Linux 5.13.0-1024-gcp x86_64; 153x16-2)" "-"
10.44.0.0 - - [05/May/2022:18:15:45 +0000] "GET / HTTP/1.1" 200 29 "-" "curl/7.68.0" "-"
10.44.0.1 - - [05/May/2022:18:16:20 +0000] "GET / HTTP/1.1" 200 29 "-" "curl/7.74.0" "-"

이제 외부에서 pod에 접속할 수 있도록 port-forward 명령어를 사용합니다.

아래 명령어는 외부에서 8080으로 접속하면 pod의 80 port로 forwarding 하는 예시입니다.

$ kubectl port-forward --address=0.0.0.0 webserver 8080:80

다른 서버에서 curl 명령어를 사용하여 웹서버 페이지를 호출해 봅니다.

$ curl http://10.10.1.35:8080

NGINX 웹서버입니다

위에서 생성한 mainui pod의 개수를 3개에서 kubectl edit 명령어로 변경해 봅니다.

아래 명령어를 수행하면 mainui pod에 대한 설정값을 vi 에디터로 불러옵니다. 여기서 변경하고자 하는 값을 변경하면 됩니다. 본 문서에서는 replicas를 3개에서 5개로 변경해 보겠습니다. 변경 후 :wq 로 저장하고 vi 에디터를 빠져나옵니다.

kubectl edit deployments.app mainui

....
spec:
  progressDeadlineSeconds: 600
  replicas: 5
...

pod 갯수가 변경되었는지 확인합니다. 아래와 같이 mainui pod가 5개로 변경된 것을 볼 수 있습니다.

kubectl get pods

## 실행결과
$ kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
mainui-7bdb5f79fb-4qvhc   1/1     Running   0          76m
mainui-7bdb5f79fb-8t9r9   1/1     Running   0          2m23s
mainui-7bdb5f79fb-btblc   1/1     Running   0          76m
mainui-7bdb5f79fb-nrdv5   1/1     Running   0          76m
mainui-7bdb5f79fb-q6nlg   1/1     Running   0          61s
webserver                 1/1     Running   0          3h20m

 

pod 생성할 내용을 파일로 생성해 봅니다.

--dry-run 플래그를 사용하여 실제로 제출하지 않고 클러스터로 보낼 오브젝트를 미리 볼 수 있습니다.

리다이텍션으로 파일로 저장할 수도 있습니다.

kubectl run webserver --image=nginx --port 80 --dry-run=client -o yaml > webser.yaml

yaml 파일로 pod를 생성합니다. 기존에 생성한 이름과 동일한 pod를 생성하므로 기존 pod를 삭제한 후 실행합니다.

## 기존 webserver pod 삭제
$ kubectl delete pod webserver

## yaml 파일로 pod 생성
$ kubectl create -f webserver.yaml

## 생성된 pod 확인
$ kubectl get pods

 

[참고] kubectl create vs apply 

 

kubectl create
kubectl create는 명령형 관리를 위한 것입니다. 이 접근 방식에서는 생성, 교체 또는 삭제하려는 항목을 Kubernetes API에 알립니다. 간단히 말해서 create는 새 객체를 생성합니다. 리소스가 이미 있는 경우 오류가 발생합니다.

 

kubectl apply

kubectl apply는 다른 변경 사항을 개체에 적용하더라도 라이브 개체에 적용했을 수 있는 변경 사항(즉, 규모를 통해)이 "유지 관리"되는 선언적 관리 접근 방식의 일부입니다.
apply는 우리가 필요로 하는 것을 정의함으로써 기존 객체를 점진적으로 변경합니다. 리소스가 이미 있는 경우 오류가 발생하지 않습니다.

 

pod 삭제

예제) kubectl delete pods <pod> : <pod> 부분에 삭제할 pod 이름을 입력합니다.

kubectl delete pods webserver

 

 

 

 

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

쿠버네티스 - play with k8s  (0) 2022.10.20
CKA 자격증 취득하기 - 시험예상 문제  (0) 2022.06.09
쿠버네티스 보충  (0) 2022.06.08
CKA 자격증 취득하기 #2  (0) 2022.05.23
CKA 자격증 취득하기 #1  (0) 2022.05.18

https://kubernetes.io 의 document 만을 참고하여 문제를 풀 것.

사전에 auto completion 을 설정되어 있으므로 잘 활용하면 효율적임.

tmux 도 제공되므로 활용하면 좋음.

문제 지시에 따라 context 를 지정한 후 문제를 푼다.(sudo -i 를 한경우 반드시 context를 확인해야 함)

sudo -i 를 사용해야 할 경우도 있음.  --> sudo 명령어를 사용하는게 나을 듯.

 

시험전략

- 시험전에 pc compatibility 체크

- 74점 이상이므로 너무 어려운 문제를 풀려고 하지 말것.

- 최신 버전으로 시험 준비

- CKA portal : 

 

 

 

 

 

24 or 28 문제 출제??

 

시험 환경 설정

🔒 kubectl autocompletion 하기

 

echo 'source <(kubectl completion bash)' >>~/.bashrc

echo 'alias k=kubectl' >>~/.bashrc
echo 'complete -F __start_kubectl k' >>~/.bashrc

source .bashrc

예상 시험 문제

🔒 kubeadm으로 클러스터 구성하기

 

1. container runtime 설치

: kubernetes.io 사이트에서 "container runtime" 로 검색 한 후 "container runtimes" 클릭 후 설정

sudo modprobe br_netfilter

cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF

sudo modprobe overlay
sudo modprobe br_netfilter

# sysctl params required by setup, params persist across reboots
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables  = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward                 = 1
EOF

# Apply sysctl params without reboot
sudo sysctl --system

apt install containerd

2. container runtime 설치

: kubernetes.io 사이트에서 "install with kubeadm" 로 검색 한 후 설정

apt 패키지를 업데이트하고 ubernetes apt저장소를 사용하는 데 필요한 패키지를 설치한다.

sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl

Google Cloud 공개 서명 키를 다운로드

sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg

Kubernetes apt 리포지토리를 추가

echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list

패키지 인덱스를 업데이트 apt하고 kubelet, kubeadm 및 kubectl을 설치하고 해당 버전을 고정

sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

 

3. control-plane node 초기화

$ kubeadm init
...

## 완료가 되면 아래와 같은 메시지가 출력됨
  kubeadm join <control-plane-host>:<control-plane-port> --token <token> --discovery-token-ca-cert-hash sha256:<hash>

 

4. CNI 설치

아래 명령어로 weave network add-on을 설치합니다.

<weabenet 설치>

kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"

## 실행결과
serviceaccount/weave-net created
clusterrole.rbac.authorization.k8s.io/weave-net created
clusterrolebinding.rbac.authorization.k8s.io/weave-net created
role.rbac.authorization.k8s.io/weave-net created
rolebinding.rbac.authorization.k8s.io/weave-net created
daemonset.apps/weave-net created

2022.10.20 일 기준으로 kubectl 버전에 따라 위의 명령어가 수행되지 않을 경우, 아래 명령어를 수행한다

kubectl apply -f https://github.com/weaveworks/weave/releases/download/v2.8.1/weave-daemonset-k8s.yaml

<calico 설치>

1. operator 설치

kubectl apply -f https://github.com/coreos/flannel/raw/master/Documentation/kube-flannel.yml

2. calico 설정 파일 다운로드

curl https://raw.githubusercontent.com/projectcalico/calico/v3.24.3/manifests/custom-resources.yaml -O

3. calico 설치

kubectl create -f custom-resources.yaml

 

<flannel 설치>

주의할 점 : master node에서 컨트롤 플레인 설정 시 반드시 --pod-network-cidr=10.244.0.0/16 옵션으로 수행해야 한다

sudo kubeadm init --pod-network-cidr=10.244.0.0/16

아래 명령어로 flannel CNS를 설치한다.

kubectl apply -f https://github.com/coreos/flannel/raw/master/Documentation/kube-flannel.yml

 

 

5. node join

worker node에서 kubeadm join 수행

kubeadm join --token <token> <control-plane-host>:<control-plane-port> --discovery-token-ca-cert-hash sha256:<hash>

 

6. 클러스터 설치 확인

$ kubectl get nodes

NAME       STATUS   ROLES           AGE   VERSION
master     Ready    control-plane   10h   v1.25.3
worker-1   Ready    <none>          10h   v1.25.3
worker-2   Ready    <none>          10h   v1.25.3

 

🔒  node join 추가하기

🔑 : kubernetes.io 사이트에서 busybox 로 검색 한 후 설정

1. container runtime 설치

$ apt install containerd

2. kubeadm, kubectl, kubelet 설치

추가할 node에 kubernetes.io 의 문서를 참조하여 설치

 

3. kubeadm create -- 명령어로 join 명령어 추출

$ kubeadm token create --print-join-command

## 아래 IP는 각자의 master node ip
kubeadm join 10.178.0.29:6443 --token i9ty38.mujkeddsah1364iu --discovery-token-ca-cert-hash sha256:a172d4a560907269b1b6cc6f40bc1e16fa8092831f92b24515297eb7b5a50a51

4. node join 수행

kubeadm create 명령어로 추출한 명령어를 master node에서 수행

kubeadm join 10.178.0.29:6443 --token i9ty38.mujkeddsah1364iu --discovery-token-ca-cert-hash sha256:a172d4a560907269b1b6cc6f40bc1e16fa8092831f92b24515297eb7b5a50a51

5. node 확인

kubectl get nodes 로 추가된 node 확인

 

🔒  POD 생성하기(Busybox sleep 3600)

🔑 : kubernetes.io 사이트에서 busybox 로 검색 한 후 설정

아래 내용의 busybox.yaml 파일로 pod를 생성한다.

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'sleep 3600']

또는 아래 명령어를 수행한다.

kubectl run busybox --image=busybox --command -- sleep 3600

🔒  ETCD backup & restore

- etcdctl 설치

sudo apt install etcd-client

- etcd backup : etcd 프로세스를 grep 하면 프로세스에서 --trusted-ca-file, --cert-file, --key-file 옵션을 확인할 수 있다. 

각각 --cacert, --cert, --key 와 매칭된다. 마지막 snapshotdb는 백업파일명이다.

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 snapshotdb

Snapshot saved at snapshotdb

-etcd restore

ETCDCTL_API=3 etcdctl --endpoints 10.2.0.9:2379 snapshot restore snapshotdb

OR

ETCDCTL_API=3 etcdctl --data-dir <data-dir-location> snapshot restore snapshotdb

db를 restore 한 후 static pod 인 etcd 에 정보를 수정한다. static pod 의 yaml 파일은 /etc/kubernetes/manifests 디렉토리에 etcd.yaml 파일로 존재한다. 복구한 디렉토리 정보를 이 파일을 수정해 준다. 수정할 곳은 2군데이다.

복원된 etcd 정보는 etcd pod가 자동으로 적용된다. 복구되는 동안에는 kubectl 명령어가 hang 상태가 된다.

(복구하는데 시간이 약간 소요된다)

spec:
  containers:
  - command:
    - etcd
    - --advertise-client-urls=https://10.10.1.23:2379
    - --cert-file=/etc/kubernetes/pki/etcd/server.crt
    - --client-cert-auth=true
    - --data-dir=/var/lib/etcd ==> 복원한 디렉토리로 수정
    
    volumeMounts:
    - mountPath: /var/lib/etcd ==> 복원한 디렉토리로 수정
      name: etcd-data
    - mountPath: /etc/kubernetes/pki/etcd
      name: etcd-certs

 

 

 

🔒  kubernetes Upgrade

업그레이드할 버전 결정

apt update
apt-cache madison kubeadm
# 목록에서 최신 버전(1.24)을 찾는다
# 1.24.x-00과 같아야 한다. 여기서 x는 최신 패치이다.

컨트롤 플레인 노드 업그레이드

컨트롤 플레인 노드의 업그레이드 절차는 한 번에 한 노드씩 실행해야 한다. 먼저 업그레이드할 컨트롤 플레인 노드를 선택한다. /etc/kubernetes/admin.conf 파일이 있어야 한다.

"kubeadm upgrade" 호출

첫 번째 컨트롤 플레인 노드의 경우

kubeadm 업그레이드 : x 문자를 업그레이드하려는 버전의 문자로 바꾼다.

# 1.24.x-00에서 x를 최신 패치 버전으로 바꾼다.
apt-mark unhold kubeadm && \
apt-get update && apt-get install -y kubeadm=1.24.x-00 && \
apt-mark hold kubeadm

다운로드하려는 버전이 잘 받아졌는지 확인한다.

kubeadm version

업그레이드 계획을 확인한다.이 명령은 클러스터를 업그레이드할 수 있는지를 확인하고, 업그레이드할 수 있는 버전을 가져온다. 또한 컴포넌트 구성 버전 상태가 있는 표를 보여준다.

kubeadm upgrade plan

 

업그레이드할 버전을 선택하고, 적절한 명령을 실행한다. 예를 들면 다음과 같다.

# 이 업그레이드를 위해 선택한 패치 버전으로 x를 바꾼다.
sudo kubeadm upgrade apply v1.24.x

 

명령이 완료되면 다음을 확인해야 한다.

[upgrade/successful] SUCCESS! Your cluster was upgraded to "v1.24.x". Enjoy! 
[upgrade/kubelet] Now that your control plane is upgraded, please proceed with upgrading your kubelets if you haven't already done so.

 

CNI 제공자 플러그인을 수동으로 업그레이드한다.

 

다른 컨트롤 플레인 노드의 경우

첫 번째 컨트롤 플레인 노드와 동일하지만 다음을 사용한다.

sudo kubeadm upgrade node

 

kubeadm upgrade plan 을 호출하고 CNI 공급자 플러그인을 업그레이드할 필요가 없다

노드 드레인

  • 예약 불가능으로 표시하고 워크로드를 제거하여 유지 관리를 위해 노드를 준비합니다.
  • # <node-to-drain>을 드레인하는 노드의 이름으로 바꾼다.
    kubectl drain <node-to-drain> --ignore-daemonsets

kubelet과 kubectl 업그레이드

  • 모든 컨트롤 플레인 노드에서 kubelet 및 kubectl을 업그레이드한다.
# replace x in 1.24.x-00의 x를 최신 패치 버전으로 바꾼다
apt-mark unhold kubelet kubectl && \
apt-get update && apt-get install -y kubelet=1.24.x-00 kubectl=1.24.x-00 && \
apt-mark hold kubelet kubectl
  • kubelet을 다시 시작한다.
sudo systemctl daemon-reload
sudo systemctl restart kubelet

노드 uncordon

  • 노드를 스케줄 가능으로 표시하여 노드를 다시 온라인 상태로 전환한다.
  • # <node-to-drain>을 드레인하는 노드의 이름으로 바꾼다.
    kubectl uncordon <node-to-drain>

워커 노드 업그레이드

워커 노드의 업그레이드 절차는 워크로드를 실행하는 데 필요한 최소 용량을 보장하면서, 한 번에 하나의 노드 또는 한 번에 몇 개의 노드로 실행해야 한다.

kubeadm 업그레이드

  • 모든 워커 노드에서 kubeadm을 업그레이드한다.
# 1.24.x-00의 x를 최신 패치 버전으로 바꾼다
apt-mark unhold kubeadm && \
apt-get update && apt-get install -y kubeadm=1.24.x-00 && \
apt-mark hold kubeadm

"kubeadm upgrade" 호출

  • 워커 노드의 경우 로컬 kubelet 구성을 업그레이드한다.
  • sudo kubeadm upgrade node
    

노드 드레인(master node에서 수행)

  • 스케줄 불가능(unschedulable)으로 표시하고 워크로드를 축출하여 유지 보수할 노드를 준비한다.
  • # <node-to-drain>을 드레이닝하려는 노드 이름으로 바꾼다.
    kubectl drain <node-to-drain> --ignore-daemonsets
    

kubelet과 kubectl 업그레이드

  • kubelet 및 kubectl을 업그레이드한다.
# 1.24.x-00의 x를 최신 패치 버전으로 바꾼다
apt-mark unhold kubelet kubectl && \
apt-get update && apt-get install -y kubelet=1.24.x-00 kubectl=1.24.x-00 && \
apt-mark hold kubelet kubectl
  • kubelet을 다시 시작한다.
sudo systemctl daemon-reload
sudo systemctl restart kubelet

노드에 적용된 cordon 해제(master node에서 수행)

  • 스케줄 가능(schedulable)으로 표시하여 노드를 다시 온라인 상태로 만든다.
  • # <node-to-drain>을 노드의 이름으로 바꾼다.
    kubectl uncordon <node-to-drain>

클러스터 상태 확인

모든 노드에서 kubelet을 업그레이드한 후 kubectl이 클러스터에 접근할 수 있는 곳에서 다음의 명령을 실행하여 모든 노드를 다시 사용할 수 있는지 확인한다.

kubectl get nodes

모든 노드에 대해 STATUS 열에 Ready 가 표시되어야 하고, 버전 번호가 업데이트되어 있어야 한다

 

🔒  json format 출력

🔑 : jsonpath 형식으로 출력

 

 

🔒  디플로이먼트 업데이트

 

🔑 : 다음 단계에 따라 디플로이먼트를 업데이트한다.

nginx:1.14.2 이미지 대신 nginx:1.16.1 이미지를 사용하도록 nginx 파드를 업데이트 한다.

kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.16.1

 

또는 다음의 명령어를 사용한다.

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1

 

 

대안으로 디플로이먼트를 edit 해서 .spec.template.spec.containers[0].image 를 nginx:1.14.2 에서 nginx:1.16.1 로 변경한다.

kubectl edit deployment/nginx-deployment

다음과 유사하게 출력된다.

deployment.apps/nginx-deployment edited

롤아웃 상태를 보려면 다음을 실행한다

kubectl rollout status deployment/nginx-deployment

 

 

업데이트된 디플로이먼트에 대해 자세한 정보 보기

  • 롤아웃이 성공하면 kubectl get deployments 를 실행해서 디플로이먼트를 볼 수 있다. 이와 유사하게 출력된다.
  • NAME               READY   UP-TO-DATE   AVAILABLE   AGE
    nginx-deployment   3/3     3            3           36s

kubectl get rs 를 실행해서 디플로이먼트가 새 레플리카셋을 생성해서 파드를 업데이트 했는지 볼 수 있고, 새 레플리카셋을 최대 3개의 레플리카로 스케일 업, 이전 레플리카셋을 0개의 레플리카로 스케일 다운한다.

kubectl get rs

 

이와 유사하게 출력된다.

NAME                          DESIRED   CURRENT   READY   AGE
nginx-deployment-1564180365   3         3         3       6s
nginx-deployment-2035384211   0         0         0       36s

 

 

 

 

🔒  trouble shooting

 - kubelet, controller-manager, apiserver 등등 상태 분석

 - node 에 대해 describe, log 분석

 - pod에 대해 describe, log 분석

 - kubelet, controller-manager, apiserver 등등 상태 분석

  - 

 

🔒  kubernetes cluster 구성(with kubeadm 으로 설치)

- docker는 설치되어 있으니까, control plane에서 kubeadm(kubelet 이 같이 설치됨), CNI를 설치하고 worker node에서 kubeadm(kubelet 이 같이 설치됨)을 설치한 후 master node에 join 한다.

kubernetes 문서에서는 다 설치하는 것으로 설명되어 있으니 전체를 설치한다.

 

1) 6443 port가 사용하지 않고 있는지 확인(6443 port는 apiserver에서 사용할 port)

 - telnet 이나 nc 명령어로 확인

nc 127.0.0.1 6443

 

2) kubeadm, kubelet and kubectl 설치

sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

3) control-plane node 초기화

kubeadm init

4) 환경 설정

일반 user로 kubectl 명령어를 사용하기 위해 아래 명령어를 수행

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

root 는 아래 명령어 수행

echo "export KUBECONFIG=/etc/kubernetes/admin.conf" >> ~/.bashrc

 

5) CNI 설치

공식문서에서 CNI 설치 명령어를 찾을 수 없음.

how ? 별도 url 에서 찾는다. <<< 문서를 찾는 단어를 찾아본다 >> v1-2... 이런게 있었던거 같다.

 CNI 설치(flannel or weave-net)

 

 

🔒 참고

 

pod spec의 arg와 command 차이

command는 docker 의 ENTRYPOINT이고 arg는 CMD이다.

 

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

쿠버네티스 - play with k8s  (0) 2022.10.20
쿠버네티스 설치 - unbutu 22.04  (0) 2022.06.27
쿠버네티스 보충  (0) 2022.06.08
CKA 자격증 취득하기 #2  (0) 2022.05.23
CKA 자격증 취득하기 #1  (0) 2022.05.18

 

왜 ingress를 써야 하나?

 

service는 서비스당 하나의 port 만을 open할 수 있기 때문에 서비스가 많아진다.

반면, 인그레스는 포트는 하나만 open하고 도메인이나 path로 서비스를 분기해 줄 수 있기 때문이다.

 

sslip.ip는 임시로 도메인을 생성해 준다.

ingress 테스트시 사용할 수 있다.

 

 

Kubectl 자동 완성

BASH

source <(kubectl completion bash) # bash-completion 패키지를 먼저 설치한 후, bash의 자동 완성을 현재 셸에 설정한다
echo "source <(kubectl completion bash)" >> ~/.bashrc # 자동 완성을 bash 셸에 영구적으로 추가한다

또한, kubectl의 의미로 사용되는 약칭을 사용할 수 있다.

alias k=kubectl
complete -F __start_kubectl k

자동완성 기능이 활성화되지 않을 경우 bash_completion 이 설치되어 있는지 확인하여, 설치가 되어 있지 않을 경우 설치해 준다.

apt-get install bash_completion

 

kubetl 명령어 뒤에 올 수 있는 type이나 

kubectl completion bash > /etc/bash_completion.d/kubectl

 

kubectx, kubens 는?

kubectx란?

  • 다중클러스터 사용시 클러스터 전환을 쉽게 해주는 플러그인 툴

kubens란?

  • k8s cluster 내에 namespace를 쉽게 전환해주는 플러그인 툴

kubetail

pod 의 로그를 확인

 

 

ETCD 데이터 조회


ETCDCTL_API=3 etcdctl --endpoints=https://[10.10.1.23]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key get --prefix=true "" > /tmp/prefix

cat /tmp/prefix | nl | tail 
cat /tmp/prefix | nl | grep -i 'pod":"busybox-sleep-less'

 

 

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

쿠버네티스 설치 - unbutu 22.04  (0) 2022.06.27
CKA 자격증 취득하기 - 시험예상 문제  (0) 2022.06.09
CKA 자격증 취득하기 #2  (0) 2022.05.23
CKA 자격증 취득하기 #1  (0) 2022.05.18
쿠버네티스 - secret  (0) 2022.05.18

섹션6: Cluster Maintenance

- cluster upgrade 할 때

pod upgrade 및 backup & recover kubernetes cluster

 

119. OS Upgrades

OS upgrade를 해야 할 경우, replicaset 이 설정된 pod는 다른 node로 옮겨진다.단일 pod인 경우에는 서비스가 안된다.

이럴경우 pod를 다른 node로 옮긴 후 대상 node를 업그레이드한다.

 

 - cordon : pod를 다른 node로 옮기지 않는다.

 - drain : pod를 다른 node로 옮긴다.

 

kubectl cordon $NODENAME

node를 drain 한다.(pod를 다른 node로 옮긴다.)

kubectl drain $NODENAME --ignore-daemonsets

다시 node를 scheuling 상태로 변경한다.

kubectl uncordon $NODENAME

 

 

122. Kubernetes Software Versions

kubectl get nodes 의 VERSION 항목 : v1.24.1

- v1: major version, 24: minor version, 1 : patch version

alpha -> beta -> stable 버전

kube-apiserver, kube-controller-manger, kube-scheduler, kubelet, kube-proxy, kubectl 은 같은 버전

etcd, coreDNS는 버전이 다름.

 

124. Cluster Upgrade Process

모든 컴포넌트가 같은 버전이어야 하는가? 그렇지는 않다. 단, apiserver 버전보다는 높을 수 없다.

그러나, kubectl 은 apiserver 버전보다 한단계 높을 수 있다.

Kubernetes supports only up to the recent three minor versions.

Kubernetes는 최신 3개의 마이너 버전까지만 지원합니다.

 

master node upgrade

- 마스터 노드 업그레이 동안 마스터 노드의 컴포넌트를 사용할 수 없는 상태가 된다. 그러나 worker node의 pod 는 사용할 수 있다. kubectl 로 master node에 접근할 수 없다. upgrade가 완료되면 정상적으로 작동한다.

 

worker node upgrade

 방법1)  downtime을 가지고 worker node 전체를 업그레이드 한다.

 방법2) worker node 한대씩 업그레이드 한다.

 방법3) 업그레이드된 worker node 를 추가하여 node를 교체한다.

 

* kubeadm upgrade

- kubeadm upgrade plan

- kubeadm upgrade apply

=> kubeadm은 kubelet을 업그레이드하지 않는다. kubeadm을 업그레이드 한 후 kubelet을 업그레이드한다. kubelet을 재시작한다. 

----------------- upgrade 순서 --------------

kubeadm upgrade -> kubernetes component upgrade(apiserver, scheduler 등) -> kubelet upgrade

 

 

128. Backup and Restore Methods

- resource configuration : files, GitHub로 저장, kubeapi

- ETCD Cluster : data directory(etcdctl snapshot save snapshot.db 명령어로 백업, etcdctl snapshot restore snapshot.db --data-dir=/backup-dir)

- Persistent Volume

 

섹션7: Security

136. Kubernetes Security Primitives

- Network Policies

 137. Authentication

 

Accounts

139. TLS Introduction

 

140. TLS Basics

141. TLS in Kubernetes

 

151. API Groups

 

152. Authorization

 

153. Role Based Access Controls

 

<<here>>

155. Cluster Roles and Role Bindings

 

157. Service Accounts

 

159. Image Security
 
161. Security Contexts
 

163. Network Policy
164. Developing network policies
 

섹션8: Storage

 

- storage drivers

- volume drivers

 

169. Storage in Docker

- File System

- Layered architecture

storage deivers : AUFS, ZFS, BTRFS, Device Mapper, Overlay, Overlay2

 

170. Volume Driver Plugins in Docker

volume driver : local, Azure File Storage, Convoy, DigialOcean Block Storage, Flocker, gce-docker, GlusterFS, NetApp, RexRay, Portworx, VMware vSphere Storage 

 

 

171. Container Storage Interface (CSI)

 

 

173. Volumes

vloume Types : Directory(standalone node), 

storage type solution : KFS, ClusterFS, Flocker, ceph, SCALEIO, AWS ebs, GCP, Azure

 

173. Persistent Volumes

스토리지를 중앙에서 관리하고자 할 때, 관리자가 대규모 스토리지 풀을 생성해서 관리합니다.
그런 다음 사용자가 필요한 스토리지를 사용하도록 합니다.
이것이 영구 볼륨이 필요한 이유입니다.

 

 

 

173. Persistent Volume Claims

노드에서 스토리지를 사용할 수 있도록 영구 볼륨 클레임을 생성합니다. 영구 볼륨 및 영구 볼륨 클레임은 Kubernetes 에서 두 개의 개별 오브젝트입니다.
관리자가 영구 볼륨 세트를 생성하고 사용자가 영구 볼륨 클레임을 생성하여 영구 볼륨을 사용합니다.

PVC & PV -> Binding(1:1)

PVC를 삭제할 때 PV는 PV policy 에 따름(Retain, Recycle, 그리고 Delete가 있다)

Using PVCs in PODs

PVC를 생성하고 나면 다음과 같이 볼륨 섹션의 PersistentVolumeClaim 섹션에서 PVC 클레임 이름을 지정하여 POD 정의 파일에서 사용합니다.

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
    - name: myfrontend
      image: nginx
      volumeMounts:
      - mountPath: "/var/www/html"
        name: mypd
  volumes:
    - name: mypd
      persistentVolumeClaim:
        claimName: myclaim
 

ReplicaSets or Deployments 도 동일합니다. Deployment on ReplicaSet의 template section 에 PVC를 정의합니다.

  • HostPath: 볼륨 자체에는 scheduling 정보가 포함되어 있지 않습니다. 노드의 각 포드를 수정하려면 해당 포드에 대해 nodeSelector와 같은 scheduling 정보를 구성해야 합니다.
  • Local: 볼륨 자체에는 scheduling 정보가 포함되어 있으며 이 볼륨을 사용하는 포드는 특정 노드에 고정되어 데이터 연속성을 보장할 수 있습니다.

- volumeMounts: 의 name:은 volume 에서 정의한 name: 값을 사용해야 합니다.

- PVC를 사용하는 pod가 있을 때는 삭제 시 pending 상태가 됩니다.

 

 

181. Storage Class

pod에 스토리지 연결 : PV -> PVC -> Volumes -> VolumeMounts

만일, google 의 스토리지를 연결하려면 ?

SC ->  PVC -> Volumes -> VolumeMounts

 

Dynamic Provisioning

apiVersion: storage.k8s.io/v1

king: StorageClass

 

섹션9: Networking

<<HRRE>> START(22.06.28)

 

185. Prerequisite - Switching Routing

switching & routing

- switching

- routing

- gateway

 

 

185. Prerequisite - Switching Routing

- ip link

- ip addr add 192.168.1.10/24 dev eth0

- ip addr add 192.168.1.11/24 dev eth0

Switching : 같은 네트워크에서 통신할 수 있도록 해주는 장비

Routing : 같은 네트워크에서 통신할 수 있도록 해주는 장비

 

ip route add 192.168.2.0/24 via 192.168.1.1 은 192.168.2.0/24 과 통신하기 위해서는 192.168.1.1 를 통하라 라는 의미임.

네트워크 인터페이스가 하나이면 default gateway만 있으면 되지만, 네트워크 인터페이스가 2개 이상인 경우에는 각각 gateway를 설정할 수 있다. 아래 그림에서 C 서버는 192.168.2.1로 설정되어 있고, D 서버는 192.168.2.2 로 설정된 경우 C 서버는 인터넷과 연결되지만 D 서버는 연결되지 않는다.

 

 

 

186. Prerequisite - DNS

DNS 서버

DNS

- DNS Configuration on linux

- CoreDNS

Networkn namespace

Docker Networking

/etc/hosts 

* 관리하는 대상 서버들이 많을 경우 hosts 파일로 서버명을 관리하는 것은 비효율적임(IP가 변경되거나 서버가 추가되면 모든 서버의 hosts 파일을 변경해줘야 함). 그래서 하나의 서버에서 관리하는 개념이 DNS 서버임.

/etc/resolv.conf(search, nameserver 설정)

/etc/nsswitch.conf

name으로 host를 찾는 순서는 기본적으로 hosts 파일 -> DNS 서버 순서임. 그러나 nsswitch.conf 파일에서 순서를 변경할 수 있음nsswitch.conf 는 /etc 디렉토리 밑에 있으며 파일안의 hosts 항목을 hosts: dns files 로 변경하면 hostname을 찾을 때 dns 서버 먼저 찾고 없을경우 local 서버의 hosts 파일을 찾는다.

 

관련 명령어 : nslookup, dig

 

 

 

 

187. Prerequisite - CoreDNS

설치

coredns는 hosts 파일 또는 Corefile을 참조한다.

 

188. Prerequisite - Network Namespaces

집을 비유하면 host는 집이고 Network Namespaces는 각각의 방으로 생각하면 됨.

컨테이너는 namespace로 구분된다. 컨테이너 각자는 routing table과 ARP table을 가지고 있다.

 

linux에서 network namespace 생성

- ip netns add red

- ip netns add blud

ip netns 로 확인

 

container의 interface를 확인

ip netns exec red ip link(ip -n red link 도 동일)

 

컨테이너에 IP 할당

1) 가상 인터페이스 추가 : ip link add veth-red type veth peer name vech-blue

2) 가상 인터페이스를 네임스페이스에 할당 : ip link set veth-red netns red

3) 가상 인터페이스를 네임스페이스에 할당 : ip link set veth-blue netns blue

 

4) IP 할당 : ip -n red addr add 192.168.15.1 dev veth-red

5) IP 할당 : ip -n blue addr add 192.168.15.2 dev veth-blue

 

6) ip -n red link set veth-red up

6) ip -n blue link set veth-blue up

두 개의 컨테이너가 통신가능

ip netns exec red ping 192.168.15.2

여러개의 컨테이너가 있을 경우 가상 스위치를 설치한다.

- 가상스위치 : LINUX Bridge, Open vSwitch

 

가상스위치 설정 방법(Linux Bridge)

ip link add v-net-0 type bridge

 

 

 

While testing the Network Namespaces, if you come across issues where you can't ping one namespace from the other, make sure you set the NETMASK while setting IP Address. ie: 192.168.1.10/24

 

ip -n red addr add 192.168.1.10/24 dev veth-red

 

Another thing to check is FirewallD/IP Table rules. Either add rules to IP Tables to allow traffic from one namespace to another. Or disable IP Tables all together (Only in a learning environment).

 

 

190. Prerequisite - Docker Networking

 

191. Prerequisite - CNI

 

192. Cluster Networking

 

쿠버네티스 사이트에서 weavenet CNI 를 설치하는 명령어가 있는 url.( CKA 문제 중 클러스터를 구성하라는 문제가 나올 경우 CNI를 설치해야 하는데 쿠버네티스 웹페이지의 설치 문서에는 명령어가 없고 외부 url과의 링크만 되어 있다. 시험에서는 쿠버네티스 웹페이지 이외에는 접속할 수 없다. 아래 URL 접속 경로를 잘 익혀서 시험에 활용한다.

참고로 (2022.06.29 현재) 시험제도가 조금 변경되어서 즐겨찾기를 이용할 수 없다.

https://v1-22.docs.kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/#steps-for-the-first-control-plane-node (step 2)

 

ip a | grep -B2 10.13.214.10

* -B + number : 숫자만큼 이전 라인수를 보여준다.

 

196. Pod Networking

Networking Model

- Every POD should have an IP address

- Every POD should be able to communicate with every other POD in the same node

- Every POD should be able to communicate with every other POD on other nodes without NOT.

 

 

 

197. CNI in kubernetes

- container runtime must create network namespace

- Identify network the container must attach to

- container runtime to invoke network Plugin(bridge) when container is ADDed

- container runtime to invoke network Plugin(bridge) when container is DELeted

- JSON format of the network configuration

 

 

 

198. CNI weave

 

 

 

201. Practice Test - Deploy Network Solution

 

203. IP Address Management - Weave

 

 

206. Service Networking

 

209. DNS in kubernetes

 

210. CoreDNS in Kubernetes

 

213. Ingress
 
 
 

 

섹션10: Design and Install a kubernetes cluster

221. Design a Kubernetes Cluster

 

222. Choosing Kubernetes Infrastructure

- local host

- minikube

- kubeadm

 

Turnkey solution

- OpenShift : CI/CD

- Cloud Foundry Container Runtime

- VMWare Cloud PKS

- Vagrant

 

Hosted solutions(Managed service)

- GKE, AKS, EKS, OpenShift online

 

223. Configure High Availability

single master -> multiple master node, API Server 앞에 LB(Load Balancer : nginx, HAproxy 등을 둔다)

single master 클러스터에서 master node에 장애가 생기면worker node의 컨테이너는 계속 수행된다.

새로운 node나 pod를 추가할 수  없다. master node에 대한 장애 대비로 마스터 노드를 다수로 구성할 수 있다.

 

224. ETCD in HA

- default 2379 port 사용

multiple ETCD는 모두 active 모드(read/write 가능)

다른 ETCD에서 write가 발생하면 내부적으로 leader와 follower로 구분하여 follower 로 write로 요청이 오면,

leader로 write을 보낸다. leader는 follower에 데이터를 동기화한다.

 

leader election - RAFT

 

섹션11: Install a kubernetes cluster with kubeadm

master, worker1, worker2

1. docker 전체 설치

2. kubeadm 전체 설치

3. initialize(master node only)

4. CNI(master node only) : POS Network

5. join(worker node)

  master node worker node1 worker node2
docker 설치
kubeadm 설치
(kubelet, kubectl 포함)
master initialize    
POD network(CNI)    
join   

- vagrant 로 설치

- kubeadm 으로 설치

 

 

섹션12: end to end test on a kubernetes cluster

As per the CKA exam changes (effective September 2020), End to End tests is no longer part of the exam and hence it has been removed from the course.

 

If you are still interested to learn this, please check out the complete tutorial and demos in our YouTube playlist:

https://www.youtube.com/watch?v=-ovJrIIED88&list=PL2We04F3Y_41jYdadX55fdJplDvgNGENo&index=18

 

섹션13: trouble shooting

 

235. Application Failure

 

user - WEB-service - WEB - DB-service - DB

checking

check WEB-service

curl http://IP:port check

kubectl describe service web-service

 

check POD

kubectl get pod 

kubectl describe pod 

kubectl get events

kubectl logs web -f --previous

 

check DB-service

 

check DB

 

238. Control Plane Failure

service kube-apiserver status

service kube-controller-manager status

service kube-scheduler status

 

service kubelet status

service kube-proxy status

 

check service logs

- kubectl logs kube-apiserver -n kube-system

 

241. Worker Node Failure

 

246. Pre-Requisites - JSON PATH

 

 

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

DEVOPS15

 

 

 

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

CKA 자격증 취득하기 - 시험예상 문제  (0) 2022.06.09
쿠버네티스 보충  (0) 2022.06.08
CKA 자격증 취득하기 #1  (0) 2022.05.18
쿠버네티스 - secret  (0) 2022.05.18
쿠버네티스 - configmap  (0) 2022.05.18

시험 준비를 하며

 

- 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

secret 만들기

3가지 타입으로 만들수 있슴.

 

systax : kubectl create secret <available command> name [flags] [options]

  • docker-registry
  • generic
  • tls

secret 사용하기

  • environment variable 로 전달 : secretkeyRef 사용
  • command line argument 로 전달
  • volume 에 secret을 사용하여 컨테이너 디렉토리로 mount
  •  

secret 데이터 용량

secret ectd에 암호화하지 않은 텍스트로 저장되므로 secret value가 커지면 메모리를 많이 차지함

secret의 최대 크기는 1MB

configMap도 동일하게 용량이 제한됨.

 

 

configMap과 secret

 

configMap : 컨테이너 구성정보를 한곳에 관리

secret : 컨테이너가 사용하고 있는 password, auth token, ssh key 와 같은 중요한 정보를 저장하고 민감한 정보를 base64로 인코딩해서 한 곳에 모아서 관리

- 민감하지 않는 정보는 configMap으로 관리하고 민감한 정보는 secret로 관리

secret 데이터 전달 방법

- command line argument

- environment variable

- volume mount

 

 

 

 

 

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

CKA 자격증 취득하기 #2  (0) 2022.05.23
CKA 자격증 취득하기 #1  (0) 2022.05.18
쿠버네티스 - configmap  (0) 2022.05.18
쿠버네티스 - configmap  (0) 2022.05.18
쿠버네티스 - label & annotation  (0) 2022.05.18

 

pod 컨테이너의 구성정보나 환경정보 등을 한 곳에서 관리.

configmap는 API

 

  • ConfigMap 생성
  • ConfigMap 일부 적용
  • ConfigMap 전체 적용
  • ConfigMap 을 볼륨으로 적용하기

 

ConfigMap 생성

configMap : 컨테이너 구성정보를 key-value 형태로 한곳에 모아서 관리

 

ConfigMap 일부 적용

configMap의 key를 pod의 컨테이너에 적용

configMapKeyRef 사용

ConfigMap 전체 적용

configMapRef 사용

ConfigMap 을 볼륨으로 적용하기

mountpath 로 볼륨을 지정

 

 

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

CKA 자격증 취득하기 #1  (0) 2022.05.18
쿠버네티스 - secret  (0) 2022.05.18
쿠버네티스 - configmap  (0) 2022.05.18
쿠버네티스 - label & annotation  (0) 2022.05.18
쿠버네티스 Cluster 설치하기 - on centos linux  (0) 2022.05.17

+ Recent posts