EasyDebug.NET

kubectl 명령어 치트시트

컨텍스트부터 클러스터까지 9개 그룹과 실행 예시

명령어 90개

kubectl config get-contexts컨텍스트와 조회

모든 컨텍스트 목록, 클러스터 혼동은 흔한 사고

kubectl config get-contexts
kubectl config use-context prod컨텍스트와 조회

현재 컨텍스트 전환, 변경 전 반드시 확인

kubectl config use-context prod-cn
kubectl config current-context컨텍스트와 조회

현재 클러스터 확인, 스크립트 사전 검증에 유용

kubectl config current-context
kubectl config set-context --current --namespace=staging컨텍스트와 조회

기본 네임스페이스 고정, 매번 -n 생략

kubectl config set-context --current --namespace=staging
kubectl get ns컨텍스트와 조회

네임스페이스 목록

kubectl get ns
kubectl get all -n app컨텍스트와 조회

네임스페이스의 주요 리소스 한 번에 조회

kubectl get all -n app
kubectl get pods -o wide컨텍스트와 조회

IP와 노드 열 추가, 스케줄링과 네트워크 확인에 필수

kubectl get pods -o wide -n app
kubectl get pods -A컨텍스트와 조회

모든 네임스페이스의 Pod 조회

kubectl get pods -A --field-selector=status.phase!=Running
kubectl get pods -w컨텍스트와 조회

목록 변화를 계속 지켜봄, 롤아웃 관찰에 유용

kubectl get pods -w -n app
kubectl get pod web-0 -o yaml컨텍스트와 조회

리소스의 전체 YAML 출력(런타임 상태 포함)

kubectl get pod web-0 -o yaml > pod-backup.yaml
kubectl get deploy web -o yaml --export컨텍스트와 조회

클러스터 생성 필드 제거, 재적용에 편리

kubectl get deploy web -o yaml -n app
kubectl explain deploy.spec.strategy컨텍스트와 조회

터미널에서 필드 의미와 허용 값 확인

kubectl explain deploy.spec.strategy --recursive
kubectl api-resources컨텍스트와 조회

클러스터가 지원하는 모든 리소스 종류와 약어

kubectl api-resources --namespaced=true
kubectl apply -f deploy.yaml컨텍스트와 조회

선언형 적용, 반복 실행해도 안전

kubectl apply -f k8s/ -n app
kubectl delete -f deploy.yaml컨텍스트와 조회

매니페스트에 정의된 리소스 삭제

kubectl delete -f k8s/ -n app
kubectl create ns staging컨텍스트와 조회

네임스페이스 생성

kubectl create ns staging
kubectl describe pod <pod>Pod 작업

Pod 상세 정보, 마지막 Events 섹션이 핵심

kubectl describe pod web-0 -n app
kubectl logs <pod>Pod 작업

컨테이너 로그 조회

kubectl logs web-0 -n app --tail=200
kubectl logs -f <pod> -c appPod 작업

특정 컨테이너 로그 추적, 다중 컨테이너 Pod는 -c 필요

kubectl logs -f web-0 -c app -n app
kubectl logs --previous <pod>Pod 작업

직전 크래시 로그 확인, CrashLoopBackOff에 필수

kubectl logs web-0 --previous -n app
kubectl logs --since=10m <pod>Pod 작업

최근 10분 로그만 조회

kubectl logs web-0 --since=10m --timestamps -n app
kubectl exec -it <pod> -- shPod 작업

컨테이너 접속, 경량 이미지에는 대개 bash 없음

kubectl exec -it web-0 -n app -- /bin/sh
kubectl exec <pod> -- envPod 작업

컨테이너에 실제 적용된 환경변수 확인

kubectl exec web-0 -n app -- printenv
kubectl cp ./local.txt <pod>:/tmp/Pod 작업

로컬과 Pod 간 파일 복사

kubectl cp ./dump.sql app/web-0:/tmp/dump.sql
kubectl port-forward <pod> 8080:80Pod 작업

Pod 포트를 로컬로 포워딩, 노출되지 않은 서비스 디버깅

kubectl port-forward pod/web-0 8080:80 -n app
kubectl run tmp --rm -it --image=busybox -- shPod 작업

일회용 디버그 파드, 종료 시 정리

kubectl run tmp --rm -it --image=busybox:1.36 --restart=Never -- sh
kubectl get pod <pod> -o jsonpath="{.status.podIP}"Pod 작업

Pod IP 추출, 스크립트에 활용

kubectl get pod web-0 -o jsonpath="{.status.podIP}" -n app
kubectl delete pod <pod>Pod 작업

Pod 삭제, 컨트롤러 관리 대상은 자동 재생성

kubectl delete pod web-0 -n app
kubectl delete pod <pod> --grace-period=0 --forcePod 작업

Terminating에 멈춘 Pod 강제 삭제

kubectl delete pod web-0 --grace-period=0 --force -n app
kubectl get pod <pod> -o jsonpath="{.status.containerStatuses[*].restartCount}"Pod 작업

재시작 횟수 확인, 반복 크래시 판단

kubectl get pod web-0 -o jsonpath="{.status.containerStatuses[*].restartCount}" -n app
kubectl get deploy배포와 확장

Deployment 목록과 레플리카 준비 상태

kubectl get deploy -n app -o wide
kubectl scale deploy/web --replicas=3배포와 확장

레플리카 수 조정, 가장 직접적인 확장 방법

kubectl scale deploy/web --replicas=3 -n app
kubectl set image deploy/web web=app:1.1배포와 확장

이미지 버전 롤링 업데이트

kubectl set image deploy/web web=registry.example.com/app:1.1 -n app
kubectl edit deploy/web배포와 확장

운영 중 설정 직접 편집, 저장 즉시 반영

kubectl edit deploy/web -n app
kubectl patch deploy/web --type=merge -p "{\"spec\":{\"replicas\":2}}"배포와 확장

한 줄 JSON으로 필드 수정, 스크립트에 적합

kubectl patch deploy/web --type=merge -p "{\"spec\":{\"replicas\":2}}" -n app
kubectl autoscale deploy/web --min=2 --max=10 --cpu-percent=70배포와 확장

수평 자동 확장 설정

kubectl autoscale deploy/web --min=2 --max=10 --cpu-percent=70 -n app
kubectl get rs배포와 확장

ReplicaSet 목록, 이전 버전 확인

kubectl get rs -n app
kubectl get deploy web -o jsonpath="{.spec.template.spec.containers[*].image}"배포와 확장

운영 중 실제 이미지 확인

kubectl get deploy web -o jsonpath="{.spec.template.spec.containers[*].image}" -n app
kubectl annotate deploy/web note="release-1.1"배포와 확장

주석 추가, 릴리스 정보 기록

kubectl annotate deploy/web note="release-1.1" --overwrite -n app
kubectl label deploy/web tier=web배포와 확장

레이블 추가, Service 셀렉터와 조회에 사용

kubectl label deploy/web tier=web --overwrite -n app
kubectl rollout status deploy/web롤아웃과 롤백

롤아웃 진행 상황 확인, 배포 후 필수

kubectl rollout status deploy/web -n app --timeout=120s
kubectl rollout history deploy/web롤아웃과 롤백

이전 버전과 변경 사유 확인

kubectl rollout history deploy/web -n app
kubectl rollout undo deploy/web롤아웃과 롤백

이전 버전으로 롤백, 장애 시 가장 빠른 복구

kubectl rollout undo deploy/web -n app
kubectl rollout undo deploy/web --to-revision=2롤아웃과 롤백

특정 버전으로 롤백, history 확인 후 결정

kubectl rollout undo deploy/web --to-revision=2 -n app
kubectl rollout restart deploy/web롤아웃과 롤백

모든 Pod 재시작, 설정 변경 후 자주 사용

kubectl rollout restart deploy/web -n app
kubectl rollout pause deploy/web롤아웃과 롤백

롤아웃 일시 중지, 확인 후 재개 가능

kubectl rollout pause deploy/web -n app
kubectl rollout resume deploy/web롤아웃과 롤백

중지된 롤아웃 재개

kubectl rollout resume deploy/web -n app
kubectl get svcService와 네트워크

Service 목록과 ClusterIP, 포트

kubectl get svc -n app -o wide
kubectl get endpoints webService와 네트워크

Service 뒤의 실제 Pod IP 확인, 비어 있으면 셀렉터 불일치

kubectl get endpoints web -n app
kubectl describe svc webService와 네트워크

Service 상세, 셀렉터와 포트 매핑 포함

kubectl describe svc web -n app
kubectl expose deploy/web --port=80 --target-port=8080Service와 네트워크

Deployment를 Service로 노출

kubectl expose deploy/web --port=80 --target-port=8080 --type=ClusterIP -n app
kubectl port-forward svc/web 8080:80Service와 네트워크

Service 포트 포워딩, Ingress 없이 로컬 검증

kubectl port-forward svc/web 8080:80 -n app
kubectl get ingressService와 네트워크

Ingress 목록과 노출 도메인

kubectl get ingress -n app
kubectl describe ingress webService와 네트워크

Ingress 규칙과 백엔드 해석 결과

kubectl describe ingress web -n app
kubectl get netpolService와 네트워크

네트워크 정책 목록, Pod 간 통신 문제 시 확인

kubectl get netpol -n app
kubectl get svc web -o jsonpath="{.spec.clusterIP}"Service와 네트워크

ClusterIP 추출, 설정이나 스크립트에 사용

kubectl get svc web -o jsonpath="{.spec.clusterIP}" -n app
kubectl get cm설정과 시크릿

ConfigMap 목록

kubectl get cm -n app
kubectl create cm app-config --from-file=app.yaml설정과 시크릿

파일로 ConfigMap 생성

kubectl create cm app-config --from-file=config/app.yaml -n app
kubectl describe cm app-config설정과 시크릿

ConfigMap 내용 확인

kubectl describe cm app-config -n app
kubectl get secret설정과 시크릿

Secret 목록, 값은 암호화가 아닌 base64

kubectl get secret -n app
kubectl create secret generic db --from-literal=password=changeit설정과 시크릿

리터럴로 Secret 생성

kubectl create secret generic db --from-literal=password=changeit -n app
kubectl get secret db -o jsonpath="{.data.password}" | base64 -d설정과 시크릿

Secret 평문 디코딩, 설정 미반영 디버깅

kubectl get secret db -o jsonpath="{.data.password}" -n app | base64 -d
kubectl get sa설정과 시크릿

ServiceAccount 목록, Pod의 API 접근 신원

kubectl get sa -n app
kubectl auth can-i get pods --as=system:serviceaccount:app:web설정과 시크릿

특정 신원의 권한 확인, RBAC 디버깅

kubectl auth can-i get pods --as=system:serviceaccount:app:web -n app
kubectl get nodes노드와 스케줄링

노드와 상태 목록

kubectl get nodes -o wide
kubectl describe node <node>노드와 스케줄링

노드 상세, 할당된 리소스와 테인트 포함

kubectl describe node node-1
kubectl top nodes노드와 스케줄링

노드 실제 리소스 사용량, metrics-server 필요

kubectl top nodes
kubectl top pods노드와 스케줄링

Pod 리소스 사용량, 메모리 과다 사용 확인

kubectl top pods -n app --sort-by=memory
kubectl cordon <node>노드와 스케줄링

노드 스케줄 불가 표시, 기존 Pod는 유지

kubectl cordon node-1
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data노드와 스케줄링

노드의 Pod 축출, 유지보수 전 필수

kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data
kubectl uncordon <node>노드와 스케줄링

노드 스케줄 가능 상태로 복구

kubectl uncordon node-1
kubectl taint nodes node-1 dedicated=gpu:NoSchedule노드와 스케줄링

노드 테인트 추가, 톨러레이션이 있는 Pod만 스케줄

kubectl taint nodes node-1 dedicated=gpu:NoSchedule
kubectl get events --sort-by=.lastTimestamp문제 해결

시간 역순 이벤트 조회, 클러스터 수준 문제 확인

kubectl get events --sort-by=.lastTimestamp -n app | tail -30
kubectl get events -w문제 해결

이벤트 스트림 실시간 관찰, 재현 시 유용

kubectl get events -w -n app
kubectl get pod --field-selector=status.phase=Failed문제 해결

실패 상태 Pod 필터링

kubectl get pod --field-selector=status.phase=Failed -A
kubectl get pod <pod> -o jsonpath="{.status.conditions[?(@.type==\"Ready\")].reason}"문제 해결

준비되지 않은 이유 조회, describe보다 빠름

kubectl get pod web-0 -o jsonpath="{.status.conditions[?(@.type==\"Ready\")].reason}" -n app
kubectl debug -it <pod> --image=busybox --target=app문제 해결

기존 Pod에 임시 컨테이너 주입, 프로세스 네임스페이스 공유

kubectl debug -it web-0 --image=busybox:1.36 --target=app -n app
kubectl debug node/<node> -it --image=busybox문제 해결

노드에서 디버그 Pod 실행, 호스트 파일시스템 접근

kubectl debug node/node-1 -it --image=busybox:1.36
kubectl logs <pod> --all-containers문제 해결

Pod 내 모든 컨테이너 로그 조회

kubectl logs web-0 --all-containers --prefix -n app
kubectl wait --for=condition=Ready pod/web-0 --timeout=60s문제 해결

Pod 준비 대기, 스크립트 동기화 지점

kubectl wait --for=condition=Ready pod/web-0 --timeout=60s -n app
kubectl get pod web-0 -o json | jq .status문제 해결

jq로 상태 필드 정밀 조회, jsonpath보다 작성 편함

kubectl get pod web-0 -o json -n app | jq .status
kubectl get pod web-0 -o yaml --show-managed-fields문제 해결

필드를 누가 변경했는지 확인

kubectl get pod web-0 -o yaml --show-managed-fields -n app
kubectl cluster-info클러스터와 리소스

컨트롤 플레인 주소와 애드온 위치

kubectl cluster-info
kubectl version --short클러스터와 리소스

클라이언트와 서버 버전 확인, 버전 차이 주의

kubectl version --short
kubectl apply --dry-run=server -f deploy.yaml클러스터와 리소스

서버 측 드라이런, 실제 검증만 하고 반영 안 함

kubectl apply --dry-run=server -f deploy.yaml -n app
kubectl diff -f deploy.yaml클러스터와 리소스

apply가 바꿀 필드 미리 확인

kubectl diff -f deploy.yaml -n app
kubectl get pv,pvc클러스터와 리소스

볼륨과 클레임 조회, Pending은 대개 스토리지 클래스 문제

kubectl get pv,pvc -n app
kubectl get hpa클러스터와 리소스

자동 확장 상태와 현재 지표 확인

kubectl get hpa -n app
kubectl get crd클러스터와 리소스

클러스터에 설치된 CRD 목록

kubectl get crd | head -30
kubectl api-resources --verbs=list --namespaced -o name클러스터와 리소스

조회 가능한 네임스페이스 리소스 목록, 백업 스크립트에 유용

kubectl api-resources --verbs=list --namespaced -o name

뭔가 잘못됐거나 빠진 게 있나요?

피드백 보내기
작성자의 블로그
아이디어 보내기