Menu
CoddyTech

쿠버네티스 치트시트

마지막 업데이트

컨텍스트와 클러스터 정보

컨텍스트는 클러스터, 사용자, 기본 네임스페이스의 묶음이며 ~/.kube/config에 저장됩니다.

기능명령어
클라이언트와 서버 버전 보기kubectl version
클러스터 주소 보기kubectl cluster-info
컨텍스트 목록kubectl config get-contexts
현재 컨텍스트 보기kubectl config current-context
다른 컨텍스트로 전환kubectl config use-context prod
이 컨텍스트의 기본 네임스페이스 설정kubectl config set-context --current --namespace=dev
병합된 kubeconfig 보기kubectl config view
노드 목록kubectl get nodes
모든 리소스 타입과 짧은 이름 목록kubectl api-resources
리소스 필드 설명 보기kubectl explain deployment.spec.replicas

리소스 목록 보기

kubectl get은 한 타입의 리소스 목록을 보여 줍니다. 다른 네임스페이스를 보려면 -n을 붙이세요.

기능명령어
현재 네임스페이스의 파드 목록kubectl get pods
모든 네임스페이스의 파드 목록kubectl get pods -A
특정 네임스페이스의 파드 목록kubectl get pods -n kube-system
노드와 IP 열 추가kubectl get pods -o wide
레이블 보기kubectl get pods --show-labels
레이블로 필터링kubectl get pods -l app=web
필드로 필터링kubectl get pods --field-selector status.phase=Running
변경 사항을 계속 지켜보기kubectl get pods -w
디플로이먼트, 서비스, 파드를 함께 보기kubectl get deploy,svc,pods
주요 리소스 목록kubectl get all
리소스 하나를 YAML로 보기kubectl get deployment web -o yaml
서비스 목록kubectl get svc
네임스페이스 목록kubectl get ns
최근 이벤트를 오래된 순으로 보기kubectl get events --sort-by=.metadata.creationTimestamp

describe, logs, exec

파드가 Running 상태가 아닐 때 살펴볼 곳입니다.

기능명령어
파드의 상세 정보와 이벤트 보기kubectl describe pod web-7d4b9c8f6-x2k8p
디플로이먼트 상세 정보 보기kubectl describe deployment web
파드 로그 보기kubectl logs web-7d4b9c8f6-x2k8p
로그 따라가기kubectl logs -f web-7d4b9c8f6-x2k8p
재시작 전 컨테이너의 로그kubectl logs --previous web-7d4b9c8f6-x2k8p
파드 안 컨테이너 하나의 로그kubectl logs web-7d4b9c8f6-x2k8p -c sidecar
디플로이먼트에 속한 파드들의 로그kubectl logs deployment/web
레이블이 붙은 모든 파드의 로그kubectl logs -l app=web --tail=50
파드에서 셸 열기kubectl exec -it web-7d4b9c8f6-x2k8p -- sh
파드에서 명령 하나 실행kubectl exec web-7d4b9c8f6-x2k8p -- env
로컬 8080 포트를 파드의 80 포트로 포워딩kubectl port-forward pod/web-7d4b9c8f6-x2k8p 8080:80
서비스로 포워딩kubectl port-forward svc/web 8080:80
파드 밖으로 파일 복사kubectl cp web-7d4b9c8f6-x2k8p:/etc/nginx/nginx.conf ./nginx.conf
CPU와 메모리 사용량 보기(metrics-server 필요)kubectl top pods
셸이 있는 임시 파드 시작kubectl run tmp --rm -it --image=busybox -- sh

생성과 적용

apply는 리소스를 만들거나 파일 내용에 맞게 업데이트합니다. Git으로 관리하는 매니페스트에는 이 명령을 쓰세요.

기능명령어
파일로 생성 또는 업데이트kubectl apply -f deployment.yaml
폴더 안의 모든 파일 적용kubectl apply -f k8s/
kustomization 폴더 적용kubectl apply -k overlays/prod
apply로 무엇이 바뀌는지 보기kubectl diff -f deployment.yaml
디플로이먼트 생성kubectl create deployment web --image=nginx --replicas=3
파드 하나 시작kubectl run web --image=nginx
디플로이먼트를 서비스로 노출kubectl expose deployment web --port=80 --target-port=8080
모든 노드의 포트로 노출kubectl expose deployment web --type=NodePort --port=80
값으로 컨피그맵 생성kubectl create configmap app-config --from-literal=LOG_LEVEL=debug
값으로 시크릿 생성kubectl create secret generic db-pass --from-literal=password=s3cret
파일로 컨피그맵 생성kubectl create configmap nginx-conf --from-file=nginx.conf
생성하지 않고 디플로이먼트 YAML만 작성kubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yaml
잡을 한 번 실행kubectl create job hello --image=busybox -- echo hello
실행 중인 리소스를 에디터로 수정kubectl edit deployment web

디플로이먼트와 롤아웃

기능명령어
레플리카 5개로 스케일링kubectl scale deployment web --replicas=5
이미지 변경(롤아웃 시작)kubectl set image deployment/web nginx=nginx:1.27
롤아웃이 끝날 때까지 지켜보기kubectl rollout status deployment/web
롤아웃 기록 보기kubectl rollout history deployment/web
이전 버전으로 롤백kubectl rollout undo deployment/web
특정 리비전으로 롤백kubectl rollout undo deployment/web --to-revision=2
디플로이먼트의 모든 파드 재시작kubectl rollout restart deployment/web
롤아웃 일시 중지kubectl rollout pause deployment/web
롤아웃 다시 진행kubectl rollout resume deployment/web
CPU 사용량에 따라 오토스케일링kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70
환경 변수 설정kubectl set env deployment/web LOG_LEVEL=debug
CPU와 메모리 요청량 설정kubectl set resources deployment web --requests=cpu=100m,memory=128Mi

삭제

디플로이먼트는 삭제된 파드를 다시 만듭니다. 파드를 완전히 없애려면 디플로이먼트를 삭제하세요.

기능명령어
파일로 만든 리소스 삭제kubectl delete -f deployment.yaml
파드 삭제kubectl delete pod web-7d4b9c8f6-x2k8p
디플로이먼트와 그 파드 삭제kubectl delete deployment web
레이블로 파드 삭제kubectl delete pods -l app=web
기다리지 않고 파드 즉시 삭제kubectl delete pod web-7d4b9c8f6-x2k8p --grace-period=0 --force
네임스페이스와 그 안의 모든 것 삭제kubectl delete namespace dev

네임스페이스

기능명령어
네임스페이스 목록kubectl get namespaces
네임스페이스 생성kubectl create namespace dev
네임스페이스를 지정해 아무 명령이나 실행kubectl get pods -n dev
이 컨텍스트의 기본값으로 지정kubectl config set-context --current --namespace=dev
현재 컨텍스트의 네임스페이스 보기kubectl config view --minify -o jsonpath='{..namespace}'

레이블과 어노테이션

기능명령어
레이블 추가kubectl label pods web-7d4b9c8f6-x2k8p tier=frontend
레이블 변경kubectl label pods web-7d4b9c8f6-x2k8p tier=backend --overwrite
레이블 삭제kubectl label pods web-7d4b9c8f6-x2k8p tier-
어노테이션 추가kubectl annotate deployment web owner=team-a
필드 패치kubectl patch deployment web -p '{"spec":{"replicas":2}}'

노드

기능명령어
IP와 OS를 포함한 노드 목록kubectl get nodes -o wide
노드의 용량, 상태, 파드 보기kubectl describe node worker-1
노드에 새 파드가 배치되지 않게 하기kubectl cordon worker-1
유지 보수 전에 노드에서 파드 옮기기kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-data
노드에 다시 파드 배치 허용kubectl uncordon worker-1
테인트 추가kubectl taint nodes worker-1 gpu=true:NoSchedule
테인트 제거kubectl taint nodes worker-1 gpu=true:NoSchedule-
노드 CPU와 메모리 사용량 보기(metrics-server 필요)kubectl top nodes

출력 형식

어떤 get에든 -o를 붙이면 출력 내용을 바꿀 수 있습니다.

기능명령어
전체 오브젝트를 YAML로kubectl get pod web-7d4b9c8f6-x2k8p -o yaml
전체 오브젝트를 JSON으로kubectl get pod web-7d4b9c8f6-x2k8p -o json
이름만(type/name)kubectl get pods -o name
JSONPath로 필드 고르기kubectl get pods -o jsonpath='{.items[*].metadata.name}'
원하는 열 직접 지정kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName
필드로 정렬kubectl get pods --sort-by=.status.startTime
시크릿 값 디코딩kubectl get secret db-pass -o jsonpath='{.data.password}' | base64 -d

짧은 이름

대부분의 리소스 타입에는 대신 입력할 수 있는 짧은 이름이 있습니다.

리소스짧은 이름
Podpo
Deploymentdeploy
ReplicaSetrs
StatefulSetsts
DaemonSetds
Servicesvc
Ingressing
ConfigMapcm
Namespacens
Nodeno
PersistentVolumeClaimpvc
PersistentVolumepv
ServiceAccountsa
HorizontalPodAutoscalerhpa
CronJobcj

쿠버네티스(k8s)를 다룰 때 자주 쓰는 kubectl 명령어를 복사해 바로 쓰는 표로 정리했습니다. 먼저 컨텍스트와 네임스페이스를 다루고, 이어서 리소스 목록과 상세 정보, logs와 exec, 매니페스트 적용, 디플로이먼트와 롤아웃, 스케일링, 레이블, 노드, 출력 형식을 다룹니다.

kubectl은 현재 컨텍스트가 가리키는 클러스터와 통신하므로, 무언가를 삭제하기 전에 kubectl config current-context로 확인하세요. 클러스터 없이 명령어를 실행해 보려면 단일 노드 쿠버네티스 시뮬레이터가 내장된 터미널 플레이그라운드를 열어 보세요.

kubectl 치트시트 자주 묻는 질문

kubectl이란 무엇인가요?
kubectl은 쿠버네티스의 명령줄 클라이언트로, 입력한 명령을 클러스터의 API 서버로 보냅니다. kubectl get pods는 파드 목록을 보여 주고, kubectl apply -f는 YAML로 리소스를 만들거나 업데이트하며, kubectl logs와 kubectl exec는 실행 중인 컨테이너 안을 들여다봅니다. 어떤 클러스터와 통신할지는 ~/.kube/config의 현재 컨텍스트가 정합니다.
k8s와 Kubernetes는 같은 건가요?

네. k8s는 Kubernetes의 줄임말로, 첫 글자 k, 가운데 글자 8개, 마지막 s를 뜻합니다. 클러스터를 다루는 도구가 kubectl이므로 k8s 치트시트가 곧 kubectl 치트시트입니다.

kubectl apply와 kubectl create의 차이는 무엇인가요?
kubectl create는 리소스를 만들며, 이미 있으면 실패합니다. kubectl apply는 리소스를 만들거나 파일 내용에 맞게 업데이트하므로 변경할 때마다 다시 실행할 수 있습니다. Git으로 관리하는 매니페스트에는 apply를, 빠르게 만드는 일회성 리소스에는 create를 쓰세요.
파드가 시작되지 않는 이유는 어떻게 확인하나요?
kubectl describe pod <name>을 실행하고 맨 아래의 Events를 읽으세요. 이미지 풀 오류, 스케줄링 실패, 프로브 실패가 여기에 나타납니다. 컨테이너가 시작된 뒤 크래시했다면 kubectl logs --previous <name>으로 크래시한 실행의 출력을 볼 수 있습니다.
kubectl에서 네임스페이스를 전환하려면 어떻게 하나요?
명령 하나에만 적용하려면 -n dev를 붙이고, 현재 컨텍스트의 기본값을 dev로 바꾸려면 kubectl config set-context --current --namespace=dev를 실행하세요.
디플로이먼트를 재시작하려면 어떻게 하나요?
kubectl rollout restart deployment/web은 모든 파드를 몇 개씩 차례로 새 파드로 교체하며, 레플리카가 둘 이상이면 다운타임이 없습니다. kubectl rollout status deployment/web으로 끝날 때까지 기다릴 수 있습니다.
kubectl 명령어를 온라인에서 연습할 수 있나요?
네. 터미널 플레이그라운드에는 단일 노드 쿠버네티스 시뮬레이터가 있어 kubectl get, describe, apply, logs, exec, 디플로이먼트, 롤아웃, 서비스가 실제 클러스터처럼 응답하며, 설치할 것이 없습니다. port-forward, edit 같은 일부 명령은 kind나 minikube 같은 실제 클러스터가 필요합니다.
이 kubectl 치트시트는 무료인가요?

네. 무료로 읽고 복사하고 인쇄할 수 있으며 회원 가입이 필요 없습니다.

Coddy 프로그래밍 언어 일러스트

Coddy로 Kubernetes 배우기

시작하기