공부/Kubernetes

쿠버네티스 명령어

Lai_Khan 2024. 7. 17. 23:21
앞에서 생성한 NCP Kubernetes Cluster를 컨트롤하기 위해 kubectl 명령툴을 사용한다.
쿠버네티스 서버는 REST API로 통신한다. 이를 쉽게 통신할 수 있게 해주는 클라이언트 툴이 kubectl이다.
기본적인 사용법에 대해 정리한다.

 

기본 명령

◈ 컨테이너 실행

kubectl run <NAME> --image <IMAGE>

# 예시
kubectl run mynginx --image nginx
pod/mynginx created

# 도커 명령 비교
docker run

 

  컨테이너 조회

kubectl get pod

# 결과
NAME      READY   STATUS    RESTARTS   AGE
mynginx   1/1     Running   0          12s

 

  • 쿠버네티스의 최소 실행단위는 pod다.
  • 대충 컨테이너 = pod라고 이해하고 넘어가자.

 

  특정 pod 상태 정보 조회

kubectl get pod <NAME> -o yaml

# 예시
kubectl get pod mynginx -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2024-07-15T16:06:54Z"
  labels:
    run: mynginx
  name: mynginx
...

 

  pod의 IP 바로 확인

kubectl get pod -o wide

# 결과
NAME      READY   STATUS    RESTARTS   AGE   IP            NODE           NOMINATED NODE   READINESS GATES
mynginx   1/1     Running   0          10m   198.18.0.44   node1-w-5agx   <none>           <none>

# 도커 명령 비교
docker ps

 

컨테이너 상세 정보 확인

kubectl describe pod <NAME>

# 예시
kubectl describe pod mynginx
Name:         mynginx
Namespace:    default
Priority:     0
Node:         node1-w-5agx/172.16.3.6
Start Time:   Tue, 16 Jul 2024 01:06:54 +0900
Labels:       run=mynginx
Annotations:  <none>
Status:       Running
IP:           198.18.0.44
IPs:
  IP:  198.18.0.44
...

# 도커 명령 비교
docker inspect

 

  컨테이너 로깅

kubectl logs <NAME>

# 예시
kubectl logs -f mynginx
/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
...

# 도커 명령 비교
docker logs
  • -f, --follow 옵션은 출력 스트림이 종료되지 않고 지속적으로 로그를 출력한다.

 

컨테이너 명령 전달

kubectl exec <NAME> -- <CMD>

# 예시
kubectl exec mynginx -- apt-get update
Get:1 http://deb.debian.org/debian bookworm InRelease [151 kB]
Get:2 http://deb.debian.org/debian bookworm-updates InRelease [55.4 kB]
...

# 도커 명령 비교
docker exec

# -it 옵션을 사용해 컨테이너 내부로 들어가기
kubectl exec -it mynginx -- bash
  • 실행중인 컨테이너에 명령을 전달할 때 사용
  • -it 옵션을 사용해 컨테이너 내부로 들어갈 수 있다.

 

컨테이너 / 호스트 간 파일 복사

kubectl cp <TARGET> <SOURCE>

# 예시 <Host> -> <Container>
kubectl cp /etc/passwd mynginx:/tmp/passwd

# exec 명령으로 복사가 되었는지 확인
kubectl exec mynginx -- ls /tmp/passwd
kubectl exec mynginx -- cat /tmp/passwd

 

컨테이너 정보 수정

kubectl edit pod <NAME>

# 예시
kubectl edit pod mynginx
  • Windows에서는 메모장이 뜨며 수정할 수 있다. 리눅스는 vim

 

컨테이너 삭제

kubectl delete pod <NAME>

# 예시
kubectl delete pod mynginx

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

 

YAML 기반의 컨테이너 생성

kubectl apply -f <FINE_NAME>
# mynginx.yaml
apiVersion: v1
kind: Pod
metadata:
  name: mynginx
spec:
  containers:
    - name: mynginx
      image: nginx

기본 정보만 채우면 나머지는 쿠버네티스가 알아서 채운다.

 

kubectl apply -f mynginx.yaml
# pod/mynginx created

kubectl get pod
# NAME      READY   STATUS    RESTARTS   AGE
# mynginx   1/1     Running   0          43s

 

kubectl run 명령어와 동일하게 mynginx라는 컨테이너가 생성된다.

yaml 파일을 수정하고 다시 apply하면 기존 컨테이너의 설정값이 수정된다.

 

 

고급 명령

리소스별 명령

kubectl get service
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   198.19.128.1   <none>        443/TCP   4d5h

kubectl describe service kubernetes
Name:              kubernetes
Namespace:         default
Labels:            component=apiserver
                   provider=kubernetes
...

kubectl get node
NAME           STATUS   ROLES    AGE    VERSION
node1-w-5agx   Ready    <none>   4d5h   v1.28.10

kubectl describe node node1-w-5agx
Name:               node1-w-5agx
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
...

 

네임스페이스

kubectl get namespaces
NAME              STATUS   AGE
default           Active   4d5h
kube-node-lease   Active   4d5h
kube-public       Active   4d5h
kube-system       Active   4d5h

kubectl describe namespace kube-system
Name:         kube-system
Labels:       kubernetes.io/metadata.name=kube-system
Annotations:  <none>
Status:       Active
...

명령 실행시 --namespace 옵션(-n)으로 특정 네임스페이스에 리소스 생성 가능

  • default : 기본 네임스페이스
  • kube-system : 쿠버네티스의 핵심 컴포넌트들이 있는 네임스페이스
  • kube-public : 외부로 공개 가능한 리소스를 담고 있는 네잌스페이스
  • kube-node-lease : 노드가 살아있는지 마스터에 알리는 용도

 

모든 리소스 조회

kubectl api-resources
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
...

 

쿠버네티스 리소스는 네임스페이스 레벨 리소스와 클러스터 레벨 리소스로 나뉜다.

반드시 특정 네임스페이스에 속해야 하는 리소스와 상관없는 리소스.

네임스페이스 레벨 리소스만 탐색하려면 이렇게.

kubectl api-resources --namespaced=true

 

리소스 정의 설명

kubectl explain pods
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
...

 

클러스터 상태 확인

# 쿠버네티스 API 서버 작동 여부 확인
kubectl cluster-info

# 전체 노드 상태 확인
kubectl get node

# 쿠버네티스 핵심 컴포넌트의 Pod 상태 확인
kubectl get pod -n kube-system

 

클라이언트 설정 파일

kubectl config <SUBCOMMAND>

# 예시
kubectl config view

설정 파일은 크게 3가지 영역으로 나뉜다.

  1. clusters : kubectl 툴이 바라보는 클러스터 정보
  2. users : 쿠버네티스 클러스터에 접속하는 사용자 정의
  3. contexts : cluster와 user 연결

Clean up

kubectl delete pod --all