기본적인 kubectl 명령어 가이드

작성자 이경미 수정일 2022-12-27 17:02

들어가며

  • kubernetes 를 사용하기 위한 기본적인 명령어에 대해 알 수 있습니다.



내용

Kubectl 은 쿠버네티스 클러스터를 제어하기 위한 커멘드라인 도구입니다. 

이 가이드에서 kubectl 의 구문을 다루고, 커멘드 동작과 일반적인 예제를 확인할 수 있습니다. 


일반적인 작업

  1. kubectl get 
    : 하나 이상의 리소스를 표시합니다. 대소문자를 구별하지않으며, pod / service / node / event 등의 리소스 출력이 가능합니다. 
    # 모든 파드를 일반 텍스트 출력 형식으로 나열합니다. 
    kubectl get pods 
    NAME                                                      READY   STATUS      RESTARTS   AGE
    sodaflow-nginx-ingress-controller-7b55dd5954-r2hlf        1/1     Running     1          28d
    sodaflow-nginx-ingress-default-backend-64459cdb5d-spnsk   1/1     Running     1          28d
    
    # 모든 파드를 일반 텍스트 출력 형식으로 나열하고 추가 정보(예: 노드 이름)를 포함합니다. 
    kubectl get pods -o wide
    NAME                                                      READY   STATUS      RESTARTS   AGE    IP            NODE     NOMINATED NODE   READINESS GATES
    sodaflow-nginx-ingress-controller-7b55dd5954-r2hlf        1/1     Running     1          28d    6.2.196.173   master     <none>           <none>
    sodaflow-nginx-ingress-default-backend-64459cdb5d-spnsk   1/1     Running     1          28d    6.2.196.174   worker     <none>           <none>
     
    # 특정 노드에서 실행 중인 모든 파드를 나열합니다. 
    # kubectl get pods --field-selector=spec.nodeName=[Node Name]
    kubectl get pods --field-selector=spec.nodeName=worker
    NAME                                                 READY   STATUS    RESTARTS   AGE
    sodaflow-nginx-ingress-default-backend-64459cdb5d-spnsk   1/1     Running     1          28d
  2. kuebctl apply 
    : 파일 이름 또는 stdin 으로 리소스에 구성을 적용합니다. 아직 존재하지 않는 경우 리소스가 생성되며 이미 존재하는 경우 존재하는 리소스에 반영됩니다.
    - Json 및 yaml 형식이 허용됩니다. 

    - 사전 준비 yaml 파일 예시 
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: my-nginx
    spec:
      selector:
        matchLabels:
          run: my-nginx
      replicas: 2
      template:
        metadata:
          labels:
            run: my-nginx
        spec:
          containers:
          - name: my-nginx
            image: nginx
            ports:
            - containerPort: 80

    yaml 적용 방법

    # example-service.yaml의 정의를 사용하여 서비스를 생성한다. 
    # kubectl apply -f [file name]
    kubectl apply -f nginx-deployment.yaml 
    deployment.apps/my-nginx created
    
    # ==> 생성된 deployment 확인 
    kubectl get pods -l run=my-nginx -o wide
    NAME                        READY   STATUS    RESTARTS   AGE     IP           NODE     NOMINATED NODE   READINESS GATES
    my-nginx-5dc4865748-7kctb   1/1     Running   0          3m23s   6.2.171.68   worker   <none>           <none>
    my-nginx-5dc4865748-t5vw9   1/1     Running   0          3m23s   6.2.171.69   worker   <none>           <none>


    directory 단위로도 적용이 가능합니다. 

    ll ./pvcs
    -rwxr-xr-x. 1 root root 256 Nov 23 10:53 sodaflow-data-volume.yaml
    -rwxr-xr-x. 1 root root 258 Nov 23 10:53 sodaflow-docker-volume.yaml
    
    kubectl apply -f ./pvcs
    persistentvolumeclaim/data-volume created
    persistentvolumeclaim/docker-volume created


  3. kubectl describe 
    : 초기화되지 않은 리소스를 포함하여 하나 이상의 리소스의 기본 상태를 기준으로 표시합니다. 
    kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)
    
    # pod 이름이 my-nginx-5dc4865748-7kctb 인 노드의 세부 사항을 표시한다. 
    kubectl describe nodes my-nginx-5dc4865748-7kctb
    Name:         my-nginx-5dc4865748-7kctb
    Namespace:    sodaflow
    Priority:     0
    Node:         worker/192.168.50.199
    Start Time:   Tue, 27 Dec 2022 16:23:15 +0900
    Labels:       pod-template-hash=5dc4865748
                  run=my-nginx
    Annotations:  cni.projectcalico.org/podIP: 6.2.171.68/32
                  cni.projectcalico.org/podIPs: 6.2.171.68/32
    Status:       Running
    IP:           6.2.171.68
    IPs:
      IP:           6.2.171.68
    Controlled By:  ReplicaSet/my-nginx-5dc4865748
    Containers:
      my-nginx:
        Container ID:   docker://a60bc7b6e19e9b25b876824cec2fed243e2e3db5e4829ca7704fd2e88a780201
        Image:          nginx
        Image ID:       docker-pullable://nginx@sha256:0047b729188a15da49380d9506d65959cce6d40291ccfb4e039f5dc7efd33286
        Port:           80/TCP
        Host Port:      0/TCP
        State:          Running
          Started:      Tue, 27 Dec 2022 16:23:27 +0900
        Ready:          True
        Restart Count:  0
        Environment:    <none>
        Mounts:
          /var/run/secrets/kubernetes.io/serviceaccount from default-token-vk9vs (ro)
    Conditions:
      Type              Status
      Initialized       True 
      Ready             True 
      ContainersReady   True 
      PodScheduled      True 
    Volumes:
      default-token-vk9vs:
        Type:        Secret (a volume populated by a Secret)
        SecretName:  default-token-vk9vs
        Optional:    false
    QoS Class:       BestEffort
    Node-Selectors:  <none>
    Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                     node.kubernetes.io/unreachable:NoExecute for 300s
    Events:
      Type    Reason     Age   From               Message
      ----    ------     ----  ----               -------
      Normal  Scheduled  14m   default-scheduler  Successfully assigned sodaflow/my-nginx-5dc4865748-7kctb to worker
      Normal  Pulling    14m   kubelet            Pulling image "nginx"
      Normal  Pulled     14m   kubelet            Successfully pulled image "nginx"
      Normal  Created    14m   kubelet            Created container my-nginx
      Normal  Started    14m   kubelet            Started container my-nginx
    
    # 모든 파드의 정보를 출력한다. 
    kubectl describe pods

  4. kubectl delete 
    : 파일, 표준 입력 또는 레이블 선택기, 이름, 리소스 선택기나 리소스를 지정하여 적용된 리소스를 삭제합니다. 
    #  kubectl delete -f [file name]
    kubectl delete -f nginx-service.yaml 
    deployment.apps "my-nginx" deleted
    
    #  kubectl delete -f [directory name]
    kubectl delete -f ./pvcs 
    persistentvolumeclaim/data-volume deleted
    persistentvolumeclaim/docker-volume deleted
    
    # 초기화되지 않은 파드를 포함한 모든 파드를 삭제한다. 
    kubectl delete pods --all 

     

  5. kubectl exec 
    : 파드의 컨테이너에 대한 명령을 수행합니다. 
    # 파드 [pod-name]에서 'date'를 실행한 결과를 얻는다. 기본적으로, 첫 번째 컨테이너에서 출력된다. 
    # kubectl exec [pod-name] -- date 
    kubectl exec my-nginx-5dc4865748-hjl64 -- date
    Tue Dec 27 07:48:25 UTC 2022
    
    # 파드 [pod-name]에서 대화식 TTY를 연결해 bash를 실행한다. 기본적으로, 첫 번째 컨테이너에서 출력된다. 
    # kubectl exec -it [pod-name] bash 
    kubectl exec -it my-nginx-5dc4865748-hjl64 -- bash
    root@my-nginx-5dc4865748-hjl64:/# 


  6. kubectl logs
    : 파드의 컨테이너에 대한 로그를 출력합니다. 
    # 파드 [pod-name]에서 로그의 스냅샷을 반환한다. 
    # kubectl logs [pod-name]
    
    # 파드 [pod-name]에서 로그 스트리밍을 시작한다. 이것은 리눅스 명령 'tail -f'와 비슷하다. 
    # kubectl logs -f [pod-name]
    
    kubectl logs -f my-nginx-5dc4865748-hjl64
    /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
    /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: info: Getting the checksum of /etc/nginx/conf.d/default.conf
    10-listen-on-ipv6-by-default.sh: info: 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: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
    /docker-entrypoint.sh: Configuration complete; ready for start up
    2022/12/27 07:48:10 [notice] 1#1: using the "epoll" event method
    2022/12/27 07:48:10 [notice] 1#1: nginx/1.23.3
    2022/12/27 07:48:10 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
    2022/12/27 07:48:10 [notice] 1#1: OS: Linux 3.10.0-1160.el7.x86_64
    2022/12/27 07:48:10 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
    2022/12/27 07:48:10 [notice] 1#1: start worker processes
    2022/12/27 07:48:10 [notice] 1#1: start worker process 29
    2022/12/27 07:48:10 [notice] 1#1: start worker process 30
    2022/12/27 07:48:10 [notice] 1#1: start worker process 31
    2022/12/27 07:48:10 [notice] 1#1: start worker process 32
    2022/12/27 07:48:10 [notice] 1#1: start worker process 33
    2022/12/27 07:48:10 [notice] 1#1: start worker process 34
    2022/12/27 07:48:10 [notice] 1#1: start worker process 35
    2022/12/27 07:48:10 [notice] 1#1: start worker process 36



마무리

  • kubectl 명령어는 무수히 많이 활용할 수 있습니다. 
  • 운영자가 제품 상태 확인 시 필요한 명령어만 기재하였습니다. 

아티클이 유용했나요?

훌륭합니다!

피드백을 제공해 주셔서 감사합니다.

도움이 되지 못해 죄송합니다!

피드백을 제공해 주셔서 감사합니다.

아티클을 개선할 수 있는 방법을 알려주세요!

최소 하나의 이유를 선택하세요
CAPTCHA 확인이 필요합니다.

피드백 전송

소중한 의견을 수렴하여 아티클을 개선하도록 노력하겠습니다.

02-558-8300