본문 바로가기
공부/kubernetes

kubernetes kubectl 기본 사용(1)

by CITTA 2023. 2. 8.
728x90
반응형
  1. 용어 정리

(1) kubeadm: 클러스터를 부트스트랩 하는 명령어

  • bootstrap: 클러스터를 처음부터 생성하고 실행

(2) kubelet: 클러스터의 모든 머신에서 실행되는 파드와 컨테이너 시작과 같은 작업을 수행하는 컴포넌트

(3) kubectl: 클러스터와 통신하기 위한 커맨드 라인 유틸리

  • kubectl [command] [type] [name] [flags]
  • command: 실행하려는 동작으로 create, get, delete 등을 사용
  • type: 자원 타입. pod, service, ingress 등을 사용
  • name: 자원 이름
  • flag: 부가적으로 설정할 옵션을 입력
## node 확인
$ kubectl get nodes

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

## pod 조회 (구성 초기에는 별도로 생성한 pod가 없어서 나오지 않음)
$ kubectl get pods

## pod 조회 (namespaces 전체)
$ kubectl get pod --all-namepaces
NAMESPACE     NAME                                 READY   STATUS    RESTARTS      AGE
kube-system   coredns-787d4945fb-frc8t             1/1     Running   1 (20m ago)   4d17h
kube-system   coredns-787d4945fb-mxdk6             1/1     Running   1 (20m ago)   4d17h
kube-system   etcd-k8s-master                      1/1     Running   2 (20m ago)   4d17h
kube-system   kube-apiserver-k8s-master            1/1     Running   2 (20m ago)   4d17h
kube-system   kube-controller-manager-k8s-master   1/1     Running   2 (20m ago)   4d17h
kube-system   kube-proxy-j9mlk                     1/1     Running   1 (20m ago)   2d19h
kube-system   kube-proxy-jn7r4                     1/1     Running   1 (20m ago)   2d19h
kube-system   kube-proxy-s9hj7                     1/1     Running   2 (20m ago)   4d17h
kube-system   kube-scheduler-k8s-master            1/1     Running   2 (20m ago)   4d17h
kube-system   weave-net-b8g94                      2/2     Running   3 (20m ago)   2d21h
kube-system   weave-net-c44x7                      2/2     Running   2 (20m ago)   2d19h
kube-system   weave-net-s7xvl                      2/2     Running   2 (20m ago)   2d19h

## pod 조회 (특정한 namespaces)
$ kubectl get pod -n kube-system
NAME                                 READY   STATUS    RESTARTS      AGE
coredns-787d4945fb-frc8t             1/1     Running   1 (20m ago)   4d17h
coredns-787d4945fb-mxdk6             1/1     Running   1 (20m ago)   4d17h
etcd-k8s-master                      1/1     Running   2 (20m ago)   4d17h
kube-apiserver-k8s-master            1/1     Running   2 (20m ago)   4d17h
kube-controller-manager-k8s-master   1/1     Running   2 (20m ago)   4d17h
kube-proxy-j9mlk                     1/1     Running   1 (20m ago)   2d19h
kube-proxy-jn7r4                     1/1     Running   1 (20m ago)   2d19h
kube-proxy-s9hj7                     1/1     Running   2 (20m ago)   4d17h
kube-scheduler-k8s-master            1/1     Running   2 (20m ago)   4d17h
weave-net-b8g94                      2/2     Running   3 (20m ago)   2d21h
weave-net-c44x7                      2/2     Running   2 (20m ago)   2d19h
weave-net-s7xvl                      2/2     Running   2 (20m ago)   2d19h
  1. kubectl 기본 사용법

(1) echoserver pod 생성

## echoserver pod 생성(클라이언트가 전송해주는 데이터를 그대로 되돌려 전송하는 서버)
$ kubectl run echoserver --image="k8s.gcr.io/echoserver:1.10" --port=8080
pod/echoserver created

## echoserver service 생성(pod들에 접근할 때 필요)
$ kubectl expose po echoserver --type=NodePort
service/echoserver exposed

## pod 생성 확인
$ kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
echoserver   1/1     Running   0          100s

## pod 상세 정보 확인
$ kubectl describe pods echoserver
Name:             echoserver
Namespace:        default
Priority:         0
Service Account:  default
Node:             k8s-worker1/192.168.130.132
Start Time:       Mon, 06 Feb 2023 04:48:21 +0000
Labels:           run=echoserver
Annotations:      <none>
Status:           Running
IP:               10.44.0.1
IPs:
  IP:  10.44.0.1
Containers:
  echoserver:
    Container ID:   containerd://028d1d880e7ef44bdc6adfed07d8b59ed9b705c50b8792b714e4c69b6eb181ef
    Image:          k8s.gcr.io/echoserver:1.10
    Image ID:       k8s.gcr.io/echoserver@sha256:cb5c1bddd1b5665e1867a7fa1b5fa843a47ee433bbb75d4293888b71def53229
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Mon, 06 Feb 2023 04:48:30 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-kkt6n (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  kube-api-access-kkt6n:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
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  68m   default-scheduler  Successfully assigned default/echoserver to k8s-worker1
  Normal  Pulling    68m   kubelet            Pulling image "k8s.gcr.io/echoserver:1.10"
  Normal  Pulled     68m   kubelet            Successfully pulled image "k8s.gcr.io/echoserver:1.10" in 7.422212496s (7.422219623s including waiting)
  Normal  Created    68m   kubelet            Created container echoserver
  Normal  Started    68m   kubelet            Started container echoserver
  • name: pod 이름
  • ready: 숫자/숫자 형태로 준비 상태 표시, 0/1은 생성되지 않았거나 준비가 되지 않은 상태이고 1/1이면 생성 및 사용할 준비가 끝났다는 뜻
  • status: pod 현 상태, running(실행중)/terminating(컨테이너 접속 중)/containercreating(생성중) 등
  • restarts: pod 재시작 횟수
  • age: pod가 생성된 후 얼마나 시간이 지났는지 표기
## 서비스 확인
$ kubectl get services
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
echoserver   NodePort    10.100.132.118   <none>        8080:30552/TCP   7m9s
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP          4d21h
  • name: 서비스 이름
  • type: 서비스 타입
  • cluster-ip: 현 클러스터 안에서 사용되는 ip
  • external-ip: 외부에서 접속할 때 사용하는 ip, 별도 설정하지 않으면 none으로 표기
  • port(s): 서비스에 접속하는 포트
  • age: 생성 후 지난 시간

※ kubernetes 서비스는 kube-apiserver 관련 pod들을 가리킴

## echoserver 접속해보기 - 포트포워딩
$ kubectl port-forward svc/echoserver 8080:8080
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080

(2) echoserver 확인

$ curl <http://localhost:8080>
Hostname: echoserver

Pod Information:
        -no pod information available-

Server values:
        server_version=nginx: 1.13.3 - lua: 10008

Request Information:
        client_address=127.0.0.1
        method=GET
        real path=/
        query=
        request_version=1.1
        request_scheme=http
        request_uri=http://localhost:8080/

Request Headers:
        accept=*/*
        host=localhost:8080
        user-agent=curl/7.68.0

Request Body:
        -no body in request-

## echoserver pod log 확인
$ kubectl logs -f echoserver
Generating self-signed cert
Generating a 2048 bit RSA private key
........................................+++
.....................................................................................................................................................+++
writing new private key to '/certs/privateKey.key'
-----
Starting nginx
127.0.0.1 - - [06/Feb/2023:05:45:57 +0000] "GET / HTTP/1.1" 200 774 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/109.0"
127.0.0.1 - - [06/Feb/2023:05:45:57 +0000] "GET /favicon.ico HTTP/1.1" 200 723 "<http://localhost:8080/>" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/109.0"
127.0.0.1 - - [06/Feb/2023:05:50:14 +0000] "GET / HTTP/1.1" 200 809 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/109.0"
127.0.0.1 - - [06/Feb/2023:05:51:58 +0000] "GET / HTTP/1.1" 200 416 "-" "curl/7.68.0"

(3) nginx webserver pod 생성

## nginx 최신 버전 pod 생성
$ kubectl run webserver --image=nginx:latest --port 80
pod/webserver created

## pod 확인
$ kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
echoserver   1/1     Running   0          67m
webserver    1/1     Running   0          79s

## pod 상세 확인
$ kubectl describe pods webserver
Name:             webserver
Namespace:        default
Priority:         0
Service Account:  default
Node:             k8s-worker2/192.168.130.133
Start Time:       Mon, 06 Feb 2023 05:54:56 +0000
Labels:           run=webserver
Annotations:      <none>
Status:           Running
IP:               10.36.0.1
IPs:
  IP:  10.36.0.1
Containers:
  webserver:
    Container ID:   containerd://985eeeb0259ae152c6dbb3bce9738a85148b4d2f6d9b827a1f0f52033b917838
    Image:          nginx:latest
    Image ID:       docker.io/library/nginx@sha256:c54fb26749e49dc2df77c6155e8b5f0f78b781b7f0eadd96ecfabdcdfa5b1ec4
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Mon, 06 Feb 2023 05:55:03 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-7lcpw (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  kube-api-access-7lcpw:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
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  2m45s  default-scheduler  Successfully assigned default/webserver to k8s-worker2
  Normal  Pulling    2m44s  kubelet            Pulling image "nginx:latest"
  Normal  Pulled     2m38s  kubelet            Successfully pulled image "nginx:latest" in 6.495441948s (6.495448359s including waiting)
  Normal  Created    2m38s  kubelet            Created container webserver
  Normal  Started    2m38s  kubelet            Started container webserver

(4) ngix 확인 - curl, firefox web

$ curl 10.36.0.1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

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

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

(5) pod 및 서비스 삭제

## pod 확인
$ kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
echoserver   1/1     Running   0          73m
webserver    1/1     Running   0          7m

## pod 삭제
$ kubectl delete pod echoserver
pod "echoserver" deleted
$ kubectl delete pod webserver
pod "webserver" deleted

## service 확인
$ kubectl get service
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
echoserver   NodePort    10.100.132.118   <none>        8080:30552/TCP   74m
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP          4d22h

## service 삭제
$ kubectl delete service echoserver
service "echoserver" deleted

## 확인
$ kubectl get pods
No resources found in default namespace.

$ kubectl get service
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   4d22h
728x90
반응형

댓글