클라우드/Kubernetes(쿠버네티스)

[쿠버네티스] kubectl & Pods

happyso 2020. 9. 21. 00:53

쿠버네티스 실습 환경 설정

기본에 사용하던 가상머진 모두 중지

 

#1 가상머신 생성

C:\kubernetes\Vagrantfile 

# -*- mode: ruby -*-

# vi: set ft=ruby :


Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/bionic64"

  config.vm.hostname = "ubuntu"

  config.vm.network "private_network", ip: "192.168.111.110"

  config.vm.synced_folder ".", "/home/vagrant/sync", disabled: true

  config.vm.provider "virtualbox" do |vb|

    vb.cpus = 2

    vb.memory = 2048

  end

end

 

C:\kubernetes> vagrant up

C:\kubernetes> vagrant ssh



#2 패키지 최신화

vagrant@ubuntu:~$ sudo su

root@ubuntu:/home/vagrant# cd

root@ubuntu:~# apt update

root@ubuntu:~# apt upgrade



#3 도커 설치 및 설정

root@ubuntu:~# apt install docker.io -y

root@ubuntu:~# usermod -a -G docker vagrant

root@ubuntu:~# service docker restart

root@ubuntu:~# chmod 666 /var/run/docker.sock

 

root@ubuntu:~# docker version

Client:

 Version:           19.03.6

 API version:       1.40

 Go version:        go1.12.17

 Git commit:        369ce74a3c

 Built:             Fri Feb 28 23:45:43 2020

 OS/Arch:           linux/amd64

 Experimental:      false

 

Server:

 Engine:

  Version:          19.03.6

  API version:      1.40 (minimum version 1.12)

  Go version:       go1.12.17

  Git commit:       369ce74a3c

  Built:            Wed Feb 19 01:06:16 2020

  OS/Arch:          linux/amd64

  Experimental:     false

 containerd:

  Version:          1.3.3-0ubuntu1~18.04.2

  GitCommit:

 runc:

  Version:          spec: 1.0.1-dev

  GitCommit:

 docker-init:

  Version:          0.18.0

  GitCommit:



#4 kubectl 설치

https://kubernetes.io/ko/docs/tasks/tools/install-kubectl/

 

root@ubuntu:~# apt-get update && sudo apt-get install -y apt-transport-https gnupg2

root@ubuntu:~# curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

root@ubuntu:~# echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list

root@ubuntu:~# apt-get update

root@ubuntu:~# apt-get install -y kubectl

 

root@ubuntu:~# kubectl version

Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.2", GitCommit:"f5743093fd1c663cb0cbc89748f730662345d44d", GitTreeState:"clean", BuildDate:"2020-09-16T13:41:02Z", GoVersion:"go1.15", Compiler:"gc", Platform:"linux/amd64"}

The connection to the server localhost:8080 was refused - did you specify the right host or port?



#5 Minikube 설치

https://kubernetes.io/ko/docs/tasks/tools/install-minikube/

 

root@ubuntu:~# curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 && chmod +x minikube

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

                                 Dload  Upload   Total   Spent    Left  Speed

100 55.8M  100 55.8M    0     0  60.2M      0 --:--:-- --:--:-- --:--:-- 60.1M

 

root@ubuntu:~# mkdir -p /usr/local/bin/

root@ubuntu:~# install minikube /usr/local/bin/



k8s = kubernetes



#6 클러스터 시작

root@ubuntu:~# exit

exit

 

vagrant@ubuntu:~$ minikube start

😄  minikube v1.13.0 on Ubuntu 18.04 (vbox/amd64)

✨  Automatically selected the docker driver

 

⛔  Requested memory allocation (1992MB) is less than the recommended minimum 2000MB. Deployments may fail.



🧯  The requested memory allocation of 1992MiB does not leave room for system overhead (total system  memory: 1992MiB). You may face stability issues.

💡  Suggestion: Start minikube with less memory allocated: 'minikube start --memory=1992mb'

 

👍  Starting control plane node minikube in cluster minikube

🚜  Pulling base image ...

💾  Downloading Kubernetes v1.19.0 preload ...

    > preloaded-images-k8s-v6-v1.19.0-docker-overlay2-amd64.tar.lz4: 486.28 MiB

🔥  Creating docker container (CPUs=2, Memory=1992MB) ...

🐳  Preparing Kubernetes v1.19.0 on Docker 19.03.8 ...

🔎  Verifying Kubernetes components...

🌟  Enabled addons: default-storageclass, storage-provisioner

🏄  Done! kubectl is now configured to use "minikube" by default



vagrant@ubuntu:~$ minikube status

minikube

type: Control Plane

host: Running

kubelet: Running

apiserver: Running

kubeconfig: Configured



vagrant@ubuntu:~$ kubectl version

Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.2", GitCommit:"f5743093fd1c663cb0cbc89748f730662345d44d", GitTreeState:"clean", BuildDate:"2020-09-16T13:41:02Z", GoVersion:"go1.15", Compiler:"gc", Platform:"linux/amd64"}

Server Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.0", GitCommit:"e19964183377d0ec2052d1f1fa930c4d7575bd50", GitTreeState:"clean", BuildDate:"2020-08-26T14:23:04Z", GoVersion:"go1.15", Compiler:"gc", Platform:"linux/amd64"}



vagrant@ubuntu:~$ kubectl version --short

Client Version: v1.19.2

Server Version: v1.19.0

 

 

중지 ⇒ minikube stop

삭제 ⇒ minikube delete



쿠버네티스

https://myanjini.tistory.com/entry/o2-Kubernetes





포드(pod)

컨테이너 애플리케이션의 기본 단위

1개 이상의 컨테이너로 구성된 컨테이너의 집합

 

여러 개의 컨테이너를 추상화해서 하나의 애플리케이션으로 동작하도록 묶어 놓은 컨테이너의 묶음



nginx 컨테이너로 구성된 포드를 생성

vagrant@ubuntu:~/kub01$ vi nginx-pod.yml

apiVersion: v1                           ⇐ YAML 파일에서 정의한 오브젝트의 API 버전

kind: Pod                                ⇐ 리소스의 종류 (kubectl api-resources 명령의 KIND 항목)

metadata:                                ⇐ 라벨, 주석, 이름과 같은 리소스의 부가 정보

  name: my-nginx-pod

spec:

  containers:                            ⇐ 리소스 생성을 위한 정보

  - name: my-nginx-container

    image: nginx:latest

    ports:

    - containerPort: 80

      protocol: TCP



새로운 파드 생성 및 확인

vagrant@ubuntu:~/kub01$ kubectl apply -f nginx-pod.yml

pod/my-nginx-pod created

 

vagrant@ubuntu:~/kub01$ kubectl get pods

NAME           READY   STATUS    RESTARTS   AGE

my-nginx-pod   1/1     Running   0          35s

 

vagrant@ubuntu:~/kub01$ kubectl get po ⇐ pods의 축약어(po)를 이용할 수 있음

NAME           READY   STATUS    RESTARTS   AGE

my-nginx-pod   1/1     Running   0          52s



생성된 리소스의 자세한 정보를 확인

vagrant@ubuntu:~/kub01$ kubectl describe pods my-nginx-pod

Name:         my-nginx-pod

Namespace:    default

Priority:     0

Node:         minikube/172.17.0.2

Start Time:   Fri, 18 Sep 2020 06:35:11 +0000

Labels:       <none>

Annotations:  <none>

Status:       Running

IP:           172.18.0.3

IPs:

  IP:  172.18.0.3

Containers:

  my-nginx-container:

    Container ID:   docker://6d35592cf4cf94fb0f45f90b85a7146516fa856d0ae583c0d6eded380f3e27d6

    Image:          nginx:latest

    Image ID:       docker-pullable://nginx@sha256:c628b67d21744fce822d22fdcc0389f6bd763daac23a6b77147d0712ea7102d0

    Port:           80/TCP

    Host Port:      0/TCP

    State:          Running

      Started:      Fri, 18 Sep 2020 06:35:20 +0000

    Ready:          True

    Restart Count:  0

    Environment:    <none>

    Mounts:

      /var/run/secrets/kubernetes.io/serviceaccount from default-token-sh8hv (ro)

Conditions:

  Type              Status

  Initialized       True

  Ready             True

  ContainersReady   True

  PodScheduled      True

Volumes:

  default-token-sh8hv:

    Type:        Secret (a volume populated by a Secret)

    SecretName:  default-token-sh8hv

    Optional:    false

QoS Class:       BestEffort

Node-Selectors:  <none>

Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s

                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s

Events:

  Type    Reason     Age   From               Message

  ----    ------     ----  ----               -------

  Normal  Scheduled  2m8s  default-scheduler  Successfully assigned default/my-nginx-pod to minikube

  Normal  Pulling    2m7s  kubelet            Pulling image "nginx:latest"

  Normal  Pulled     119s  kubelet            Successfully pulled image "nginx:latest" in 8.202726173s

  Normal  Created    119s  kubelet            Created container my-nginx-container

  Normal  Started    119s  kubelet            Started container my-nginx-container



클러스터 내부에 테스트를 위한 임시 포드를 생성해서 nginx 포드의 동작을 확인

### alicek106/ubuntu:curl 이미지를 이용해서 debug 이름의 포드를 생성

vagrant@ubuntu:~/kub01$ kubectl run -it --rm debug --image=alicek106/ubuntu:curl --restart=Never bash

If you don't see a command prompt, try pressing enter.

root@debug:/#



### debug 포드가 생성(실행)된 상태에서 포드를 조회

vagrant@ubuntu:~$ kubectl get pods

NAME           READY   STATUS    RESTARTS   AGE

debug          1/1     Running   0          58s

my-nginx-pod   1/1     Running   0          8m13s



### debug 포드에서 my-nginx-pod(172.18.0.3)로 요청을 전달

root@debug:/# curl 172.18.0.3

<!DOCTYPE html>

<html>

<head>

<title>Welcome to nginx!</title>

<style>

    body {

        width: 35em;

        margin: 0 auto;

        font-family: Tahoma, Verdana, Arial, sans-serif;

    }

</style>

</head>

<body>

<h1>Welcome to nginx!</h1>

<p>If you see this page, the nginx web server is successfully installed and

working. Further configuration is required.</p>

 

<p>For online documentation and support please refer to

nginx.org.

Commercial support is available at

nginx.com.

 

 

<p><em>Thank you for using nginx.</em></p>

</body>

</html>



### debug 포드를 빠져 나오는 것과 동시에 삭제되는 것을 확인

root@debug:/# exit

exit

pod "debug" deleted

 

vagrant@ubuntu:~/kub01$ kubectl get pods

NAME           READY   STATUS    RESTARTS   AGE

my-nginx-pod   1/1     Running   0          12m



kubectl exec 명령으로 포드의 컨테이너에 명령어를 전달

vagrant@ubuntu:~/kub01$ kubectl exec -it my-nginx-pod -- bash

 

root@my-nginx-pod:/# ls /etc/nginx/

conf.d  fastcgi_params  koi-utf  koi-win  mime.types  modules  nginx.conf  scgi_params  uwsgi_params  win-utf

 

root@my-nginx-pod:/# exit

exit

 

vagrant@ubuntu:~/kub01$



kubectl logs 명령으로 포드의 로그를 확인

vagrant@ubuntu:~/kub01$ kubectl logs my-nginx-pod

/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration ⇐ nginx 포드의 표준 출력 로그

/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/

/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh

10-listen-on-ipv6-by-default.sh: Getting the checksum of /etc/nginx/conf.d/default.conf

10-listen-on-ipv6-by-default.sh: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf

/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh

/docker-entrypoint.sh: Configuration complete; ready for start up

172.18.0.4 - - [18/Sep/2020:06:45:49 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.35.0" "-"



쿠버네티스 오브젝트를 삭제

vagrant@ubuntu:~/kub01$ kubectl delete -f nginx-pod.yml

pod "my-nginx-pod" deleted

 

vagrant@ubuntu:~/kub01$ kubectl get pods

No resources found in default namespace.




pod 정의

vagrant@ubuntu:~/kub01$ vi nginx-pod-with-ubuntu.yml

apiVersion: v1

kind: Pod

metadata:

  name: my-nginx-pod

spec:

  containers:

  - name: my-nginx-container

    image: nginx:latest

    ports:

    - containerPort: 80

      protocol: TCP


  - name: ubuntu-sidecar-container

    image: alicek106/rr-test:curl

    command: [ "tail" ]

    args: [ "-f", "/dev/null" ]



pod 생성

vagrant@ubuntu:~/kub01$ kubectl apply -f nginx-pod-with-ubuntu.yml

pod/my-nginx-pod created

 

vagrant@ubuntu:~/kub01$ kubectl get pods

NAME           READY   STATUS              RESTARTS   AGE

my-nginx-pod   0/2     ContainerCreating   0          11s

 

vagrant@ubuntu:~/kub01$ kubectl get pods

NAME           READY   STATUS    RESTARTS   AGE

my-nginx-pod   2/2     Running   0          21s



my-nginx-pod에는 my-nginx-container 컨테이너와 ubuntu-sidecar-container 컨테이너가 실행 중

 

### pod로 명령어를 전달할 때 실행할 컨테이너를 지정하면 default로 설정된 컨테이너가 실행

vagrant@ubuntu:~/kub01$ kubectl exec -it my-nginx-pod -- bash

Defaulting container name to my-nginx-container.

Use 'kubectl describe pod/my-nginx-pod -n default' to see all of the containers in this pod.

root@my-nginx-pod:/# exit

exit

 

### 특정 컨테이너에게 명령어를 전달할 때는 -c 옵션을 사용

vagrant@ubuntu:~/kub01$ kubectl exec -it my-nginx-pod -c ubuntu-sidecar-container -- bash

root@my-nginx-pod:/#

 

root@my-nginx-pod:/# curl localhost       ⇒ 우분투 컨테이너 내부에서 localhost 요청에 대해 응답이 도착하는 것을 확인

<!DOCTYPE html>                                         우분투 컨테이너의 localhost에서 nginx 서버로 접근이 가능

<html>                                                 포드 내부의 컨테이너들은 네트워크와 같은 리눅스 네임스페이스를 공유

<head>

<title>Welcome to nginx!</title>

<style>

    body {

        width: 35em;

        margin: 0 auto;

        font-family: Tahoma, Verdana, Arial, sans-serif;

    }

</style>

</head>

<body>

<h1>Welcome to nginx!</h1>

<p>If you see this page, the nginx web server is successfully installed and

working. Further configuration is required.</p>

 

<p>For online documentation and support please refer to

nginx.org.

Commercial support is available at

nginx.com.

 

 

<p><em>Thank you for using nginx.</em></p>

</body>

</html>




### ubunut-sidecar-container 컨테이너만으로 구성된 pod를 생성한 후 해당 pod에서 curl을 동작

vagrant@ubuntu:~/kub01$ cp nginx-pod-with-ubuntu.yml nginx-pod-test.yml

vagrant@ubuntu:~/kub01$ vi nginx-pod-test.yml

apiVersion: v1

kind: Pod

metadata:

  name: my-nginx-pod-test

spec:

  containers:

  - name: ubuntu-sidecar-container

    image: alicek106/rr-test:curl           ⇐ 웹 서버를 포함하고 있지 않음

    command: [ "tail" ]

    args: [ "-f", "/dev/null" ]

 

vagrant@ubuntu:~/kub01$ kubectl apply -f nginx-pod-test.yml

pod/my-nginx-pod-test created

vagrant@ubuntu:~/kub01$ kubectl exec -it my-nginx-pod-test -- bash

root@my-nginx-pod-test:/# curl localhost

curl: (7) Failed to connect to localhost port 80: Connection refused ⇐ 80 포트로 서비스를 제공하고 있지 않다