전체 치트시트

kubectl 명령어 치트시트

Kubernetes CLI 클라이언트 kubectl 의 빠른 참조: context, get/describe, apply, logs/exec, rollout, 스케일링과 디버깅 — 자주 쓰는 옵션과 실전 예시까지 정리했습니다.

명령어 40개

클러스터 & Context

kubectl version

클라이언트와 서버 버전 정보를 출력합니다(버전 차이 디버깅에 유용).

--client 클라이언트만; -o yaml/json

kubectl version -o yaml | yq '.clientVersion.minor'
kubectl cluster-info

클러스터의 마스터와 서비스 정보를 표시합니다.

--context ctx; --output json|yaml

kubectl cluster-info --context prod-eu
kubectl config get-contexts

kubeconfig 의 모든 context 를 나열합니다.

--minify; -o name|json|yaml

kubectl config get-contexts -o name | xargs -I{} echo {}
kubectl config use-context <name>

현재 context 를 다른 context 로 전환합니다.

kubectl config use-context prod-eu
kubectl config current-context / set-context <name>

현재 context 확인 / context 의 이름이나 설정(namespace, cluster, user) 변경.

--current 현재값 출력; set-context --namespace N --cluster C --user U

kubectl config set-context dev-team-a --namespace shop --cluster dev --user dev
kubectl config set <name> <value>

context 별 기본 namespace 를 바꿔 -n 을 매번 적지 않도록 합니다.

kubectl config set-context --current --namespace=argocd && kubectl get pods

Get & Inspect

kubectl get all

pod, service, deployment, replicaset, statefulset 등을 나열합니다.

-A 모든 namespace; -n ns; -l label=key=value 셀렉터; -o wide|yaml|json|name|custom-columns; --sort-by

kubectl get all -A -o wide | grep -i Error
kubectl get pods / svc / deploy / ds / sts

특정 리소스 타입 목록을 보여줍니다(가장 흔히 쓰는 리소스).

-A; -l app=api; -o wide (node, ip 표시); --field-selector; --sort-by .metadata.creationTimestamp

kubectl get pod -n kube-system -l k8s-app=metrics-server -o wide
kubectl get -o yaml|json

객체 전체를 YAML/JSON 으로 덤프해 조회하거나 내보냅니다.

-o yaml; --export 클러스터 설정 필드 제외하고 저장

kubectl get deploy api -n shop -o yaml | grep -E 'image|replicas|envFrom'
kubectl describe <type> <name>

저수준 상세, 이벤트, 컨테이너 상태, 생명주기를 표시합니다 — 디버깅에 최고.

-n ns; -A 모든 ns; --show-events=true

kubectl describe pod api-7c5d-xn2kq -n shop | tail -50
kubectl explain <resource[.field]>

API 서버의 스키마/필드 문서를 바로 보여줍니다.

kubectl explain pod.spec.containers.resources.limits

Apply & 관리

kubectl apply -f <file|dir|url>

클러스터 상태가 매니페스트와 일치하도록 적용/업데이트(선언적).

-f file|dir|URL; -R 재귀 dir; --prune; --force-conflicts server-side apply; --server-side

kubectl apply -k overlays/prod && kubectl apply -f https://.../manifests.yaml
kubectl diff -f <file>

`apply` 가 적용할 변경 사항을 미리 보여줍니다(KUBECTL_EXTERNAL_DIFF 또는 diff 바이너리 필요).

-R; --server-side; --prune

kubectl diff -f overlays/prod | head -50
kubectl create|delete -f <file>

매니페스트로 명령형(임퍼러티브) 생성 또는 삭제(1회성).

create -f; delete -f; delete pod foo; delete svc,deploy -l app=foo (복합)

kubectl delete -f bad-app.yaml --grace-period=0 --force
kubectl edit <type> <name>

실제 객체를 에디터로 엽니다(기본 vi).

-o yaml; --save-config; --windows-line-ending

KUBE_EDITOR="code --wait" kubectl edit deploy api -n shop
kubectl patch <type> <name> --patch '<json>'

실제 객체에 strategic-merge 또는 JSON-patch 를 적용합니다.

--type strategic|merge|json; --patch-file file.json

kubectl patch deploy api -n shop --type merge -p '{"spec":{"replicas":6}}'
kubectl set image <type> <name> container=image

새 이미지로 rollout 을 트리거합니다. `set image env / resources` 와 동일하게 사용 가능.

set image env / resources / serviceaccount / subject / selector

kubectl set image deploy/api api=ghcr.io/team/api:1.4.2 && kubectl rollout status deploy/api
kubectl label / annotate <type> <name>

실제 객체에 label / annotation 을 추가하거나 갱신합니다.

key=value 추가; key- 삭제(-로 끝남); --overwrite

kubectl label pod -n shop -l app=api release=v1.4.2 --overwrite

로그 & Exec

kubectl logs <pod>

pod 의 로그를 출력합니다(-c 로 특정 컨테이너 지정 가능).

-f follow; --tail N; --since R|D|T; --timestamps; -c container; --all-containers; -p previous

kubectl logs -n shop -f --tail 100 --timestamps api-7c5d-xn2kq
kubectl logs --previous

컨테이너의 직전 인스턴스 로그를 보여줍니다(크래시/롤아웃 후).

-c container; --tail N

kubectl logs -p api-7c5d-xn2kq -c api --tail 200 | grep panic
kubectl logs -l <label> --all-containers

label 로 매칭되는 모든 pod 의 로그를 모읍니다 — Deployment 에 잘 어울립니다.

-l app=api; --all-containers=true; -f; --max-log-requests N

kubectl logs -n shop -l app=worker --all-containers -f --max-log-requests 8
kubectl exec -it <pod> -- <cmd>

pod 안에서 명령을 실행합니다. 인터랙티브(bash/sh)도 가능합니다.

-it; -c container; -n ns; -- /bin/sh

kubectl exec -n shop -it api-7c5d-xn2kq -- /bin/sh -c 'printenv | grep DATABASE'
kubectl cp <pod>:<src> <dest>

exec 위에서 tar 로 동작: pod 안팎으로 파일/폴더를 복사합니다.

-c container; -n ns

kubectl cp shop/api-7c5d-xn2kq:app/config.yaml ./config.yaml
kubectl port-forward <pod> <local>:remote>

로컬 포트 한 개 이상을 pod(또는 svc, deploy)로 포워딩합니다.

pod/<name> <l>:r; svc/<name> <l>:r; --address 127.0.0.1

kubectl port-forward svc/argocd-server -n argocd 8443:443

Rollout & Scale

kubectl rollout status deploy/<name>

롤링 업데이트가 끝날 때까지 진행 상황을 지켜봅니다(또는 타임아웃).

--timeout 5m; --revision N

kubectl rollout status deploy/api -n shop --timeout 2m
kubectl rollout history / undo

롤아웃 히스토리 표시 / 이전 리비전으로 롤백.

history --revision N; undo --to-revision N; --dry-run=client

kubectl rollout history deploy/api -n shop && kubectl rollout undo deploy/api --to-revision=3
kubectl rollout restart deploy/<name>

pod 템플릿을 패치해 Deployment(DaemonSet/StatefulSet 포함)를 재시작합니다.

-n ns

kubectl rollout restart deploy api -n shop && kubectl get pods -l app=api -w
kubectl scale deploy/<n> --replicas=N

replica 수를 수동으로 설정합니다. 매니페스트는 변경되지 않습니다.

--current-replicas 사전 확인; --dry-run=client -o yaml

kubectl scale deploy/api -n shop --current-replicas 2 --replicas 6
kubectl autoscale deploy/<n> --min=2 --max=10 --cpu-percent=80

지정한 범위로 HPA 를 만듭니다(`kubectl create hpa` 도 가능).

--max --min --cpu-percent; --dry-run=client -o yaml

kubectl autoscale deploy/api -n shop --min=3 --max=15 --cpu-percent=70

Node & Pod 생명주기

kubectl drain <node> --ignore-daemonsets --delete-emptydir-data

유지 보수(예: 업그레이드) 전 노드에서 pod 을 안전하게 비웁니다.

--grace-period N; --force; --skip-errors; --dry-run; --delete-emptydir-data

kubectl drain ip-10-0-1-7 --ignore-daemonsets --delete-emptydir-data --grace-period 60
kubectl cordon / uncordon <node>

노드를 스케줄 불가(cordon) / 가능(uncordon) 상태로 표시합니다. 유지 보수 후 uncordon 합니다.

--name 옵션 없이 노드명 사용

kubectl cordon ip-10-0-1-7 && kubectl uncordon ip-10-0-1-7
kubectl delete pod <pod>

pod 을 삭제합니다. Deployment 의 경우 컨트롤러가 새 pod 을 만들고(단일 인스턴스 강제 재시작 용도).

--grace-period=0 --force; -n ns; --now

kubectl delete pod -n shop api-7c5d-xn2kq --grace-period=0 --force

디버그

kubectl top node / pod

실시간 CPU/메모리 사용량을 표시합니다(metrics-server 필요).

--sort-by cpu|memory; --containers; -A; -l

kubectl top node && kubectl top pod -A --sort-by=memory | head
kubectl debug <pod>

디버깅 도구가 들어 있는 디버그 컨테이너를 붙입니다(kubectl-debug / Ephemeral Containers).

--image <img>; --target-container; --share-processes; --profile

kubectl debug -it api-7c5d-xn2kq --image=nicolaka/netshoot --target-container=api
kubectl get events --sort-by=.lastTimestamp

스케줄링/이미지 pull/probe 실패를 찾으려면 클러스터 이벤트를 살펴봅니다.

--field-selector involvedObject.name=podX; -A; -w; --watch-only-events

kubectl get events -n shop --sort-by=.lastTimestamp -w | grep -v 'Normal'
kubectl auth can-i <verb> <resource>

현재 사용자가 무엇을 할 수 있는지 확인합니다 — RBAC 디버깅에 최고.

--as user; --as-group; -n ns; --all-namespaces

kubectl auth can-i create pods -n prod --as system:serviceaccount:team-a:deployer
kubectl wait --for=condition=Ready

리소스가 원하는 조건에 도달할 때까지 블록(CI/스크립트에서 사용).

--for condition=Ready|Available; --timeout 60s; --all --selector

kubectl wait -n shop --for=condition=Available deploy/api --timeout 120s

리소스 & 매니페스트

kubectl create cm|secret ... --from-file|--from-literal

ConfigMap / Secret 을 명령형으로 생성(`kubectl create secret generic ...`).

--from-file; --from-literal=KEY=val; --dry-run=client -o yaml

kubectl -n shop create secret generic api-creds --from-literal=API_KEY=$(cat key.txt)
kubectl create token <serviceaccount>

ServiceAccount 용 단기 토큰을 발급합니다(정적 secret 보다 권장).

--duration 24h

kubectl -n shop create token deployer --duration=12h | pbcopy
kubectl get secret <name> -o jsonpath='{.data.K}' | base64 -d

base64 로 인코딩된 secret 키를 일회성으로 디코드합니다.

kubectl -n shop get secret api-creds -o jsonpath='{.data.API_KEY}' | base64 -d

치트시트 버전 1.0.0

kubectl 1.28+ 대응