파란하늘의 지식창고
반응형

여기 있는 내용은 모두 아래 공식 한글 문서의 내용임.

운영자가 아닌 사용자 입장에서 많이 쓰는 명령어 위주로 정리

https://kubernetes.io/ko/docs/reference/kubectl/overview/

 

kubectl 개요

Kubectl은 쿠버네티스 클러스터를 제어하기 위한 커맨드 라인 도구이다. 구성을 위해, kubectl 은 config 파일을 $HOME/.kube 에서 찾는다. KUBECONFIG 환경 변수를 설정하거나 --kubeconfig 플래그를 설정하여

kubernetes.io

kubectl은 kubernetes cluster를 제어하기 위한 command line tool이다.

config file은 $HOME/.kube에서 찾으며 KUBECONFIG 환경 변수를 설정하거나 '--kubeconfig' flag를 사용하여 다른 kubeconfig 파일을 지정할 수 있다.

기본적인 명령어 사용

kubernetes는 kubectl로 시작하는 명령어를 사용한다.

kubectl [command] [TYPE] [NAME] [flags]
  • command: 하나 이상의 리소스에서 수행하려는 동작을 지정한다. 예: create, get, describe, delete
  • TYPE: resource TYPE을 지정한다. resource TYPE은 대소문자를 구분하지 않으며 단수형, 복수형 또는 약어 형식을 지정할 수 있다. 예를 들어, 다음의 명령은 동일한 출력 결과를 생성한다.
    kubectl get pod pod1
    kubectl get pods pod1
    kubectl get po pod1
  • NAME: resource NAME을 지정한다. name은 대소문자를 구분한다. name을 생략하면, 모든 resource에 대한 세부 사항이 표시된다.
    예: 'kubectl get pods'
    또한 여러 resource에 대한 작업을 수 행할 때 type 및 name 별로 각 resource를 지정하거나 하나 이상의 file을 지정할 수 있다.
    • type 및 name으로 resource를 지정하려만 다음을 참고한다.
      • resource가 모두 동일한 type인 경우 resource를 그룹화하려면 다음을 사용한다. 'TYPE name1 name2 name<#>'
        예: 'kubectl get example-pod1 example-pod2'
      • 여러 resource type을 개별적으로 지정하려면 다음을 사용한다. 'TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/NAME<#>'
        예 : 'kubectl get pod/example-pod1 replicationcontroller/example-rc1'
    • 하나 이상의 file로 resource를 지정하려면 다음을 사용한다. '-f file1 -f file2 -f file<#>'
      예: 'kubectl get -f ./pod.yaml'
  • flags : 선택적 flag를 지정한다. 예를 들어 '-s' 또는 '--server' flag를 사용하여 kubernetes API 서버의 address와 port를 지정할 수 있다.

명령어 모음

모든 command 확인

kubectl의 모든 명령어는 아래처럼 확인할 수 있다.

kubectl

또는

kubectl --help

위 명령을 사용하면 아래와 같이 모든 command를 확인할 수 있다.

kubectl controls the Kubernetes cluster manager.

 Find more information at: https://kubernetes.io/docs/reference/kubectl/

Basic Commands (Beginner):
  create          Create a resource from a file or from stdin
  expose          Take a replication controller, service, deployment or pod and expose it as a new Kubernetes service
  run             Run a particular image on the cluster
  set             Set specific features on objects

Basic Commands (Intermediate):
  explain         Get documentation for a resource
  get             Display one or many resources
  edit            Edit a resource on the server
  delete          Delete resources by file names, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout         Manage the rollout of a resource
  scale           Set a new size for a deployment, replica set, or replication controller
  autoscale       Auto-scale a deployment, replica set, stateful set, or replication controller

Cluster Management Commands:
  certificate     Modify certificate resources.
  cluster-info    Display cluster information
  top             Display resource (CPU/memory) usage
  cordon          Mark node as unschedulable
  uncordon        Mark node as schedulable
  drain           Drain node in preparation for maintenance
  taint           Update the taints on one or more nodes

Troubleshooting and Debugging Commands:
  describe        Show details of a specific resource or group of resources
  logs            Print the logs for a container in a pod
  attach          Attach to a running container
  exec            Execute a command in a container
  port-forward    Forward one or more local ports to a pod
  proxy           Run a proxy to the Kubernetes API server
  cp              Copy files and directories to and from containers
  auth            Inspect authorization
  debug           Create debugging sessions for troubleshooting workloads and nodes

Advanced Commands:
  diff            Diff the live version against a would-be applied version
  apply           Apply a configuration to a resource by file name or stdin
  patch           Update fields of a resource
  replace         Replace a resource by file name or stdin
  wait            Experimental: Wait for a specific condition on one or many resources
  kustomize       Build a kustomization target from a directory or URL.

Settings Commands:
  label           Update the labels on a resource
  annotate        Update the annotations on a resource
  completion      Output shell completion code for the specified shell (bash, zsh, fish, or powershell)

Other Commands:
  alpha           Commands for features in alpha
  api-resources   Print the supported API resources on the server
  api-versions    Print the supported API versions on the server, in the form of "group/version"
  config          Modify kubeconfig files
  plugin          Provides utilities for interacting with plugins
  version         Print the client and server version information

Usage:
  kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

command가 기억나지 않아도 kubectl만 입력하면 모두 찾을 수 있다.

resource TYPE 목록 확인

kubernetes는 모든 게 resource 단위로 이루어져 있고 yaml을 통해 생성되는 것들은 모두 resource이다.

이 resource가 어떤 TYPE이 있는지를 확인하려면 다음 명령어를 사용하면 된다.

kubectl api-resources

이 글 작성 시점 기준으로 대략 다음과 같은 api-resource 들을 확인할 수 있다.

kubernetes 버전이 올라가면 사용하는 api version이 변경될 수 있다.

api-resource를 통해 변경된 버전을 확인할 수 있다.

NAME                              SHORTNAMES   APIVERSION                        NAMESPACED   KIND
bindings                                       v1                                true         Binding
componentstatuses                 cs           v1                                false        ComponentStatus
configmaps                        cm           v1                                true         ConfigMap
endpoints                         ep           v1                                true         Endpoints
events                            ev           v1                                true         Event
limitranges                       limits       v1                                true         LimitRange
namespaces                        ns           v1                                false        Namespace
nodes                             no           v1                                false        Node
persistentvolumeclaims            pvc          v1                                true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                false        PersistentVolume
pods                              po           v1                                true         Pod
podtemplates                                   v1                                true         PodTemplate
replicationcontrollers            rc           v1                                true         ReplicationController
resourcequotas                    quota        v1                                true         ResourceQuota
secrets                                        v1                                true         Secret
serviceaccounts                   sa           v1                                true         ServiceAccount
services                          svc          v1                                true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1         false        APIService
controllerrevisions                            apps/v1                           true         ControllerRevision
daemonsets                        ds           apps/v1                           true         DaemonSet
deployments                       deploy       apps/v1                           true         Deployment
replicasets                       rs           apps/v1                           true         ReplicaSet
statefulsets                      sts          apps/v1                           true         StatefulSet
tokenreviews                                   authentication.k8s.io/v1          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v1                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1beta1                     true         CronJob
jobs                                           batch/v1                          true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1            false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1            true         Lease
endpointslices                                 discovery.k8s.io/v1beta1          true         EndpointSlice
events                            ev           events.k8s.io/v1                  true         Event
ingresses                         ing          extensions/v1beta1                true         Ingress
ingressclasses                                 networking.k8s.io/v1              false        IngressClass
ingresses                         ing          networking.k8s.io/v1              true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1              true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1beta1               false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1beta1                    true         PodDisruptionBudget
podsecuritypolicies               psp          policy/v1beta1                    false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io/v1      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1      true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1      true         Role
priorityclasses                   pc           scheduling.k8s.io/v1              false        PriorityClass
csidrivers                                     storage.k8s.io/v1                 false        CSIDriver
csinodes                                       storage.k8s.io/v1                 false        CSINode
storageclasses                    sc           storage.k8s.io/v1                 false        StorageClass
volumeattachments                              storage.k8s.io/v1                 false        VolumeAttachment

이 목록 중 pods, replicasets, deployments, services는 application을 배포하기 위해 반드시 있어야 할 필수적인 요소이므로 알아두는 게 좋다.

또한 목록엔 NAME이 복수형으로 끝에 s가 붙어 있지만 복수가 아닌 단수로도 호출이 된다.

kubectl get pods
kubectl get pod

또한 SHORTNAME을 사용하면 좀 더 간결하게 확인할 수 있다.

kubectl get po

사용 가능한 api version 확인

인터넷에 돌아다니는 yaml 파일 예제들을 실행하면 안 되는 경우가 많다.
이 중 api version이 현재 kubernetes에서 지원되지 않는 경우라면 아래 명령어를 통해 현재 지원되는 api version을 확인하면 된다.

kubectl api-versions

이 글 작성 시점 기준으로 대략 다음과 같은 api-version 들을 확인할 수 있다.

admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

resource 생성

resource를 생성하기 위해서는 kubernetes API에 정의된 api 형태에 맞춰 yaml 파일을 생성하여 아래와 같이 실행한다.

1개의 yaml 파일에 여러 종류의 resource를 '---' 구분자로 나누어 선언할 수 있으며 한꺼번에 생성된다.

kubectl apply -f [해당 yaml 파일]

resource 삭제

생성 시 사용한 yaml 파일을 지정하면 해당 resource를 삭제한다.

해당 yaml 파일에 여러 종류의 resource를 '---' 구분자로 나누어 선언할 수 있으며 한꺼번에 삭제된다.

kubectl delete -f [해당 yaml 파일]

만약 직접 해당 resource type에 대해 직접 지우고 싶은 경우 아래처럼 사용한다.

kubectl delete [TYPE] [NAME]

예를 들어 pod를 지우고 싶은 경우 다음과 같다.

kubectl delete pod [pod NAME]

라이브에서 쓰면 안 되지만 개별 공부하면서 사용하는 경우 아래처럼 사용하여 일괄 삭제도 가능함

kubectl delete deployment,pod,rs --all

resource 확인

kubectl get [해당 resource]

pod를 확인하는 경우 다음과 같다.

kubectl get pods

보통 수많은 pod를 사용하기 때문에 특정 pod만 찾아서 보는 경우가 많다.

kubectl get pods | grep [pod name]

window에서 사용하는 경우 window의 findstr 명령어를 사용한다.

kubectl get pods | findstr [pod name]

pods가 실행 중인 node 정보까지 확인하고 싶은 경우 -o wide 옵션을 사용한다.

kubectl get pods -o wide

label 도 같이 확인

kubectl get pods --show-labels

resource 정보 확인

kubectl describe [해당 resource name]

보통 pod가 제대로 뜨지 않은 경우 log를 확인하거나 해당 pod의 describe 정보를 확인하여 원인을 확인한다.

pod log 확인

kubectl logs POD [-c CONTAINER] [--follow] [flags]

예를 들어 해당 pod의 최근 100 라인을 보고 싶은 경우 다음과 같다.

kubectl logs [pod NAME] -f --tail=100

만약 해당 pods가 여러 개의 container를 가지고 있는 경우 -c 옵션으로 대상 container를 지정하면 된다.

kubectl logs [pod NAME] -c [container NAME] -f --tail=100

보통 1개 pod만 띄우지 않고 replica set 설정으로 여러 개의 pod를 띄우는데 이 전체 pod에 대한 로그를 확인하고 싶은 경우 대략 다음과 같이 사용한다.

kubectl logs -f --since=10m deployment/[deployment NAME]

pod의 container 명령 실행

kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]

예를 들어 특정 pod에 들어가고 싶은 경우 다음과 같다.

kubectl exec [pod NAME] -it /bin/bash

만약 해당 pods가 여러 개의 container를 가지고 있는 경우 -c 옵션으로 대상 container를 지정하면 된다.

kubectl exec [pod NAME] -c [container NAME] -it /bin/bash

-c에 넣을 container name을 모르더라도 해당 option 없이 사용하면 어떤 container를 사용할지 안내하는 메시지에서 container name을 확인할 수 있다. (또는 describe pod로 확인 가능)

node 목록 확인

kubectl get nodes

resource 사용량 확인

kubectl top [resource]
kubectl top pods
kubectl top nodes

cluster 정보 확인

kubectl cluster-info

autoscaling 관련 상태 확인

replica set을 설정하여 autoscaling을 하는 경우 모니터링을 할 때 사용한다.

kubectl get hpa

기타 설명

보통 pod를 생성하면 기본적으로 deployment, service, endpoint 같은 resource가 생성된다.

따라서 pod 생성 후 이런 resource들이 어떻게 생성되었는지를 kubectl 명령어를 통해 살펴보면서 좋다.

또는 command line 명령어로 사용하는 것보다 gui를 선호한다면 lens 같은 app을 추천한다.

https://k8slens.dev/

 

Lens | The Kubernetes IDE

Lens IDE for Kubernetes. The only system you’ll ever need to take control of your Kubernetes clusters. It's open source and free. Download it today!

k8slens.dev

 

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요