brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Jun 27. 2021

쿠버1탄-4. 쿠버네티스 구성요소

다음은 쿠버네티스 스터디 자료를 참고해  정리한 내용입니다.


<1> 사전 확인 사항

<2>  쿠버네티스 클러스터 확인

<3>   kubens  , kubectx   유틸 사용 (선택)

<4>  프롬프트 변경하는 kube-ps1 유틸  (선택)

<5>  k8s 구성 요소 확인 -  노드 정보

<6>  k8s  마스터 노드의 구성 요소  확인

<7>  k8s  워커 노드의 구성 요소 확인

<8> Pod 배포 해보기

<9> GCR (구글 컨테이너 저장소)의 샘플 이미지로 Pod 배포

<10> Deployment 배포

<11> 다음 과정 보기



<1> 사전 확인 사항


1

클러스터 설치가 되어 있는지 확인?


도메인 없는 경우 클러스터 설치법

https://brunch.co.kr/@topasvga/1681


도메인이 있는경우 설치법

https://brunch.co.kr/@topasvga/1649



2

싱가포르  리전에서 테스트

EC2 접속

admin role 할당  또는 Clouud9에 admin role 할당 사용

여기서는 EC2에  admin role 할당 후 테스트한다.


쿠버네티스 master API 서버 로그인 

ssh -i ~/.ssh/id_rsa ubuntu@api.k8s.serverchk.com


3

Master API서버에서 자동완성 설정

# kubectl 자동완성 기능

source <(kubectl completion bash)

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


# (옵션) 단축키 : alias kubectl to k 

echo 'alias k=kubectl' >> ~/.bashrc

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



4

kubectl api-resources

ubuntu@ip-172-20-41-255:~$ kubectl api-resource


5

네임스페이스와 네임스페이스간 구분이 된다.


네임 스페이스 확인

kubectl get namespaces


ubuntu@ip-172-20-41-255:~$ kubectl get namespaces

NAME              STATUS   AGE

default           Active   2d16h

kube-node-lease   Active   2d16h

kube-public       Active   2d16h

kube-system       Active   2d16h


6

네임 스페이스에 pod가 있는지 확인 ?

default namespace 에는 없다고 나옴

 k get pod


ubuntu@ip-172-20-41-255:~$ k get pod

No resources found in default namespace.


7

kube-system의 pod를 보자

k get pod -n kube-system






<2>  쿠버네티스 클러스터 확인


1

API 서버 동작 확인 

kubectl cluster-info


root@ip-172-20-41-255:/tmp# kubectl cluster-info

Kubernetes control plane is running at https://api.k8.serverchk.com

CoreDNS is running at https://api.k8.serverchk.com/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.



2

노드 정보 확인

kubectl get nodes


ubuntu@ip-172-20-46-78:~$ kubectl get nodes

NAME                                               STATUS   ROLES                  AGE     VERSION

ip-172-20-46-78.ap-southeast-1.compute.internal  Ready  control-plane,master   6d11h   v1.20.7

ip-172-20-49-236.ap-southeast-1.compute.internal   Ready    node                   6d11h   v1.20.7

ip-172-20-61-135.ap-southeast-1.compute.internal   Ready    node                   6d11h   v1.20.7



3

네임 스페이스 확인

kubectl get namespaces


root@ip-172-20-41-255:/tmp# kubectl get namespaces

NAME              STATUS   AGE

default           Active   29m

kube-node-lease   Active   29m

kube-public       Active   29m

kube-system       Active   29m



4

파드 정보 확인 - kube-system 네임스페이스에서

kubectl get pod -n kube-system





5

kubectl 툴

KUBECONFIG ($HOME/.kube/config) 설정 파일을 참조하여, 마스터 주소, 인증 정보 등을 관리. 


.kube/config 권한 인증 로드 확인

디버그 명령어로 내용 확인

kubectl get pods -v9


ubuntu@ip-172-20-46-78:~$ kubectl get pods -v9

I0626 23:36:44.907062 2866232 loader.go:379] Config loaded from file:  /home/ubuntu/.kube/config

// 사용자에 대한 정보들이 들어가 있다.




<3>   kubens  , kubectx   유틸 사용 (선택)


1

클러스터 와 네임스페이스 변경 유틸?

git clone https://github.com/ahmetb/kubectx /opt/kubectx

ln -s /opt/kubectx/kubens /usr/local/bin/kubens

ln -s /opt/kubectx/kubectx /usr/local/bin/kubectx



2

네임스페이스 변경 유틸?

kubens


ubuntu@ip-172-20-46-78:~$ kubens

default

kube-node-lease

kube-public

kube-system


3

네임 스페이스 변경

 kubens kube-system


root@ip-172-20-41-255:/tmp# kubens kube-system

Context "k8.serverchk.com" modified.

Active namespace is "kube-system".


변경 확인 ?

kubens

root@ip-172-20-41-255:/tmp# kubens

default

kube-node-lease

kube-public

kube-system



4

원래의 디폴트 네임스페이스로 변경

kubens -

root@ip-172-20-41-255:/tmp# kubens -

Context "k8.serverchk.com" modified.

Active namespace is "default".


kubectl get pod

root@ip-172-20-41-255:/tmp# kubectl get pod

No resources found in default namespace.




<4>  프롬프트 변경하는 kube-ps1 유틸  (선택)


프롬프트  설정 ?

1

cd


2

git clone https://github.com/jonmosco/kube-ps1.git


3

vim .bashrc


맨아래  source <(kubectl completion bash)  대신 

source ~/kube-ps1/kube-ps1.sh

PS1='[\u@\h:\w $(kube_ps1)]\$ '

KUBE_PS1_SYMBOL_ENABLE=false


4

# 적용

source ~/.bashrc


5

# kubernetes-admin@kubernetes 를 kube

sed -i "s/kubernetes-admin@kubernetes/kube/g" ~/.kube/config


6

kubeoff

kubeon


kubeoff

[root@ip-172-20-46-78:~ (k8s.serverchk.com:default)]# kubeoff


kubeon

[root@ip-172-20-46-78:~ ]# kubeon

[root@ip-172-20-46-78:~ (k8s.serverchk.com:default)]#





<5>  k8s 구성 요소 확인 -  노드 정보


1

Master API에 로그온헤 확인

ssh -i ~/.ssh/id_rsa 

ubuntu@api.k8s.serverchk.com


2

kubectl get nodes


Ready  를 확인한다.

ubuntu@ip-172-20-46-78:~$ kubectl get nodes

NAME                                               STATUS   ROLES                  AGE     VERSION

ip-172-20-46-78.ap-southeast-1.compute.internal  Ready  control-plane,master   6d11h   v1.20.7

ip-172-20-49-236.ap-southeast-1.compute.internal   Ready    node                   6d11h   v1.20.7

ip-172-20-61-135.ap-southeast-1.compute.internal   Ready    node                   6d11h   v1.20.7



3

nodes 정보 확인

kubectl get nodes -o wide


ubuntu@ip-172-20-46-78:~$ kubectl get nodes -o wide

NAME                                               STATUS   ROLES                  AGE     VERSION   INTERNAL-IP     EXTERNAL-IP    OS-IMAGE             KERNEL-VERSION   CONTAINER-RUNTIME

ip-172-20-46-78.ap-southeast-1.compute.internal    Ready    control-plane,master   6d11h   v1.20.7   172.20.46.78    13.250.58.93   Ubuntu 20.04.2 LTS   5.4.0-1045-aws   containerd://1.4.4

ip-172-20-49-236.ap-southeast-1.compute.internal   Ready    node                   6d11h   v1.20.7   172.20.49.236   52.76.67.50    Ubuntu 20.04.2 LTS   5.4.0-1045-aws   containerd://1.4.4

ip-172-20-61-135.ap-southeast-1.compute.internal   Ready    node                   6d11h   v1.20.7   172.20.61.135   13.212.239.0   Ubuntu 20.04.2 LTS   5.4.0-1045-aws   containerd://1.4.4


4

nodes 중  Master node 정보 확인

kubectl describe node ip-172-20-46-78.ap-southeast-1.compute.interna






<6>  k8s  마스터 노드의 구성 요소  확인


1

파드 정보 출력(default 네임스페이스) 

디폴트에는 pod가 없다.

 kubectl get pod


[root@ip-172-20-41-255:~ (k8.serverchk.com:default)]#  kubectl get pod

No resources found in default namespace.


2

모든 namespaces에서 pod 가져오기

kubectl get pod --all-namespaces



3

kube-system에서 pod정보 가져오기

kubectl get pod -n kube-system


[root@ip-172-20-41-255:~ (k8.serverchk.com:default)]# kubectl get pod -n kube-system

NAME                                                                          READY   STATUS    RESTARTS   AGE

calico-kube-controllers-cc8b58cdf-66hnt               1/1     Running        0          47m

calico-node-4n9j6                                                        1/1     Running   0          47m

calico-node-mrkcw                                                     1/1     Running   0          46m

calico-node-qm6ht                                                    1/1     Running   0          46m

coredns-5489b75945-hqkg2                                    1/1     Running   0          45m

coredns-5489b75945-nj4gx                                     1/1     Running   0          47m

coredns-autoscaler-6f594f4c58-mj2rp                 1/1     Running   0          47m

dns-controller-f6fbbfd67-98z7v                             1/1     Running   0          47m

etcd-manager-events-ip-172-20-41-255.ap-northeast-1.compute.internal   1/1  Running  0   46m

etcd-manager-main-ip-172-20-41-255.ap-northeast-1.compute.internal    1/1   Running   0   46m

kops-controller-9fbqg                                            1/1     Running   0      46m

kube-apiserver-ip-172-20-41-255.ap-northeast-1.compute.internal    2/2     Running   1          46m

kube-controller-manager-ip-172-20-41-255.ap-northeast-1.compute.internal 1/1 Running 0 46m

kube-proxy-ip-172-20-38-114.ap-northeast-1.compute.internal     1/1     Running   0          46m

kube-proxy-ip-172-20-38-144.ap-northeast-1.compute.internal     1/1     Running   0          46m

kube-proxy-ip-172-20-41-255.ap-northeast-1.compute.internal      1/1     Running   0          46m

kube-scheduler-ip-172-20-41-255.ap-northeast-1.compute.internal  1/1     Running   0          46m


// coredns-autoscaler-6f594f4c58-mj2rp   COREDNS에 AUTOSCALER가 있네요~~



4

kubectl get pod -n kube-system -o wide | egrep '(NAME|coredns)'


ubuntu@ip-172-20-41-255:~$ kubectl get pod -n kube-system -o wide | egrep '(NAME|coredns)'

NAME                                                                       READY   STATUS    RESTARTS   AGE     IP               NODE                                               NOMINATED NODE   READINESS GATES

coredns-5489b75945-hqkg2                                                   1/1     Running   0          2d20h   100.99.166.2     ip-172-20-38-114.ap-northeast-1.compute.internal   <none>           <none>

coredns-5489b75945-nj4gx                                                   1/1     Running   0          2d20h   100.99.166.3     ip-172-20-38-114.ap-northeast-1.compute.internal   <none>           <none>

coredns-autoscaler-6f594f4c58-mj2rp                                        1/1     Running   0          2d20h   100.99.166.1     ip-172-20-38-114.ap-northeast-1.compute.internal   <none>           <none>



5

kubectl get pod -o wide -A



6

sudo su -

docker 가 설치되어 있지 않아 설치 ?


docker ps

apt  install docker.io


7

containerd config default


8

AWS는  ps 로 컨테이너 런타임(containerd) 정보로 동작 중인 컨테이너 정보 확인

ps afxuwww


ps axf |grep /usr/bin/containerd





<7>  k8s  워커 노드의 구성 요소 확인


Woker node 에 로그인한다.


1

kubelet 상태 확인 ?

kubelet은 Master node의 명령을 받아 처리하는 프로세스 이다.

컨테이너를 생성해달라고 요청을 받으면 처리하는 것이다.


systemctl status kubelet


[root@ip-172-20-41-255:~ (k8.serverchk.com:default)]# systemctl status kubelet

kubelet.service - Kubernetes Kubelet Server

     Loaded: loaded (/lib/systemd/system/kubelet.service; static; vendor preset: enabled)

     Active: active (running) since Sun 2021-06-27 10:26:30 UTC; 57min ago

       Docs: https://github.com/kubernetes/kubernetes

   Main PID: 4268 (kubelet)

      Tasks: 19 (limit: 4638)

     Memory: 52.5M

        CPU: 1min 18.504s

     CGroup: /system.slice/kubelet.service

             └─4268 /usr/local/bin/kubelet --anonymous-auth=false --authentication-token-webhook=true --authorization-mode=Webhook --cgroup-driver=systemd --cgroup-root=/ --client-ca-file=/srv/kubernetes/ca.crt --cloud-provider=aws --cl>

Jun 27 11:22:37 ip-172-20-41-255 kubelet[4268]: I0627 11:22:37.297977    4268 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-controller-manager-ip-172-20-41-255.ap-northeast-1.compute.internal" status=Running




2

kube-proxy 확인 ?


pstree

ps afxuwww |grep proxy | grep -v color=auto

iptables -t filter -S

iptables -t nat -S

iptables -t mangle -S

iptables -t raw -S



3

ps afxuwww |grep proxy | grep -v color=auto


ubuntu@ip-172-20-41-255:~$ ps afxuwww |grep proxy | grep -v color=auto

root        5060  0.0  0.4 743816 16312 ?        Ssl  Jun27   0:30  \_ /usr/local/bin/kube-proxy --cluster-cidr=100.96.0.0/11 --conntrack-max-per-core=131072 --hostname-override=ip-172-20-41-255.ap-northeast-1.compute.internal --kubeconfig=/var/lib/kube-proxy/kubeconfig --master=https://127.0.0.1 --oom-score-adj=-998 --v=2 --logtostderr=false --alsologtostderr --log-file=/var/log/kube-proxy.log



<8> Pod 배포 해보기


1

다른 터미널에서 

watch -d kubectl get pod 

실행하여 Pod모니터링 하자~



# Pod 배포

# kubectl run <NAME> --image <IMAGE>


kubectl run myweb1 --image nginx


kubectl run myweb2 --image nginx && kubectl get pod -w

pod/myweb2 created

NAME     READY   STATUS              RESTARTS   AGE

myweb1   1/1     Running             0          65s

myweb2   0/1     ContainerCreating   0          0s

myweb2   0/1     ContainerCreating   0          1s

myweb2   1/1     Running             0          8s

// 도커 허브에서 NGINX 이미지를 가져와서 배포한다.



2

# Pod 정보 확인

kubectl get pod

NAME     READY   STATUS    RESTARTS   AGE

myweb1   1/1     Running   0          100s

myweb2   1/1     Running   0          35s


3

## Pod 배치 노드, Pod 의 IP 정보를 확인


kubectl get pod -o wide

root@k8s-m:~# kubectl get pod -o wide

NAME     READY   STATUS    RESTARTS   AGE     IP            NODE     NOMINATED NODE   READINESS 

myweb1   1/1     Running   0      2m18s   172.16.228.68   k8s-w1   <none>           <none>

myweb2   1/1     Running   0          93s     172.16.228.69   k8s-w1   <none>           <none>

// 설치된 NODE 위치 확인 , k8s-w1


참고

 watch -d kubectl get pods,svc -owide



// OPS-VIEW tools은  낮은 쿠버네티스 버전에서만 지원했다. 지금은 더 이상 개발,지원이 되지 않는다.

Helm 설치, OPS-VIEW 설치

curl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash

helm version --short

helm repo add stable https://charts.helm.sh/stable

helm install kube-ops-view stable/kube-ops-view --set service.type=LoadBalancer --set rbac.create=True


웹 브라우저로 접속 

aae40958f667be7ae67712-202734646.ap-northeast-1.elb.amazonaws.com



4

## kubectl get pod mywebsrv -o yaml 내용 중 특정 열과 내용값을 출력


kubectl get pod -o=custom-columns=NAME:.metadata.name,IP:.status.podIP

NAME     IP

myweb1   100.111.183.2

myweb2   100.108.82.195



5

kubectl get pod -o=custom-columns=NAME:.metadata.name,IP:.status.podIP,NODE:.spec.nodeName

NAME       IP            NODE

mywebsrv   172.16.46.1   k8s-w2


6

## Pod 상세 정보 확인

kubectl describe pod myweb1


7

# Pod(Nginx) 에 curl 접속

ping 172.16.228.68

curl 172.16.228.68


8

# Pod 로그 확인

kubectl logs myweb1

kubectl logs -f myweb1


9

# 컨테이너 명령 전달

// Pod에 로그온해서  ls 명령어 실행함!

kubectl exec myweb1 -- ls /usr/share/nginx/html/

50x.html

index.html



kubectl exec myweb1 -- cat /usr/share/nginx/html/index.html

<!DOCTYPE html>

<html>

<head>

<title>Welcome to nginx!</title>

<style>

html { color-scheme: light dark; }



kubectl exec myweb1 -- hostname

myweb1


10

# (옵션) Pod 이름만 출력

kubectl get pod|awk 'NR>1 {print $1}'


//  myweb으로 시작하는것만 보여줌

kubectl get pod|awk 'NR>1 {print $1}'|grep myweb


11

# (옵션) Pod IP만 출력

kubectl get pod -o wide|awk 'NR>1 {print $6}'


12

# (옵션) nginx Pod 의 index.html 에 각 컨테이너 호스트이름을 기록

for pod in $(kubectl get pod|awk 'NR>1 {print $1}'); do kubectl exec $pod -- /bin/sh -c "hostname > /usr/share/nginx/html/index.html"; done



13

# (옵션) Pod IP로 curl 접속 시도

for podIP in $(kubectl get pod -o wide|awk 'NR>1 {print $6}'); do curl -s $podIP; done


14

# Pod 삭제

# kubectl delete pod <NAME>

kubectl delete pod $(kubectl get pod|awk 'NR>1 {print $1}')

kubectl get pod





<9> GCR (구글 컨테이너 저장소)의 샘플 이미지로 Pod 배포


구글 컨테이너 저장소를 사용해서 Pod를 배포 할수도 있다.



1

kubectl run myweb3 --image gcr.io/google-samples/kubernetes-bootcamp:v1 && kubectl get pod -w


// gcr.io에서 다운받아 Pod를 띠운다

pod/myweb3 created

NAME                            READY   STATUS              RESTARTS   AGE

kube-ops-view-894bc75fb-lnxl6   1/1     Running             0          19m

myweb3                          0/1     ContainerCreating   0          0s

myweb3                          0/1     ContainerCreating   0          1s

myweb3                          1/1     Running             0          10s



2

# Pod IP 로 curl 접속(8080포트)

kubectl get pod -o=custom-columns=IP:.status.podIP

kubectl get pod -o=custom-columns=IP:.status.podIP | grep -v IP


3

curl `kubectl get pod -o=custom-columns=IP:.status.podIP | grep -v IP`:8080

Hello Kubernetes bootcamp! | Running on: myweb3 | v=1


4

# 삭제

kubectl delete pod `kubectl get pod -o=custom-columns=NAME:.metadata.name | grep -v NAME`



<10> Deployment 배포


1

# 터미널 1

watch -d kubectl get pods,deploy

NAME                                READY   STATUS    RESTARTS   AGE

pod/kube-ops-view-894bc75fb-lnxl6   1/1     Running   0          26m

pod/my-webs-67ddcbf958-qsjdv        1/1     Running   0          71s

pod/my-webs-67ddcbf958-zp8v8        1/1     Running   0          71s

pod/my-webs-67ddcbf958-zppm8        1/1     Running   0          71s



NAME                            READY   UP-TO-DATE   AVAILABLE   AGE

deployment.apps/kube-ops-view   1/1     1            1           32m

deployment.apps/my-webs         3/3     3            3           71s




2

# 터미널2

## Deployment로 배포(Pod 3개)

kubectl create deployment my-webs --image=gcr.io/google-samples/kubernetes-bootcamp:v1 --replicas=3


kubectl get pod -o wide


Pod는 my-webs-xxxxxxxxx 로 이름이 생성 된다.



3

## Pod IP로 curl 접속 시도

for podIP in $(kubectl get pod -o=custom-columns=IP:.status.podIP | grep -v IP); do curl -s $podIP:8080; done


4

## Deployment Scale 를 3개에서 6개로 증가 → 100개로 증가 가능한가?

kubectl scale --current-replicas=3 --replicas=6 deployment/my-webs

kubectl get pod -o wide


100개 까지는 안된다.

서버 사양별로 지원하는 네트워크 수가 제한 된다.


5

## 바라는상태?

pod 를 delete 해보자! ⇒ 어떤 일이 벌어지는가? (pod NAME 잘 확인)


Pod는 my-webs-xxxxxxxxx 로 이름이 생성 된다.


삭제?

kubectl delete pod `kubectl get pod -o=custom-columns=NAME:.metadata.name | grep -v NAME`

kubectl get pod -o wide

kubectl get deployments

kubectl get replicasets

삭제 수 만큼 새로 생성 되어 동일수가 유지된다.


6

## Deployment  를 6개에서 1개로 감소

kubectl scale --current-replicas=6 --replicas=1 deployment/my-webs

kubectl get pod -o wide


1개로 줄어듬

 Deployment를 삭제해야 함


7

# 삭제

kubectl delete deployments.apps my-webs


8

참고

제약 조건



<11> 다음 과정 보기


https://brunch.co.kr/@topasvga/1669



감사합니다.

매거진의 이전글 쿠버1탄-3. KOPS로 AWS에 쿠버네티스-2021

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari