쿠버네티스 kubectl 실무 치트시트: 파드 관리와 디버깅

💡 핵심 요약 (Executive Summary)

본 가이드는 쿠버네티스 kubectl 핵심 가이드 및 실전 아키텍처의 핵심 개념, 실전 구성 명령어 및 아키텍처 베스트 프랙티스를 다룹니다. 클라우드 네이티브 및 인프라 엔지니어링 실무에 즉시 활용 가능하도록 체계적으로 정리했습니다.

📑 Table of Contents

참고자료

Commands

kubectl –help
bash
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).
Basic Commands (Beginner)
create
bash
# create 

# 파일을 이용하여 configmap create
kubectl create configmap ${cm} -n ${namespace} --from-file=${filePath}

# namespace
kubectl create ns ${namespace}

# deployment
kubectl create deployment ${deployment} --image=$image --replicas=$rscnt

# role (--resource=apiGroup(rs.apps),resource(pods),subresource(pods/status)
kubectl create role ${role} -n ${namespace} --verb=get,list,watch --resource=pods,pods/status
kubectl create role $role --verb=get --resource=pods --resource-name=$pod1
--resource-name=$pod2

# rolebinding
# USERS(Grouped), ClusterRole
kubectl create rolebinding $rolebinding --clusterrole=admin --user=user1 --user=user2 --group=group1
# SA, ROLE
kubectl create rolebinding $rolebinding --role=admin --serviceaccount=monitoring:sa-dev

# secret
kubectl create secret tls $secret --cert=$crtfile --key=$keyfile
kubectl create secret generic $secret --from-literal=$key1=$value1 --from-literal=$key2=$value2
kubectl create secret docker-registry $secret --docker-server=$service_endpoint --docker-username=$user --docker-password=$password

# cronjob 테스트를 위한 일회성 job 생성
kubectl create job $jobname --from=cronjob/$cronjobname
expose
bash
# create svc by application resources
#pod (po)
#service (svc)
#replicationcontroller (rc)
#deployment (deploy)
#replicaset (rs)

#ClusterIP로 생성
kubectl expose $resourcetype $resourcename --port=$svcport --target-port=$appPort

#NodePort로 생성 (자동지정)
kubectl expose $resourcetype $resourcename --port=$svcport --target-port=$appPort --type=NodePort
run
bash
# 단일 바이너리이미지 러닝 유지
kubectl run $POD --image=$IMAGE --command -- sleep infinity

# create pods
## 이미지 테스트용 명령 (timeout)
kubectl run $POD --image=$IMAGE --restart=Never --command -- sleep 3600

# 이미지만 명시하여 파드 러닝
#kubectl run nginx --image=nginx
kubectl run $POD --image=$IMAGE

#파드를 러닝하지 않고 yaml로 출력
kubectl run $POD --image=$IMAGE --dry-run=client -o yaml > $sample_yaml

#파드를 러닝하지 않고 yaml로 출력, command 입력(모든 옵션중 마지막에 기입)
kubectl run $POD --image=$IMAGE --dry-run=client -o yaml --command -- ${commands} > $sample_yaml
set
bash
# setting subresource

# change image for deployments
kubectl set image deploy/$deployments ${container}=${image}
Basic Commands (Intermediate)
explain
bash
#리소스, 내부 필드의 목록, 설명을 확인하기 위한 명령어, jsonPath 기준으로 찾는다.

#리소스의 설명을 제외하고 하위 필드 전체를 트리구조로 나열
kubectl explain $resource --recursive

#리소스의 lv1 필드,description 목록 나열
kubectl explain $resource

#리소스의 해당 필드 내에있는 lv2 필드, description 목록 나열
kubectl explain ${resource}.${field}
get
bash
# 목록 조회
kubectl get ${api-resource}

# 네임스페이스 명시하여 조회
kubectl get ${api-resource} -n ${namespace}

# 모든 네임스페이스 조회
kubectl get ${api-resource} -A
kubectl get ${api-resource} --all-namespaces

# 라벨 조회
kubectl get ${api-resource} --show-labels

# 형식 지정
kubectl get ${api-resource} -o wide
kubectl get ${api-resource} -o yaml
kubectl get ${api-resource} -o json
# 커스텀컬럼
kubectl get ${api-resource} -o custom-columns="$columnName":${jsonpath}
#kubectl get pods -o custom-columns="Image":.spec.containers[*].image

# 라벨 셀렉터
kubectl get ${api-resource} -l ${label}=${value}
kubectl get ${api-resource} -l ${label}
# AND
kubectl get ${api-resource} -l ${label}=${value},${label}=${value},${label}=${value}
# OR
kubectl get ${api-resource} -l 'app in (${label}=${value},${label}=${value},${label}=${value})'
kubectl get ${api-resource} --selector ${label}=${value}
kubectl get ${api-resource} --selector ${label}

# field 셀렉터
#kubectl get ${api-resource} --field-selector=status.phase=Failed
kubectl get ${api-resource} --field-selector=${field}=${value}

# 원하는 manifest/status 값 얻기 : pv명
kubectl get pvc -n grafana-loki data-portal-grafana-loki-ingester-0 -o jsonpath={.spec.volumeName}

# 위를 활용하여 pv 검색
kubectl describe pv `kubectl get pvc -n grafana-loki data-portal-grafana-loki-ingester-0 -o jsonpath={.spec.volumeName}`

# 위를 활용하여 pv 실제경로 출력
echo `kubectl get pv \`kubectl get pvc -n grafana-loki data-portal-grafana-loki-ingester-0 -o jsonpath={.spec.volumeName}\` -o jsonpath={.spec.nfs.path}`
edit
bash
# 러닝중인 resource에서 manifest.yaml 수정 (주로 deployments 등 컨트롤러나 configmap 등의 구성요소)
kubectl edit $resourcetype $resourcename
delete
bash
# field-selector
kubectl -n ${namespace} delete pods --field-selector=status.phase=Failed

# label-selector
kubectl -n ${namespace} delete pods -l k8s-app=kube-dns
Deploy Commands
rollout
bash
# deployment restart
kubectl rollout restart deployment -n ${ 네임스페이스 } ${ Deployment1 Deployment2 ... }

kubectl rollout restart deamonset
kubectl rollout restart statefulset
scale
bash
##Set a new size for a deployment, rs, rc, statefulSet

#replicas 변경
kubectl scale --replicas=$cnt rs $rs
autoscale
Cluster Management Commands
certificate
bash
#csr 승인
kubectl certificate approve $csr

#Pending인 csr을 찾아 Approved로 변경
kubectl certificate approve $(kubectl get csr | grep Pending | awk '{print $1}' | sed -z 's/[\n\r]/ /g')
cluster-info
bash
# apiserver 주소 확인
kubectl cluster-info

# Service IP Range 확인
kubectl cluster-info dump | grep -m 1 service-cluster-ip-range
#10.233.0.0/18

# Pod IP Range 확인
kubectl cluster-info dump | grep -m 1 cluster-cidr
#10.233.64.0/18
top
sql
# show top of cluster member nodes
kubectl top node

# show top of namspace member pods
kubectl top pod -n {namespace}
cordon
bash
# node를 스케줄링할 수 없도록 표기
kubectl cordon ${ NodeName }
uncordon
bash
# node를 cordon 해제
kubectl uncordon ${ NodeName }
drain
bash
# 유지 보수를 위해서 node를 준비 상태로 비움
kubectl drain $node
taint
bash
#taint 추가
kubectl taint nodes ${node} ${key}=${value}:${taint-effect}
# taint-effect:
## NoSchedule: NoSchedule 이펙트가 있는 무시되지 않은 테인트가 하나 이상 있으면 쿠버네티스는 해당 노드에 파드를 스케줄하지 않는다.
## PreferNoSchedule: NoSchedule 이펙트가 있는 무시되지 않은 테인트가 없지만 PreferNoSchedule 이펙트가 있는 무시되지 않은 테인트가 하나 이상 있으면 쿠버네티스는 파드를 노드에 스케쥴하지 않으려고 시도 한다
## NoExecute: NoExecute 이펙트가 있는 무시되지 않은 테인트가 하나 이상 있으면 파드가 노드에서 축출되고(노드에서 이미 실행 중인 경우), 노드에서 스케줄되지 않는다(아직 실행되지 않은 경우).

#taint 제거
kubectl taint nodes ${node} ${key}-
kubectl taint nodes ${node} ${key}:${taint-effect}-
kubectl taint nodes ${node} ${key}=${value}:${taint-effect}-
  • taint 활용
bash
# pipeline-agent node
  kubectl taint nodes $node dedicated=pipeline-agent:NoSchedule
  kubectl label nodes $node dedicated=pipeline-agent

  # in template.spec
  spec:
  ...
  	tolerations:
  	  - key: "dedicated"
  	    operator: "Equal"
  	    value: "pipeline-agent"
  	    effect: "NoSchedule"
  	nodeSelector:
  	  dedicated: pipeline-agent
Troubleshooting and Debugging Commands
describe
bash
# find trouble or status on events 
kubectl describe $resourcetype $resourcename
logs
bash
# 단일 컨테이너 로그 (follow)
kubectl logs -n ${namespace} ${pod} ${container} -f

# [flags]
#kubectl logs 명령어 사용시 모든 컨테이너를 log stream으로 재생시
--all-containers

#kubectl logs 명령어 사용시 5개 초과의 log streams 사용시
--max-log-requests=$num
attach
exec
bash
# container 내부 접속 : 쉘
kubectl exec -it -n ${ 네임스페이스 } ${ Pod 명 } -- bash
kubectl exec -it -n ${ 네임스페이스 } ${ Pod 명 } -- sh

# container command 실행
kubectl exec -n ${ 네임스페이스 } ${ Pod 명 } -- $commands
port-forward
bash
Examples:
  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
  kubectl port-forward pod/mypod 5000 6000

  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the
deployment
  kubectl port-forward deployment/mydeployment 5000 6000

  # Listen on port 8443 locally, forwarding to the targetPort of the service's port named "https" in a pod selected by
the service
  kubectl port-forward service/myservice 8443:https

  # Listen on port 8888 locally, forwarding to 5000 in the pod
  kubectl port-forward pod/mypod 8888:5000

  # Listen on port 8888 on all addresses, forwarding to 5000 in the pod
  kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000

  # Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
  kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000

  # Listen on a random port locally, forwarding to 5000 in the pod
  kubectl port-forward pod/mypod :5000
  
  
  # 인그레스 없이 외부 노출 (임시)
  kubectl port-forward --address 0.0.0.0 svc/$service 9090:9090 &
proxy
bash
kubectl proxy #kubeapiserver local proxy 8001
cp
bash
# pod 컨테이너 내부의 파일 외부로 복사
kubectl cp portal-grafana-9fdc9976c-fc9bq:/opt/bitnami/grafana/conf/grafana.ini ./grafana.ini
>>>
# 에러가 나지만 파일은 정상적으로 가져와짐.
Removing leading `/' from member names
<<<
# pod에서 pod으로 파일 복사는 지원하지 않음
auth
bash
#sa - $sa가 $target_ns의 secrets에 get 권한이 있는지 확인
kubectl auth can-i get secrets --as=system:serviceaccount:${sa_ns}:${sa} -n ${target_ns}

#user 
kubectl auth can-i get pods --as=${user}
debug
Advanced Commands
diff
bash
# yaml을 사용하여 resource create or update
kubectl apply -f ${yaml}

# 명령어로 더미파일 요청
kubectl apply -f - <<EOF
EOF

# kustomize dir를 사용하여 배포
kubectl apply -k ${dir}
  • 실행과 동시에 표준출력
bash
cat <<EOF | tee /dev/tty | kubeectl apply -f -
  EOF
patch
bash
## jsonPath를 사용하여 리소스 구성요소를 업데이트

# 노드를 부분적으로 업데이트
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'

# 컨테이너의 이미지를 업데이트. 병합(merge) 키이므로, spec.containers[*].name이 필요
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

# 위치 배열을 이용한 json 패치를 사용하여, 컨테이너의 이미지를 업데이트
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

# 위치 배열을 이용한 json 패치를 사용하여 livenessProbe 디플로이먼트 비활성화
kubectl patch deployment valid-deployment  --type json   -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'

# 이미 만들어진 reclaimPolicy=Delete(삭제)인 pv를 Retain(보존)으로 변경
kubectl patch pv $pv -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'

# 위치 배열에 새 요소 추가
kubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'

# 디플로이먼트의 scale 서브리소스를 패치하여 레플리카 수 업데이트
kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}'
  • Terminating ns 모두 제거
bash
#metadata
  for ns in $(kubectl get ns --no-headers | awk '/Terminating/ {print $1}'); do
    echo "Force deleting namespace: $ns"
  	kubectl patch ns $ns --type='merge' -p='{"metadata": {"finalizers": []}}'
  done
replace
bash
# 삭제 후 yaml로 생성
kubectl replace --force -f $yaml
wait
kustomize
Settings Commands
label
bash
# Update pod 'foo' with the label 'unhealthy' and the value 'true'
kubectl label pods foo unhealthy=true

# Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value
kubectl label --overwrite pods foo status=unhealthy

# Update all pods in the namespace
kubectl label pods --all status=unhealthy

# Update a pod identified by the type and name in "pod.json"
kubectl label -f pod.json status=unhealthy

# Update pod 'foo' only if the resource is unchanged from version 1
kubectl label pods foo status=unhealthy --resource-version=1

# Update pod 'foo' by removing a label named 'bar' if it exists
# Does not require the --overwrite flag
kubectl label pods foo bar-
annotate
completion
bash
## bash
cat <<EOF >> ~/.bashrc
source <(kubectl completion bash)
# source <(kubeadm completion bash)
alias k=kubectl
complete -F __start_kubectl k
EOF
source ~/.bashrc

## zsh
cat <<EOF >> ~/.zshrc
source <(kubectl completion zsh)
alias k=kubectl
if type kubectl &>/dev/null; then
  source <(kubectl completion zsh)
  compdef k=kubectl
fi
EOF
source ~/.zshrc
Other Commands
bash
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
alpha
bash
#Commands for features in alpha
api-resource
bash
kubectl api-resources

kubectl api-resources --namespaced=true
#role, rolebinding

kubectl api-resources --namespaced=false
#clusterrole, clusterrolebinding
api-versions
bash
# Print the supported API versions on the server, in the form of "group/version"
config
bash
# kubeconfig 조회
kubectl config view

## [Context]
# context 조회
kubectl config get-contexts
# context 삭제
kubectl config delete-context ${context}
# context rename
kubectl config rename-context ${asis-context} ${tobe-context}

# context 추가
kubectl config set-context ${new-context} --cluster=${new-cluster} --user=${user}

# current-context 변경
kubectl config use-context ${cluster}

# current-context 조회
kubectl config current-context
# current-context default namespace 변경
kubectl config set-context --current --namespace={ 네임스페이스 }

## [Cluster]
# cluster 조회
kubectl config get-clusters

## [User]
# 사용자 조회
kubectl config get-users

## [Credential]
kubectl config set-credentials ${service-account} --token=${service-account-token}
kubectl config scraped
bash
current-context  -- Display the current-context
delete-cluster   -- Delete the specified cluster from the kubeconfig
delete-context   -- Delete the specified context from the kubeconfig
delete-user      -- Delete the specified user from the kubeconfig
get-clusters     -- Display clusters defined in the kubeconfig
get-contexts     -- Describe one or many contexts
get-users        -- Display users defined in the kubeconfig
rename-context   -- Rename a context from the kubeconfig file
set              -- Set an individual value in a kubeconfig file
set-cluster      -- Set a cluster entry in kubeconfig
set-context      -- Set a context entry in kubeconfig
set-credentials  -- Set a user entry in kubeconfig
unset            -- Unset an individual value in a kubeconfig file
use-context      -- Set the current-context in a kubeconfig file
view             -- Display merged kubeconfig settings or a specified kubeconfig file
plugin
bash
## Provides utilities for interacting with plugins
version
bash
## version 확인
kubectl version

flags

bash
## selector
#filed-selector
--filed-selector
#label-selector
-l
#namespaces
-n
#all-namespaces
-A

#kubectl logs 명령어 사용시 모든 컨테이너를 log stream으로 재생시
--all-containers
#kubectl logs 명령어 사용시 5개 초과의 log streams 사용시
--max-log-requests=$num

## global
#rollout history에 기록 (Deployments, StatefulSet, DaemonSet)
--records

## view
#테이블뷰의 헤더행 제거
--no-headers
#라벨 조회
--show-labels
-o, —output
bash
-o custom-columns
-o custom-columns-file
-o go-template
-o go-template-file

#json 출력
-o json
#json 일부 출력
-o=jsonpath='{@}'
-o=jsonpath='{.items[0]}'
-o=jsonpath='{.items[0].metadata.name}'
-o=jsonpath="{.items[*]['metadata.name', 'status.capacity']}"
-o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
-o=jsonpath="{.data.alertmanager-overview\.json}"

-o jsonpath-as-json
-o jsonpath-file

#이름만 출력
-o name

-o template
-o templatefile
#상세정보 포함
-o wide
#yaml 출력
-o yaml

features

Upgrading ~/.bashrc
  • Completion:

    • completion
  • 자동완성 래퍼

bash
_k_wrap() {
    local resource=()
    local args=()

    # ---- 옵션 파싱 ----
    while [[ $# -gt 0 ]]; do
      case "$1" in
        --resource)
          shift
          IFS=' ' read -r -a resource <<< "$1"
          shift
          ;;
        --resource=*)
          IFS=' ' read -r -a resource <<< "${1#*=}"
          shift
          ;;
        --)
          shift
          args=("$@")
          break
          ;;
        *)
          echo "unknown option: $1" >&2
          return 1
          ;;
      esac
    done

    # ---- args 내에서 "--" 분리 ----
    local pre=()
    local post=()
    local seen_ddash=0

    for arg in "${args[@]}"; do
      if [[ "$arg" == "--" && $seen_ddash -eq 0 ]]; then
        seen_ddash=1
        continue
      fi

      if (( seen_ddash )); then
        post+=("$arg")
      else
        pre+=("$arg")
      fi
    done

    # ---- kubectl 실행 ----
    if (( seen_ddash )) && ((${#post[@]} > 0)); then
      kubectl "${pre[@]}" "${resource[@]}" -- "${post[@]}"
    else
      kubectl "${pre[@]}" "${resource[@]}"
    fi
  }
  • 자동완성 구현
bash
export dev_kubeconfig="/workspace/cmp-helm/_gitops/.tmp/.dev.kubeconfig"
  export stg_kubeconfig="/workspace/cmp-helm/_gitops/.tmp/.stg.kubeconfig"
  function kd() {
    _k_wrap --resource="--kubeconfig $dev_kubeconfig" -- "$@"
  }
  function ks() {
    _k_wrap --resource="--kubeconfig $stg_kubeconfig" -- "$@"
  }
  function k_argow() {
    _k_wrap --resource="-n deploy-system deploy/argo-workflows-server" -- "$@"
  }
  function k_vault() {
    _k_wrap --resource="-n portal-system sts/vault" -- "$@"
  }
verbose flag (Client Version: v1.31.0)
bash
# Config loaded from file, apiserver 요청본문 확인
k get pods --v=6

# Req Header, Res Status 확인
k get pods --v=7

# Res Header, Res Body(Truncated) 확인
k get pods --v=8

# Res Body(Full) 확인
k get pods --v=9

# 좀 더 자세한 정보 (returning cashed discovery info 등)
k get pods --v=10
특수 조회
k8s 리소스를 즉시 실행가능한 형태로 백업
bash
#for 1 resource
specified=(-n management-system deploy/cert-manager)
kubectl get ${specified[@]} -o yaml | \
    yq 'del(.metadata.uid, 
        .metadata.resourceVersion, 
        .metadata.creationTimestamp, 
        .metadata.managedFields, 
        .metadata.annotations."kubectl.kubernetes.io/last-applied-configuration", 
        .metadata.generation, 
        .status)'

#for list
specified=(-n management-system deploy)
kubectl get ${specified[@]} -o yaml | \
    yq 'del(.items[].metadata.uid, 
        .items[].metadata.resourceVersion, 
        .items[].metadata.creationTimestamp, 
        .items[].metadata.managedFields, 
        .items[].metadata.annotations."kubectl.kubernetes.io/last-applied-configuration", 
        .items[].metadata.generation, 
        .items[].status)'
tls 파일화
bash
kubectl get secret -n cicd harbor.fredric.playground.cld-tls -o jsonpath="{.data.ca\.crt}" | base64 -d > ca.pem
kubectl get secret -n cicd harbor.fredric.playground.cld-tls -o jsonpath="{.data.tls\.crt}" | base64 -d > cert.pem
kubectl get secret -n cicd harbor.fredric.playground.cld-tls -o jsonpath="{.data.tls\.key}" | base64 -d > key.pem
get-jsonpath Samples
bash
# Pod 내의 모든 컨테이너의 커맨드 조회
kubectl get pods $pod -n $namespace -o jsonpath='{.spec.containers[*].command}'
모든 컨테이너 조회
bash
#container 조회 후 중복 counting
kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c

# custom columns
kubectl get pods -A -o=custom-columns="Image:{.spec.containers[*].image}"
Default ServiceAccount Token 확인
bash
kubectl get secret $(kubectl get sa default -ojsonpath="{.secrets[0].name}") -ojsonpath="{.data.token}" | base64 -d
자원할당량 확인
bash
kubectl get po -o custom-columns="Name:metadata.name,CPU-Requet:spec.containers[].resources.requests.cpu,CPU-limit:spec.containers[].resources.limits.cpu,MEM-Request:spec.containers[].resources.requests.memory,MEM-limit:spec.containers[].resources.limits.memory"
Export NodePort
bash
export NODE_PORT=$(kubectl get --namespace jenkins-Enterprise Cloud -o jsonpath="{.spec.ports[0].nodePort}" services jenkins)
export NODE_IP=$(kubectl get nodes --namespace jenkins-Enterprise Cloud -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT/login
CIDR 확인
bash
# Service IP Range 확인
kubectl cluster-info dump | grep -m 1 service-cluster-ip-range
#10.233.0.0/18

# Pod IP Range 확인
kubectl cluster-info dump | grep -m 1 cluster-cidr
#10.233.64.0/18
api-resource, API 그룹으로 조회
bash
factor=istio
kubectl get $(kubectl api-resources -o name | grep $factor | sed -z 's/[\n\r]/,/g' | sed 's/.$//g') -A
Ingress 전체를 /etc/hosts 입력용으로 조회
bash
kubectl get ing -A --no-headers | awk '
{
    addr = $5
    host = $4
    hosts[addr] = (hosts[addr] ? hosts[addr] " " host : host)
}
END {
    for (a in hosts) {
        print a, hosts[a]
    }
}' | sort
Update
지워지지 않는 리소스 강제 삭제
bash
resource_type=pv
resource_name=browser-file
NS=portal
kubectl get -n $NS $resource_type $resource_name -o name | xargs -I {} kubectl patch {} -n $NS -p '{"metadata":{"finalizers":[]}}' --type=merge
찾아 지우기
bash
# field-selector
kubectl -n ${namespace} delete pods --field-selector=status.phase=Failed

# label-selector
kubectl -n ${namespace} delete pods -l k8s-app=kube-dns
Kubeconfig
Service Account 기간제한 없는 토큰 생성
bash
#kubectl create clusterrole cluster-admin-role --verb=* --resource=*
#kubectl edit clusterrole cluster-admin-role #apigroup=*로 변경
ns=deploy-system
sa=deploy-admin
kubectl apply -f - <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: ${sa}-role
rules:
- apiGroups:
  - '*'
  resources:
  - '*'
  verbs:
  - '*'
EOF
kubectl create sa $sa -n $ns
kubectl create clusterrolebinding ${sa}-rolebinding --clusterrole ${sa}-role --serviceaccount ${ns}:${sa}
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: ${sa}-token
  namespace: $ns
  annotations:
    kubernetes.io/service-account.name: $sa
type: kubernetes.io/service-account-token
EOF
Shell로 SA 생성
bash
#!/bin/bash
# `./generate_kubeconfig.sh dev 10.0.X.X mypasswd 2222 > .my.kubeconfig`
ns=default
sa=cmp-admin

# SSH 명령을 단 한번 호출하는 버전이 가장 안정적임
remote_script=$(cat <<EOF
# 1. ClusterRole 생성
kubectl apply -f - <<'E1'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: ${sa}-role
rules:
- apiGroups:
  - '*'
  resources:
  - '*'
  verbs:
  - '*'
E1

# 2. ServiceAccount 생성
kubectl create sa ${sa} -n ${ns} --dry-run=client -o yaml | kubectl apply -f -

# 3. ClusterRoleBinding 생성
kubectl create clusterrolebinding ${sa}-rolebinding \
  --clusterrole ${sa}-role \
  --serviceaccount ${ns}:${sa} \
  --dry-run=client -o yaml | kubectl apply -f -

# 4. Token Secret 생성
kubectl apply -f - <<'E2'
apiVersion: v1
kind: Secret
metadata:
  name: ${sa}-token
  namespace: ${ns}
  annotations:
    kubernetes.io/service-account.name: ${sa}
type: kubernetes.io/service-account-token
E2
EOF
)

remote_script2=$(cat <<EOF
# 5. token 값 출력
kubectl get secret ${sa}-token -n ${ns} -o jsonpath="{.data.token}"
EOF
)

printf "%s" "$remote_script" | /bin/bash -s > /dev/tty
token_b64=$(printf "%s" "$remote_script2" | /bin/bash -s)
printf "%s" "$token_b64" | base64 -d
CLI로 kubeconfig 등록
  • insecure
bash
context=
  cluster_endpoint=
  sa_token=
  kubectl config set-cluster $context \
      --server=$cluster_endpoint \
      --insecure-skip-tls-verify=true
  kubectl config set-credentials $context \
      --token=
  kubectl config set-context my-prod-context \
      --cluster=prod-cluster \
      --user=prod-user \
      --namespace=production
SSH로 Kubeconfig 생성
bash
#!/bin/bash
# `./generate_kubeconfig.sh dev 10.0.X.X mypasswd 2222 > .my.kubeconfig`
contextName=$1
hostname=$2
ssh_port=${3:-22}
dest_ip=$(dig $hostname +short)
endpoint="https://$dest_ip:6443"
ns=default
sa=tester

# ─────────────────────────────────────────────
# 원격 스크립트 정의
# ─────────────────────────────────────────────
remote_script=$(cat <<EOF
# 1. ClusterRole 생성
kubectl apply -f - <<'E1'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: ${sa}-role
rules:
- apiGroups:
  - '*'
  resources:
  - '*'
  verbs:
  - '*'
E1

# 2. ServiceAccount 생성
kubectl create sa ${sa} -n ${ns} --dry-run=client -o yaml | kubectl apply -f -

# 3. ClusterRoleBinding 생성
kubectl create clusterrolebinding ${sa}-rolebinding \
  --clusterrole ${sa}-role \
  --serviceaccount ${ns}:${sa} \
  --dry-run=client -o yaml | kubectl apply -f -

# 4. Token Secret 생성
kubectl apply -f - <<'E2'
apiVersion: v1
kind: Secret
metadata:
  name: ${sa}-token
  namespace: ${ns}
  annotations:
    kubernetes.io/service-account.name: ${sa}
type: kubernetes.io/service-account-token
E2
EOF
)

remote_script2=$(cat <<EOF
# 5. token 값 출력
kubectl get secret ${sa}-token -n ${ns} -o jsonpath="{.data.token}"
EOF
)

# ─────────────────────────────────────────────
# 원격에서 스크립트 실행 및 token 가져오기
# ─────────────────────────────────────────────
printf "%s" "$remote_script" | ssh -p$ssh_port root@$hostname "/bin/bash -s" > /dev/tty
token_b64=$(printf "%s" "$remote_script2" | ssh -p$ssh_port root@$hostname "/bin/bash -s")

# Base64 → RAW token
serviceToken=$(printf "%s" "$token_b64" | base64 -d)

# ─────────────────────────────────────────────
# 로컬 kubeconfig 생성
# ─────────────────────────────────────────────
cat <<EOF
apiVersion: v1
kind: Config
preferences: {}
current-context: ${contextName}
clusters:
  - name: ${contextName}
    cluster:
      server: ${endpoint}
      insecure-skip-tls-verify: true
contexts:
  - name: ${contextName}
    context:
      cluster: ${contextName}
      user: ${contextName}
users:
  - name: ${contextName}
    user:
      token: ${serviceToken}
EOF
krew
설치
shell
# krew: plugin-manager 설치
# Krew 설치
(
  set -x; cd "$(mktemp -d)" &&
  OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
  ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
  KREW="krew-${OS}_${ARCH}" &&
  curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz" &&
  tar zxvf "${KREW}.tar.gz" &&
  ./"${KREW}" install krew
)

# .bashrc or .zshrc에 추가
sudo bash -c "echo 'export PATH=\"\${KREW_ROOT:-\$HOME/.krew}/bin:\$PATH\"'" >> /etc/profile

# shell 재시작
source /etc/profile
ns
bash
# ns 설치: 디폴트 네임스페이스 변경
kubectl krew install ns
kubectl ns { 네임스페이스 }
images
shell
# 이미지정보
krew install images
kubectl images -A
Automation Support
Node IP 조회
bash
# 현재 노드 단일
k get nodes $(hostname) -o jsonpath='{.status.addresses}' | \
  jq -r '.[] | select(.type == "InternalIP") | .address'

# all-members
k get nodes -o jsonpath='{.items[*].status.addresses}' | \
  jq -r '.[] | select(.type == "InternalIP") | .address'

# control-plain
k get nodes -l node-role.kubernetes.io/control-plane \
  -o jsonpath='{.items[*].status.addresses}' | \
  jq -r '.[] | select(.type == "InternalIP") | .address'

# worker
k get nodes --selector='!node-role.kubernetes.io/control-plane,!node-role.kubernetes.io/master' \
  -o jsonpath='{.items[*].status.addresses}' | \
  jq -r '.[] | select(.type == "InternalIP") | .address'
ETC
kube-apiserver swagger 노출
bash
kubectl get --raw /openapi/v2 > k8s-openapi-v2.json
kubectl apply -f - << EOF
apiVersion: v1
kind: Pod
metadata:
  name: kube-swagger
  labels:
    app: kube-swagger
spec:
  containers:
  - name: kube-swagger
    image: swaggerapi/swagger-ui
    ports:
    - containerPort: 8080
    volumeMounts:
    - name: swagger-volume
      mountPath: /app/swagger.json
      readOnly: true
  volumes:
  - name: swagger-volume
    hostPath:
      path: $(pwd)/k8s-openapi-v2.jso
      type: File
EOF
kubectl expose pod kube-swagger --type=NodePort
kube-apiserver swagger 노출
bash
kubectl get --raw /openapi/v2 > k8s-openapi-v2.json
kubectl apply -f - << EOF
apiVersion: v1
kind: Pod
metadata:
  name: kube-swagger
  labels:
    app: kube-swagger
spec:
  containers:
  - name: kube-swagger
    image: swaggerapi/swagger-ui
    ports:
    - containerPort: 8080
    volumeMounts:
    - name: swagger-volume
      mountPath: /app/swagger.json
      readOnly: true
  volumes:
  - name: swagger-volume
    hostPath:
      path: $(pwd)/k8s-openapi-v2.jso
      type: File
EOF
kubectl expose pod kube-swagger --type=NodePort
yaml 생성 sample (문제풀이)
bash
#a: pod
kubectl run nginx-pod --image=nginx:alpine --dry-run=client -o yaml> a.yaml
#b: pod
kubectl run redis --image=redis:alpine -l tier=db --dry-run=client -o yaml > b.yaml
#c: service
kubectl create svc clusterip redis-service --tcp=6379 --dry-run=client -o yaml > c.yaml
#d: deploy
kubectl create deploy webapp --image=kodekloud/webapp-color -r 3 -o yaml --dry-run=client > d.yaml
#e: pod
kubectl run custom-nginx --image=nginx --port=8080 --dry-run=client -o yaml > e.yaml
#f: ns, deploy
kubectl create ns dev-ns --dry-run=client -o yaml > f.yaml
echo "---" >> f.yaml
kubectl create deploy redis-deploy -n dev-ns --image=redis -r 2 --dry-run=client -o yaml >> f.yaml
#g: pod, service
kubectl run httpd --image=httpd:alpine --port=80 -l app=httpd --dry-run=client -o yaml > g.yaml
echo "---" >> g.yaml
kubectl create svc clusterip httpd --tcp=80:80 --dry-run=client -o yaml >> g.yaml
#g2: expose=true 옵션으로 자동 노출(svc 정의)
kubectl run httpd --image=httpd:alpine --port=80 --expose=true --dry-run=client -o yaml > g2.yaml
# cronjob 테스트를 위한 일회성 job 생성
bash
kubectl create job $jobname --from=cronjob/$cronjobname

이 포스팅은 쿠팡 파트너스 및 알리익스프레스 어필리에이트 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

이 포스팅은 쿠팡 파트너스 및 알리익스프레스 어필리에이트 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *