kubectl 기본
클러스터 정보
kubectl cluster-info kubectl get nodes kubectl config current-context kubectl config use-context my-cluster
필수 명령어
kubectl get <resource>리소스 목록 조회
kubectl describe <resource> <name>리소스 상세 정보
kubectl create -f file.yaml파일로 리소스 생성
kubectl apply -f file.yaml리소스 생성 또는 업데이트
kubectl delete -f file.yaml파일로 리소스 삭제
kubectl edit <resource> <name>리소스 인플레이스 편집
kubectl api-resources모든 리소스 유형 목록
출력 형식
-o wide추가 컬럼 표시 (IP, 노드)
-o yaml전체 YAML 출력
-o json전체 JSON 출력
-o jsonpath='{.spec}'특정 필드 추출
--sort-by=.metadata.name필드 기준 정렬
파드
파드 작업
kubectl get pods kubectl get pods -A # all namespaces kubectl run nginx --image=nginx # quick pod kubectl delete pod nginx
파드 YAML
apiVersion: v1 kind: Pod metadata: name: myapp labels: { app: myapp } spec: containers: - name: app image: nginx:1.27 ports: - containerPort: 80
파드 상태값
Running모든 컨테이너 시작됨
Pending스케줄링 또는 이미지 풀 대기 중
CrashLoopBackOff컨테이너가 계속 충돌하고 재시작
ImagePullBackOff컨테이너 이미지를 가져올 수 없음
Completed실행 완료 (Job)
디플로이먼트
디플로이먼트 YAML
apiVersion: apps/v1 kind: Deployment metadata: name: web spec: replicas: 3 selector: matchLabels: { app: web } template: metadata: labels: { app: web } spec: containers: - name: web image: nginx:1.27 ports: - containerPort: 80
디플로이먼트 명령어
kubectl get deploy디플로이먼트 목록
kubectl scale deploy web --replicas=5레플리카 수 조정
kubectl set image deploy/web web=nginx:1.28이미지 업데이트 (롤링)
kubectl rollout status deploy/web롤아웃 진행 상황 확인
kubectl rollout undo deploy/web이전 리비전으로 롤백
kubectl rollout history deploy/web리비전 히스토리 조회
서비스
서비스 유형
ClusterIP클러스터 내부 전용 (기본값)
NodePort각 노드 IP의 정적 포트로 외부 노출
LoadBalancer외부 로드 밸런서 (클라우드)
ExternalName외부 서비스로의 DNS 별칭
서비스 YAML
apiVersion: v1 kind: Service metadata: name: web-svc spec: type: ClusterIP selector: { app: web } ports: - port: 80 targetPort: 80
빠른 노출
kubectl expose deploy web --port=80 --type=ClusterIP kubectl expose deploy web --port=80 --type=NodePort kubectl get svc
ConfigMap 및 Secret
ConfigMap
kubectl create configmap app-cfg \ --from-literal=DB_HOST=db.example.com \ --from-file=config.ini
Secret
kubectl create secret generic db-creds \ --from-literal=username=admin \ --from-literal=password=s3cret
파드에서 사용
# As environment variables envFrom: - configMapRef: { name: app-cfg } - secretRef: { name: db-creds } # As volume mount volumes: - name: cfg configMap: { name: app-cfg }
명령어
kubectl get cmConfigMap 목록
kubectl get secretSecret 목록
kubectl describe cm app-cfgConfigMap 데이터 표시
kubectl get secret db-creds -o yamlSecret 표시 (base64 인코딩)
네임스페이스
네임스페이스 명령어
kubectl get ns네임스페이스 목록
kubectl create ns staging네임스페이스 생성
kubectl delete ns staging네임스페이스 및 모든 리소스 삭제
kubectl get pods -n staging네임스페이스의 파드 목록
kubectl get pods -A전체 네임스페이스의 파드 목록
기본 네임스페이스 설정
kubectl config set-context --current \ --namespace=staging
볼륨
PersistentVolumeClaim
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: data-pvc spec: accessModes: [ReadWriteOnce] resources: requests: { storage: 10Gi }
파드에 마운트
volumes: - name: data persistentVolumeClaim: claimName: data-pvc containers: - volumeMounts: - name: data mountPath: /app/data
볼륨 유형
emptyDir임시 디렉터리, 파드 삭제 시 함께 삭제
hostPath호스트 파일시스템 경로 마운트
persistentVolumeClaim영구 스토리지 (PVC)
configMapConfigMap을 파일로 마운트
secretSecret을 파일로 마운트
인그레스
인그레스 YAML
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: web-ingress spec: rules: - host: app.example.com http: paths: - path: / pathType: Prefix backend: service: name: web-svc port: { number: 80 }
인그레스 참고
Ingress Controller필수 (nginx-ingress, traefik 등)
pathType: PrefixURL 접두사 매칭
pathType: Exact정확한 URL 경로 매칭
TLSSecret 이름으로 tls: 섹션 추가
디버깅
진단 명령어
kubectl logs <pod>컨테이너 stdout/stderr
kubectl logs <pod> -c <ctr>특정 컨테이너 로그
kubectl logs <pod> --previous충돌한 컨테이너의 로그
kubectl describe pod <pod>이벤트, 조건, 상태
kubectl exec -it <pod> -- sh컨테이너에 쉘 접속
kubectl port-forward <pod> 8080:80로컬 포트를 파드로 포워딩
kubectl top podsCPU/메모리 사용량 (metrics-server 필요)
kubectl get events --sort-by=.lastTimestamp클러스터 이벤트 타임라인
디버그 파드
kubectl run debug --rm -it --image=busybox -- sh # or attach ephemeral container kubectl debug -it --image=busybox
주요 패턴
레이블 및 셀렉터
kubectl get pods -l app=web kubectl get pods -l 'env in (prod,staging)' kubectl label pod myapp env=prod
리소스 제한
resources: requests: { cpu: 100m, memory: 128Mi } limits: { cpu: 500m, memory: 256Mi }
활성 및 준비 프로브
livenessProbe: httpGet: { path: /healthz, port: 8080 } initialDelaySeconds: 5 periodSeconds: 10 readinessProbe: httpGet: { path: /ready, port: 8080 }
빠른 레시피
Dry runkubectl apply -f file.yaml --dry-run=client
Generate YAMLkubectl create deploy web --image=nginx --dry-run=client -o yaml
Watchkubectl get pods -w
Copy fileskubectl cp file.txt pod:/tmp/
Restart deploykubectl rollout restart deploy/web