시작하기
kubectl 기본
kubectl이 Kubernetes의 CLI입니다. get이 리소스를 나열하고, create가 새로 만들며, expose가 서비스를 만들고, scale이 복제본 수를 바꿉니다. describe가 리소스에 대한 상세 정보를 줍니다.
# cluster info
kubectl cluster-info
# list nodes
kubectl get nodes
# list pods (all namespaces)
kubectl get pods --all-namespaces
# create a deployment
kubectl create deployment nginx --image=nginx
# expose deployment as service
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# scale deployment
kubectl scale deployment nginx --replicas=3
# get detailed info
kubectl describe pod <pod-name>
# view logs
kubectl logs <pod-name>출력 포매팅
-o flag가 출력을 제어합니다. yaml/json이 전체 리소스 스펙을 보여주고, jsonpath와 custom-columns가 스크립팅용 특정 필드를 추출합니다. -w가 실시간 변화를 감시합니다. 스크립트에서는 열 이름을 버리려 --no-headers를 쓰세요.
# wide format (more columns)
kubectl get pods -o wide
# YAML output
kubectl get pod nginx -o yaml
# JSON output
kubectl get pod nginx -o json
# jsonpath (extract specific fields)
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase
# show labels
kubectl get pods --show-labels
# watch for changes
kubectl get pods -w컨텍스트 & 설정
컨텍스트가 클러스터 주소, 사용자 자격 증명, 네임스페이스를 묶습니다. kubeconfig 파일(기본 ~/.kube/config)이 이를 저장합니다. 여러 파일을 KUBECONFIG 환경 변수로 결합해 많은 클러 스터를 관리할 수 있습니다.
# view current config
kubectl config view
# list contexts
kubectl config get-contexts
# switch context
kubectl config use-context my-cluster
# set default namespace for current context
kubectl config set-context --current --namespace=dev
# show current context
kubectl config current-context
# KUBECONFIG with multiple files
export KUBECONFIG=~/.kube/config:~/.kube/prod-configexplain & API 리소스
api-resources가 클러스터가 지원하는 것을 나열합니다. explain이 어떤 리소스든 OpenAPI 스키마를 보여줍니다 — 터미널을 떠나지 않고 YAML을 쓰는 데 매우 유용합니다. 중첩 구조 전체를 덤프하려 --recursive를 쓰세요.
# list all resource types
kubectl api-resources
# list namespaced vs cluster-scoped
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
# explain a resource's fields
kubectl explain pod
kubectl explain pod.spec.containers
kubectl explain deployment.spec.strategy
# explain with recursion (all nested fields)
kubectl explain pod --recursive
# include description
kubectl explain pod.spec.containers.resources --api-version=apps/v1드라이런 & YAML 생성
--dry-run=client -o yaml이 명령형 커맨드에서 매니페스트를 뽑아내는 표준 방법입니다. --dry-run=server는 저장 없이 실제 apiserver(admission 웹훅, 스키마)에 대해 검증합니다. 선언적 YAML 부트스트래핑에 좋습니다.
# generate YAML without applying
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml
# pipe generated YAML straight to a file
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx.yaml
# apply the generated manifest
kubectl apply -f nginx.yaml
# dry-run against the server (validates with apiserver)
kubectl apply -f nginx.yaml --dry-run=server
# generate a service from a deployment
kubectl create service clusterip my-svc --tcp=80:80 --dry-run=client -o yaml도움말 & 자동완성
모든 kubectl 커맨드가 예제와 함께 --help를 지원합니다. 셸 자동완성이 엄청난 타이핑을 아끼고 서브커맨드를 노출합니다. k=kubectl 별칭이 실무자들 사이에 거의 만능입니다 — 최고 경험을 위해 자동완성과 결합하세요.
# top-level help
kubectl --help
# subcommand help
kubectl create --help
kubectl explain --help
# generate bash completion
kubectl completion bash > /etc/bash_completion.d/kubectl
# zsh completion
source <(kubectl completion zsh)
# alias k=kubectl with completion
alias k=kubectl
complete -o default -F __start_kubectl k
# shorthand: kubectl -> k
echo 'alias k=kubectl' >> ~/.bashrcPod
Pod 매니페스트
Pod가 가장 작은 배포 단위이며, 네트워크와 스토리지를 공유하는 하나 이상의 컨테이너를 담습니다. pod 안의 컨테이너는 항상 같은 노드에 함께 스케줄됩니다. pod를 직접 만드는 일은 드뭅니다 — 대신 Deployment나 Job을 쓰세요.
apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi
restartPolicy: Always다중 컨테이너 Pod (사이드카)
다중 컨테이너 pod는 네트워크(같은 IP, 포트 공간)와 볼륨을 공유합니다. 흔한 패턴: sidecar(헬퍼), adapter(출력 변환), ambassador(프록시). 공유 emptyDir 볼륨으로 사이드카가 메인 컨테이너가 쓰는 로그를 읽을 수 있습니다.
apiVersion: v1
kind: Pod
metadata:
name: web-with-logs
spec:
containers:
- name: app
image: nginx
volumeMounts:
- name: shared-logs
mountPath: /var/log/nginx
- name: log-shipper
image: busybox
command: ["sh", "-c", "tail -f /var/log/nginx/access.log"]
volumeMounts:
- name: shared-logs
mountPath: /var/log/nginx
readOnly: true
volumes:
- name: shared-logs
emptyDir: {}Pod 라이프사이클 & 페이즈
pod의 페이즈는 높은 수준입니다(Pending, Running, Succeeded, Failed). 컨테이너 상태(Waiting/Running/Terminated)가 실제 세부를 줍니다 — 예: CrashLoopBackOff는 컨테이너가 계속 종료된다는 뜻. 진단에는 재시작 횟수와 이벤트를 확인하세요.
# pod phases: Pending | Running | Succeeded | Failed | Unknown
kubectl get pod nginx
# show status including container states
kubectl get pod nginx -o jsonpath='{.status}'
# container states: Waiting | Running | Terminated
kubectl describe pod nginx
# common Waiting reasons: ImagePullBackOff, CrashLoopBackOff, CreateContainerConfigError
kubectl get pods --field-selector=status.phase=Pending
# restart count reveals crash loops
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[*].restartCount}'Pod 상태 & 이벤트
이벤트는 리소스의 감사 로그입니다 — 스케줄링, 이미지 가져오기, 가져오기 오류, 라이브니스 실패. 이들은 만료됩니다(기본 약 1시간)이므로 디버깅 중에 캡처하세요. describe가 이벤트를 리소스 스펙과 묶어 빠른 분류를 돕습니다.
# full describe (includes Events at the bottom)
kubectl describe pod nginx
# list cluster events sorted by time
kubectl get events --sort-by=.lastTimestamp
# events for a specific namespace
kubectl get events -n default
# watch events live
kubectl get events -w
# filter events by type
kubectl get events --field-selector type=Warning
# events for a specific pod
kubectl get events --field-selector involvedObject.name=nginxexec & port-forward
exec이 컨테이너 안에서 명령을 실행합니다; -it이 셸용 TTY를 할당합니다. port-forward가 pod/서비스에 노출 없이 로컬 포트를 터널링합니다 — 노트북에서 데이터베이스나 웹 UI를 디버깅하는 데 필수입니다.
# open an interactive shell
kubectl exec -it nginx -- sh
# run a one-off command
kubectl exec nginx -- ls /etc/nginx
# specify container in a multi-container pod
kubectl exec -it web-with-logs -c log-shipper -- sh
# forward a local port to a pod port
kubectl port-forward pod/nginx 8080:80
# forward to a service / deployment
kubectl port-forward svc/nginx 8080:80
kubectl port-forward deployment/nginx 8080:80
# forward to a random local port
kubectl port-forward pod/nginx :80삭제 & 강제
Deployment/StatefulSet이 제어하는 pod를 삭제하면 즉시 교체됩니다. --force --grace-period=0은 TERM 시그널 유예 기간을 건너뛰어 오래된 리소스를 남길 수 있습니다 — 아껴 쓰세요. 멈춘 terminating pod에는 보통 파이널라이저 제거가 필요합니다.
# delete a pod (controller will recreate it)
kubectl delete pod nginx
# force delete immediately (bypasses graceful shutdown)
kubectl delete pod nginx --grace-period=0 --force
# delete by label
kubectl delete pods -l app=nginx
# delete all pods in a namespace
kubectl delete pods --all -n default
# delete a pod and wait for it to be gone
kubectl delete pod nginx --wait
# delete with a timeout
kubectl delete pod nginx --timeout=30sDeployment
Deployment 매니페스트
Deployment가 ReplicaSet을 관리하며 선언적 롤링 업데이트와 롤백을 제공합니다. spec.selector는 spec.template.metadata.labels와 일치해야 합니다. 템플릿이 롤아웃될 pod 스펙을 정의합니다.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80롤링 업데이트 전략
RollingUpdate(기본값)가 무중단을 위해 pod를 점진 교체합니다. maxSurge/maxUnavailable이 롤아웃 속도와 가용성을 제어합니다. Recreate는 새 것을 만들기 전에 모든 pod를 죽입니다 — 앱이 두 버전을 동시에 못 실행할 때 씁니다(예: 단일 볼륨 작성자).
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 10
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25% # extra pods above replicas during update
maxUnavailable: 25% # pods allowed down during update
# alternative: recreate (kills all, then starts new)
# strategy:
# type: Recreate
selector:
matchLabels:
app: nginx
template:롤백
pod 템플릿의 변경마다 ReplicaSet 리비전이 만들어집니다. undo가 트래픽을 이전 ReplicaSet으로 되돌립니다. pause로 카나리 증분 사이에 여러 수정을 할 수 있습니다. 변경 사유 추적에는 --record(폐기됨)나 어노테이션을 쓰세요.
# view rollout history
kubectl rollout history deployment/nginx
# see details of a specific revision
kubectl rollout history deployment/nginx --revision=2
# undo to the previous revision
kubectl rollout undo deployment/nginx
# undo to a specific revision
kubectl rollout undo deployment/nginx --to-revision=2
# pause/resume a rollout (for canary pauses)
kubectl rollout pause deployment/nginx
kubectl rollout resume deployment/nginx
# check rollout status
kubectl rollout status deployment/nginx스케일 & HPA
HPA가 CPU/메모리나 커스텀 메트릭으로 복제본을 스케일합니다. CPU/메모리에는 metrics-server가 필요합니다. minReplicas와 maxReplicas가 스케일링을 제한합니다. v2 API는 여러 메트릭과 동작(스케일다운 안정화)을 지원합니다.
# scale manually
kubectl scale deployment/nginx --replicas=5
# horizontal pod autoscaler (CPU target)
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
# list HPA
kubectl get hpa
# HPA manifest (v2 with custom metrics)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: nginx
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 80이미지 업데이트 & 재시작
set image가 새 ReplicaSet과 롤링 업데이트를 트리거합니다. rollout restart가 최신 이미지를 당기거나 설정을 새 로 고치는 가장 깔끔한 방법입니다 — 같은 스펙의 새 ReplicaSet을 만듭니다. edit이 $EDITOR를 열어 애드혹 수정을 합니다.
# update container image
kubectl set image deployment/nginx nginx=nginx:1.26
# update from a specific container
kubectl set image deployment/nginx container=nginx:1.26 --record
# trigger a rollout restart (same image, recreate pods)
kubectl rollout restart deployment/nginx
# edit a deployment in editor
kubectl edit deployment/nginx
# patch a single field
kubectl patch deployment/nginx -p '{"spec":{"replicas":5}}'
# apply a manifest change
kubectl apply -f nginx-deployment.yamlDeployment 상태
Deployment가 ReplicaSet들을 소유하며 하나만 활성입니다(replicas>0). 오래된 ReplicaSet은 롤백을 위해 0으로 스케일됩니다. pod-template-hash가 각 pod에 리비전 라벨을 붙입니다. Available, Progressing, ReplicaFailure 신호는 status.conditions에서 확인하세요.
# deployment status
kubectl get deployment nginx
# watch rollout
kubectl rollout status deployment/nginx
# show ReplicaSets owned by the deployment
kubectl get rs -l app=nginx
# show pods across all revisions
kubectl get pods -l app=nginx --show-labels
# pod-template-hash label distinguishes revisions
# kubectl get pods -l app=nginx,pod-template-hash=xxxx
# conditions: Available, Progressing, ReplicaFailure
kubectl get deployment nginx -o jsonpath='{.status.conditions}'Service
서비스 타입
Service가 pod 집합에 걸쳐 로드밸런싱하는 안정적인 IP/DNS를 제공합니다. ClusterIP가 기본입니다(클러스터 안에서만). NodePort와 LoadBalancer가 외부에 노출합니다. ExternalName은 프록시가 아닌 DNS 별칭입니다.
# four service types:
# - ClusterIP (default): reachable inside the cluster
# - NodePort: exposed on each node's IP at a static port
# - LoadBalancer: cloud-provisioned external LB
# - ExternalName: DNS CNAME to an external host
# quick create
kubectl expose deployment nginx --port=80 --type=ClusterIP
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# external name (no proxying, pure DNS)
kubectl create service externalname my-svc --external-name=db.example.comClusterIP 서비스
ClusterIP가 클러스터 안의 안정적 가상 IP와 DNS 이름을 줍니다. selector가 pod 라벨에 매칭되고, kube-proxy가 엔드포인트에 걸쳐 로드밸런싱하도록 iptables/IPVS를 프로그래밍합니다. <svc>.<ns>.svc.cluster.local이나 그냥 <svc>로 해석합니다.
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: ClusterIP
selector:
app: nginx
ports:
- name: http
port: 80 # service port
targetPort: 80 # container port
protocol: TCP
# DNS: nginx.default.svc.cluster.local
# short names also work: nginx, nginx.default
# kube-dns / CoreDNS resolves the service VIPNodePort 서비스
NodePort가 모든 노드에서 같은 정적 포트(30000-32767)를 엽니다. 어떤 노드:nodePort로의 트래픽이든 pod에 닿습니다(kube-proxy가 다른 노드의 pod로 리다이렉트할 수 있음). 클라우드 LB를 프로비저닝할 수 없을 때 유용; HA에는 외부 LB와 짝지으세요.
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: NodePort
selector:
app: nginx
ports:
- port: 80
targetPort: 80
nodePort: 30080 # optional, 30000-32767 range
# reachable at <any-node-ip>:30080
# also still reachable via clusterIP:80
# get assigned nodePort
kubectl get svc nginx -o jsonpath='{.spec.ports[*].nodePort}'LoadBalancer 서비스
LoadBalancer가 노드를 가리키는 외부 로드밸런서를 프로비저닝하도록 클라우드 제공자에 요청합니다. externalTrafficPolicy: Local은 클라이언트 소스 IP를 보존하지(SNAT 없음) 크로스 노드 로드밸런싱을 건너뜁니다. 준비되면 STATUS가 할당된 외부 IP를 보여줍니다.
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: LoadBalancer
selector:
app: nginx
ports:
- port: 80
targetPort: 80
# cloud-specific annotations
# annotations:
# service.beta.kubernetes.io/aws-load-balancer-type: nlb
# service.beta.kubernetes.io/azure-load-balancer-internal: "true"
# externalTrafficPolicy: Local preserves client IP
externalTrafficPolicy: Local
# status.ingress shows the external IP/hostnameHeadless 서비스
headless 서비스(clusterIP: None)는 VIP가 없습니다 — DNS가 pod IP를 직접 반환합니다. StatefulSet이 각 pod가 안정적 DNS 이름(pod-0.svc, pod-1.svc)을 얻기 위해 필요합니다. 모든 백엔드를 스스로 발견하고 싶은 클라이언트도 씁니다.
apiVersion: v1
kind: Service
metadata:
name: nginx-headless
spec:
clusterIP: None # makes it headless
selector:
app: nginx
ports:
- port: 80
targetPort: 80
# DNS returns pod IPs directly (not a VIP)
# A records: nginx-headless.default.svc.cluster.local
# -> 10.1.0.5, 10.1.0.6, 10.1.0.7
# used by StatefulSet for stable pod DNS:
# <pod-name>.<svc-name>.default.svc.cluster.localEndpoints & EndpointSlice
Endpoints/EndpointSlices가 실제로 트래픽을 받는 pod IP를 나열합니다 — Ready인 pod만 나타납니다. 서비스에 엔드포인트가 없으면 pod가 셀렉터에 매칭되지 않거나 Ready가 아닙니다. EndpointSlices(v1)는 거대한 서비스에 더 잘 확장되며 기본입니다.
# view endpoints backing a service
kubectl get endpoints nginx
# endpoint slices (newer, more scalable)
kubectl get endpointslices -l kubernetes.io/service-name=nginx
# endpoints track pods that match the selector
# AND pass readiness checks
kubectl describe endpoints nginx
# a service with no ready pods has no endpoints
# - check pod readiness if traffic is refused
# - EndpointSlices are grouped by address type (IPv4/IPv6)
# manually managed endpoints (selector-less service)ConfigMap
ConfigMap 생성
ConfigMap이 민감하지 않은 설정을 키-값 쌍으로 저장합니다. 인라인 값에는 --from-literal, 전체 파일을 담기에는 --from-file(파일명이 키가 됨)을 쓰세요. 재빌드 없이 설정을 이미지에서 분리하는 데 유용합니다.
# from literal values
kubectl create configmap app-config \
--from-literal=LOG_LEVEL=debug \
--from-literal=ENABLE_FEATURE=true
# from a file (key = filename, value = contents)
kubectl create configmap app-config --from-file=app.properties
# from a directory (one key per file)
kubectl create configmap app-config --from-file=configs/
# from an env file
kubectl create configmap app-config --from-env-file=app.env
# from a file with a custom key
kubectl create configmap app-config --from-file=custom-key=app.propertiesConfigMap 매니페스트
data가 문자열 값을 담습니다(마운트 시 각 키가 env var이나 파일이 됨). 여러 줄 문자열에는 YAML 블록 스칼라(|)를 씁니다. binaryData가 바이너리 블롭용 base64를 받습니다. 전체 크기 한도는 ConfigMap당 1 MiB입니다.
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
LOG_LEVEL: "debug"
ENABLE_FEATURE: "true"
application.yml: |
server:
port: 8080
logging:
level: debug
binaryData:
# base64-encoded binary values
logo.png: iVBORw0KGgoAAAANSUhEUg...환경 변수로 소비
envFrom이 모든 ConfigMap 키를 한 번에 env var로 주입합니다. configMapKeyRef가 있는 env가 개별 키를 고릅니다. optional: true는 ConfigMap이 없어도 pod가 시작되게 합니다. ConfigMap의 갱신은 실행 중인 pod의 env var를 새로 고치지 않습니다.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: app-config
key: LOG_LEVEL
envFrom:
- configMapRef:
name: app-config # injects all keys as env vars
optional: true # pod starts even if CM missing볼륨으로 소비
ConfigMap을 볼륨으로 마운트하면 각 키가 파일로 프로젝션됩니다. ConfigMap의 갱신은 결국 마운트된 파일에 반영되지만(kubelet 동기 주기로 설정됨) — 앱이 다시 읽어야 합니다. subPath 마운트는 단일 키를 고정하며 갱신되지 않습니다.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: config
mountPath: /etc/config
readOnly: true
volumes:
- name: config
configMap:
name: app-config
items: # optional: pick subset
- key: application.yml
path: app.yml # rename file
defaultMode: 0644
# each ConfigMap key becomes a file under /etc/config갱신 & 리로드
마운트된 ConfigMap 파일은 자동 갱신되지만(kubelet 동기 후), env var는 pod 수명 동안 불변입니다 — env 변화를 반영하려 pod를 재시작하세요. 설정 갱신을 Deployment에 전파하는 가장 깔끔한 방법은 rollout restart입니다.
# edit the configmap
kubectl edit configmap app-config
# patch a single key
kubectl patch configmap app-config \
--type merge -p '{"data":{"LOG_LEVEL":"info"}}'
# mounted files update within ~kubelet sync period (default 60s)
# but env vars do NOT update in running pods
# force pods to pick up new config by rolling them
kubectl rollout restart deployment/app
# verify the new value on a pod
kubectl exec app -- printenv LOG_LEVEL불변 ConfigMap
immutable: true는 ConfigMap을 얼립니다 — 어떤 변경이든 delete + recreate가 필요합니다. 이는 크고 안정적인 설정에 대한 kubelet-apiserver watch 트래픽을 크게 줄입니다(대규모에서 주요 확장성 이득). 이미지와 함께 버저닝되는 앱 설정에서 흔합니다.
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
immutable: true
data:
LOG_LEVEL: "debug"
# once immutable, the only change allowed is delete + recreate
# benefits: kubelet does not watch it, lower apiserver load
# useful for large, stable configs in production
# make it mutable again
kubectl patch configmap app-config -p '{"immutable":false}'
# (this fails if currently immutable — must delete instead)Secret
Secret 생성
Secret이 민감한 데이터를 base64로 인코딩해 저장합니다(기본 저장 시 암호화가 아닙니다 — 프로덕션에서는 저장 시 암호화를 활성화). 임의 데이터에는 generic/Opaque, 이미지 풀에는 docker-registry, Ingress TLS에는 tls를 쓰세요. Secret YAML을 git에 커밋하지 마세요.
# generic (opaque) from literals
kubectl create secret generic db-creds \
--from-literal=username=admin \
--from-literal=password='S3cur3!'
# from a file (e.g. SSH key, certificate)
kubectl create secret generic ssh-key --from-file=ssh-privatekey=~/.ssh/id_rsa
# docker registry secret (for private image registries)
kubectl create secret docker-registry regcred \
--docker-server=registry.example.com \
--docker-username=user \
--docker-password=pass \
[email protected]
# TLS secret from cert/key files
kubectl create secret tls my-tls \
--cert=fullchain.pem \
--key=privkey.pemSecret 매니페스트
data 값은 base64로 인코딩되어야 합니다(echo -n 'value' | base64). stringData는 평문을 받아 apply 시 data에 병합되는 편의 기능입니다. type Opaque가 기본이며, 전용 타입(kubernetes.io/tls, kubernetes.io/dockerconfigjson)은 키를 검증합니다.
apiVersion: v1
kind: Secret
metadata:
name: db-creds
type: Opaque
data:
username: YWRtaW4= # base64 of "admin"
password: UzNjdXIzIQ== # base64 of "S3cur3!"
# stringData accepts plaintext (auto-encoded on apply)
stringData:
api-key: "live-key-xyz"
# encode on the command line:
# echo -n 'admin' | base64
# decode:
# echo 'YWRtaW4=' | base64 -dSecret을 환경 변수로
env var로 시크릿을 소비하는 것은 ConfigMap과 같지만 secretKeyRef/secretRef를 씁니다. env var는 /proc/1/environ과 컨테이너의 모든 프로세스에 보입니다 — 매우 민감한 데이터에는 볼륨 마운트를 권합니다.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-creds
key: password
envFrom:
- secretRef:
name: db-creds # injects all keys
optional: trueSecret을 볼륨으로
마운트된 시크릿은 tmpfs(메모리) 볼륨에 파일로 프로젝션됩니다 — 노드 디스크에는 절대 쓰이지 않습니다. defaultMode 0400이 접근을 제한합니다. 마운트된 시크릿은 env var 시크릿과 달리 Secret이 바뀌면(kubelet 동기 후) 실제로 갱신됩니다.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: secrets
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secrets
secret:
secretName: db-creds
defaultMode: 0400 # restrict permissions
items:
- key: password
path: db-password # written to /etc/secrets/db-password
# memory-backed tmpfs, never written to disk on the nodeImagePullSecret
imagePullSecrets가 이미지를 가져올 때 프라이빗 레지스트리에 인증합니다. ServiceAccount에 붙이면 그 SA를 쓰는 모든 pod에 적용됩니다 — 선호되는 패턴입니다. docker-registry 시크릿 타입이 올바른 .dockerconfigjson 페이로드를 자동으로 만듭니다.
# attach to a pod
apiVersion: v1
kind: Pod
metadata:
name: private-app
spec:
imagePullSecrets:
- name: regcred
containers:
- name: app
image: registry.example.com/myapp:1.0
# attach to a service account (auto-applied to all pods using it)
kubectl patch serviceaccount default \
-p '{"imagePullSecrets":[{"name":"regcred"}]}'
# verify
kubectl get sa default -o jsonpath='{.imagePullSecrets}'시크릿 타입
전용 시크릿 타입이 검증과 통합을 가능하게 합니다: Ingress에는 tls, 이미지 풀에는 dockerconfigjson, pod에 자동 마운트되는 service-account-token. 올바른 타입을 쓰면 키가 검증되고 올바른 컨트롤러가 소비합니다.
# Opaque (default) — arbitrary key-value
type: Opaque
# kubernetes.io/service-account-token — auto for SAs
type: kubernetes.io/service-account-token
# kubernetes.io/dockerconfigjson — registry auth
type: kubernetes.io/dockerconfigjson
data:
.dockerconfigjson: <base64>
# kubernetes.io/tls — for Ingress TLS
type: kubernetes.io/tls
data:
tls.crt: <base64>
tls.key: <base64>
# kubernetes.io/basic-auth
type: kubernetes.io/basic-auth
stringData:
username: admin
password: passNamespace
네임스페이스 생성
네임스페이스가 여러 팀이나 환경(개발/스테이지/운영)을 위해 클러스터를 나눕니다. 리소스 이름은 네임스페이스 안에서 고유해야 합니다. 일부 리소스(노드, PV, StorageClass)는 클러스터 스코프이며 네임스페이스가 없습니다.
# imperative
kubectl create namespace dev
# declarative
apiVersion: v1
kind: Namespace
metadata:
name: dev
labels:
environment: development
team: platform
# apply
kubectl apply -f namespace.yaml
# list namespaces
kubectl get namespaces
# set default namespace for current context
kubectl config set-context --current --namespace=devResourceQuota
ResourceQuota가 네임스페이스의 총 리소스 사용을 제한합니다 — 총 CPU/메모리 requests/limits, 객체 수(pod, PVC, 서비스, deployment). 다중 테넌트 클러스터에서 한 팀이 다른 팀을 굶기지 않게 하는 데 필수입니다. quota가 설정되면 명시적 requests가 없는 pod는 거부됩니다.
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-quota
namespace: dev
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
pods: "50"
services.loadbalancers: "2"
persistentvolumeclaims: "10"
count/deployments.apps: "5"
# limits total aggregate resource use in the namespaceLimitRange
LimitRange가 리소스별 기본값과 경계를 설정합니다: 지정하지 않는 pod의 기본 requests/limits, 그리고 터무니없는 값을 제한하는 min/max. ResourceQuota와 짝짓습니다 — 기본 requests가 없으면 quota가 설정을 잊은 모든 pod를 거부합니다.
apiVersion: v1
kind: LimitRange
metadata:
name: default-limits
namespace: dev
spec:
limits:
- type: Container
default: # default limits (if unset)
cpu: 500m
memory: 512Mi
defaultRequest: # default requests (if unset)
cpu: 100m
memory: 128Mi
max: # max allowed limits
cpu: "2"
memory: 2Gi
min: # min allowed requests
cpu: 50m
memory: 64Mi
- type: PersistentVolumeClaim
max:
storage: 100Gi
min:
storage: 1Gi네임스페이스 삭제 & 파이널라이저
네임스페이스 삭제는 그 리소스 전부를 캐스케이드합니다. Terminating에 멈춘 네임스페이스에는 보통 완료할 수 없는 파이널라이저가 있습니다 — 사용 불가한 APIService(예: metrics-server)나 컨트롤 러가 사라진 CRD. 파이널라이저를 제거하면 강제 완료되지만 외부 리소스가 새어 나올 수 있습니다.
# delete a namespace (cascades all resources in it)
kubectl delete namespace dev
# if stuck in Terminating, inspect finalizers
kubectl get namespace dev -o yaml
# remove finalizer to force completion (DANGEROUS)
kubectl patch namespace dev -p '{"metadata":{"finalizers":null}}'
# resources that block deletion:
# - APIService unavailable (metrics-server removed)
# - custom resources whose CRD is gone
# - PVCs with attached PVs
# check what's still in the namespace
kubectl api-resources --verbs=list --namespaced -o name \
| xargs -n 1 kubectl get -n dev --ignore-not-found기본 네임스페이스
kube-system이 컨트롤 플레인과 애드온(DNS, kube-proxy, CNI)을 실행합니다. kube-public은 미인증 사용자가 읽을 수 있는 부트스트랩 데이터를 담습니다. kube-node-lease가 성능을 위해 노드 하트비트를 Lease 객체로 저장합니다. 네임스페이스를 지정하지 않으면 default에 워크로드가 놓입니다.
# built-in namespaces
kubectl get namespaces
# NAME STATUS AGE
# default Active 30d <- user workloads land here
# kube-system Active 30d <- control plane / addons
# kube-public Active 30d <- publicly readable (bootstrap)
# kube-node-lease Active 30d <- node heartbeats (leases)
# kube-system holds:
# - kube-dns / CoreDNS
# - kube-proxy
# - metrics-server
# - CNI, CSI, cloud provider controllers
# kube-public is readable by all (used for cluster info discovery)네임스페이스 스코프 vs 클러스터 스코프
대부분의 워크로드 리소스는 네임스페이스화되어 있고, 인프라(노드, PV, StorageClass, ClusterRole)는 클러스터 스코프입니다. Service는 자기 네임스페이스의 pod만 타깃할 수 있습니다. -A가 --all-namespaces의 축약입니다 — 클러스터 전체 가시성에 필수입니다.
# which resources are namespaced?
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
# namespaced: pods, services, deployments, configmaps, secrets
# cluster-scoped: nodes, namespaces, PVs, StorageClasses, ClusterRoles
# access across namespaces:
# - a Service selector only matches pods in the SAME namespace
# - cross-namespace refs require special controllers (e.g. external-dns)
# list resources across all namespaces
kubectl get pods --all-namespaces
kubectl get pods -A # shorthand라벨 & 셀렉터
라벨 문법
라벨은 리소스를 식별·그룹화하는 키-값 쌍입니다. 키에는 선택적 접두사가 있습니다(DNS 서브도메인, 예: app.kubernetes.io/). 라벨은 임의의 비식별 메타데이터인 어노테이션과 달리 조회/필터링용입니다.
# labels are key=value pairs
# key: prefix (optional DNS subdomain) + name
# value: string, up to 63 chars
metadata:
labels:
app: nginx
tier: frontend
env: prod
app.kubernetes.io/name: nginx
app.kubernetes.io/version: "1.25"
# view labels
kubectl get pods --show-labels
# add/overwrite a label
kubectl label pod nginx env=prod
kubectl label pod nginx env=staging --overwrite
# remove a label (trailing dash)
kubectl label pod nginx env-동등 & 집합 셀렉터
두 가지 셀렉터 방식: 동등 기반(=, ==, !=)과 집합 기반(in, notin, exists, !exists). 쉼표로 구분된 여러 조건은 AND됩니다. 서비스와 Deployment는 YAML에서 동등 기반 셀렉터를 쓰고, kubectl -l은 둘 다 지원합니다.
# equality-based: = == !=
kubectl get pods -l app=nginx
kubectl get pods -l env!=dev
kubectl get pods -l 'app=nginx,env=prod' # AND of conditions
# set-based: in, notin, exists
kubectl get pods -l 'env in (prod,staging)'
kubectl get pods -l 'env notin (dev)'
kubectl get pods -l 'tier' # key exists
kubectl get pods -l '!canary' # key does not exist
# combine equality and set-based
kubectl get pods -l 'app=nginx,env in (prod,staging)'리소스 라벨링
label은 식별 메타데이터를 변형합니다 — 셀렉터가 매칭할 모든 것에 쓰세요. annotate는 비식별 메타데이터입니다(소유자, 티켓, 설명, 도구 힌트). 노드에는 보통 스케줄링을 유도하려 토폴로지나 하드웨어 힌트 라벨을 붙입니다.
# label a pod
kubectl label pod nginx app=nginx tier=web
# label all pods matching a selector
kubectl label pods -l app=oldapp app=newapp --overwrite
# label a node (for scheduling hints)
kubectl label node node-1 disktype=ssd
# remove a node label
kubectl label node node-1 disktype-
# list nodes by label
kubectl get nodes -l disktype=ssd
# annotate (non-identifying metadata)
kubectl annotate pod nginx owner=alice
kubectl annotate pod nginx description="web server"매니페스트의 셀렉터
YAML에서 셀렉터는 matchLabels(동등)와 matchExpressions(In/NotIn/Exists/DoesNotExist가 있는 집합 기반)를 씁니다. Deployment의 셀렉터는 생성 뒤 불변이며 — pod 템플릿 라벨이 이와 일치해야 합니다. 서비스는 matchLabels만 지원합니다.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels: # equality-based
app: nginx
matchExpressions: # set-based (optional)
- key: env
operator: In
values: [prod, staging]
- key: tier
operator: Exists
template:
metadata:
labels:
app: nginx # MUST match selector
env: prod
tier: web어노테이션
어노테이션은 도구가 쓰는 비식별 메타데이터를 담습니다 — kubectl apply가 last-applied 설정을 저장하고, cert-manager가 발급자 힌트를 읽으며, Prometheus가 스크레이프 설정을 읽고, 컨트롤러가 롤아웃 상태를 저장합니다. 라벨과 달리 어노테이션 값은 큰 JSON 블롭이 될 수 있습니다.
metadata:
annotations:
kubernetes.io/change-cause: "bump nginx to 1.26"
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"apps/v1",...}
cert-manager.io/cluster-issuer: "letsencrypt-prod"
# view annotations
kubectl get pod nginx -o jsonpath='{.metadata.annotations}'
# annotate
kubectl annotate pod nginx owner=team-platform
# remove an annotation (trailing dash)
kubectl annotate pod nginx owner-권장 라벨
app.kubernetes.io/* 라벨은 공유 어휘입니다. 이로써 도구(Helm, 오퍼레이터, 대시보드)가 애플리케이션의 모든 리소스를 그룹화합니다. name+instance가 릴리스를 고유 식별하고, component/part-of가 계층을 기술하며, managed-by/created-by가 소유권을 추적합니다.
# shared recommended labels (app.kubernetes.io/*)
metadata:
labels:
app.kubernetes.io/name: nginx
app.kubernetes.io/instance: nginx-prod
app.kubernetes.io/version: "1.25"
app.kubernetes.io/component: web
app.kubernetes.io/part-of: storefront
app.kubernetes.io/managed-by: helm
app.kubernetes.io/created-by: controller-manager
# Helm applies these automatically; kubectl doesn't.
# They unify how tooling identifies an application's resources
# across Deployments, Services, Ingresses, ConfigMaps, etc.ReplicaSet
ReplicaSet 매니페스트
ReplicaSet이 셀렉터에 매칭되는 안정적인 복제 pod 집합을 유지합니다 — pod가 삭제되거나 실패하면 재생성합니다. 거의 항상 Deployment를 쓰세요. 이는 ReplicaSet을 감싸 롤링 업데이트와 롤백을 더합니다.
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
# kubectl get rs
# kubectl describe rs nginxReplicaSet 동작 방식
ReplicaSet 컨트롤러가 셀렉터를 써 기대 pod 수와 실제 수를 조정(reconcile)합니다. 각 pod가 RS를 가리키는 ownerReference를 얻습니다 — kubectl get pod가 'Owned by ReplicaSet/nginx'를 보여주는 이유입니다. 스케일링은 기대 수를 바꿀 뿐입니다.
# the controller loop:
# 1. count pods matching selector
# 2. if fewer than replicas -> create from template
# 3. if more than replicas -> delete excess (arbitrary order)
# owned-by reference on each pod
kubectl get pod -l app=nginx -o jsonpath='{.items[*].metadata.ownerReferences}'
# if you delete a pod, the RS creates a new one immediately
kubectl delete pod <pod-name>
kubectl get pods -l app=nginx
# scale by editing replicas
kubectl scale rs nginx --replicas=5ReplicaSet vs ReplicationController
ReplicationController(원래의 v1 프리미티브)는 동등 셀렉터만 지원하며 폐기됐습니다. ReplicaSet(apps/v1)이 집합 기반 셀렉터를 추가합니다. 실전에서는 Deployment를 쓰세요 — ReplicaSet을 대신 관리하고 롤링 업데이트/롤백을 제공합니다.
# ReplicationController (v1, legacy): equality-only selectors
# ReplicaSet (apps/v1, modern): set-based selectors (in, notin, exists)
# ReplicationController is deprecated; do not use.
apiVersion: v1
kind: ReplicationController # legacy
# ...
# ReplicaSet is the successor:
apiVersion: apps/v1
kind: ReplicaSet # modern
# ...
# Deployment wraps ReplicaSet and is the recommended primitive:
apiVersion: apps/v1
kind: Deployment # use this in practice수동 스케일링
kubectl scale이 replicas 필드를 바꿉니다. HPA가 같은 리소스를 타깃하면 다음 reconcile에서 수동 스케일링을 덮어씁니다. 일회성에는 kubectl scale, 지속적인 탄력적 워크로드에는 HPA를 권합니다.
# scale a replicaset directly
kubectl scale rs nginx --replicas=5
# scale via patch
kubectl patch rs nginx -p '{"spec":{"replicas":5}}'
# scale multiple resources at once
kubectl scale deployment nginx deployment web --replicas=3
# scale by referencing a file
kubectl scale --replicas=5 -f nginx.yaml
# the autoscaler (HPA) will override manual scaling
# if it targets the same resource템플릿 변경 & 채택
Deployment와 달리 맨 ReplicaSet은 pod 템플릿 변경을 롤아웃하지 않습니다 — 새로 만들어진 pod(삭제/스케일업 뒤)만 새 스펙을 받습니다. ReplicaSet은 셀렉터에 매칭되는 고아 pod를 채택해 의외의 동작을 일으킬 수 있습니다.
# changing the pod template does NOT update existing pods
# (unlike a Deployment, a bare ReplicaSet won't roll out)
kubectl edit rs nginx # change image -> new pods use it, old ones don't
# delete old pods to force them onto the new template
kubectl delete pods -l app=nginx
# a ReplicaSet will ADOPT existing pods that match its selector
# even pods created independently — useful (and dangerous)
# orphaned pods (no owner) matching the selector are taken over
kubectl get pods -l app=nginx --show-kindReplicaSet에서 pod 제거
ReplicaSet이 재생성하지 않고 pod를 제거하려면, RS를 먼저 0으로 스케일하거나 pod에서 ownerReferences를 떼어 RS가 더 이상 소유하지 않게 하세요. 특정 인스턴스 디버깅이나 정리 전 로그 추출에 유용합니다.
# detaching a pod from its ReplicaSet (so it isn't replaced)
kubectl patch pod <pod-name> \
-p '{"metadata":{"ownerReferences":[]}}'
# now deleting this pod won't trigger a replacement,
# because the RS no longer owns it
# or scale the RS to 0 first, then delete
kubectl scale rs nginx --replicas=0
kubectl delete pod <pod-name>
# useful for debugging a specific failing pod instance
# without the RS immediately recreating itStatefulSet
StatefulSet 매니페스트
StatefulSet이 pod에 안정적인 정체(이름, 호스트명, 스토리지)와 순서화된 배포/스케일을 줍니다. headless인 serviceName이 필요합니다. volumeClaimTemplates가 pod마다 전용 PVC를 만듭니다 — pod-0이 재스케줄돼도 같은 볼륨을 다시 붙입니다.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
serviceName: mysql # required: headless service
replicas: 3
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:8
ports:
- containerPort: 3306
volumeMounts:
- name: data
mountPath: /var/lib/mysql
volumeClaimTemplates: # one PVC per pod
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi안정적인 정체
각 pod가 안정적인 서수 이름(mysql-0, mysql-1, …)과 headless 서비스를 통한 안정적 DNS 이름을 얻습니다. 노드가 실패하면 pod-0이 다른 곳으로 재스케줄되지만 이름을 유지하고 볼륨을 다시 붙입니다 — 안정적인 멤버십에 의존하는 클러스터형 데이터베이스에 결정적입니다.
# pods are named <statefulset-name>-<ordinal>
# mysql-0, mysql-1, mysql-2
kubectl get pods -l app=mysql
# each pod has stable DNS (via the headless service):
# mysql-0.mysql.default.svc.cluster.local
# mysql-1.mysql.default.svc.cluster.local
# stable hostname inside the pod:
kubectl exec mysql-0 -- hostname
# -> mysql-0
# ordinal index also exposed:
kubectl exec mysql-0 -- sh -c 'echo $HOSTNAME'
# -> mysql-0
# pod identity persists across reschedules안정적인 스토리지
volumeClaimTemplates가 pod마다 예측 가능한 이름의 PVC를 생성합니다(data-mysql-0, …). PVC는 pod와 StatefulSet 삭제를 살아남습니다 — 데이터 손실을 막지만 저장소 회수를 위해 PVC를 명시적으로 삭제해야 합니다. 같은 볼륨이 항상 같은 서수 pod에 다시 붙습니다.
# one PVC per pod, named <volumeClaimTemplate-name>-<pod-name>
kubectl get pvc
# NAME STATUS VOLUME CAPACITY ...
# data-mysql-0 Bound pvc-aaa 10Gi
# data-mysql-1 Bound pvc-bbb 10Gi
# data-mysql-2 Bound pvc-ccc 10Gi
# when pod-0 is rescheduled, it re-binds data-mysql-0
# deleting the StatefulSet does NOT delete PVCs by default
# (protects from accidental data loss)
# to actually delete the data:
kubectl delete pvc data-mysql-0 data-mysql-1 data-mysql-2순서화 배포 & pod 관리
OrderedReady(기본값)는 pod를 엄격히 0→1→2 순서로 만들고 역순으로 삭제합니다 — 복제본보다 프라이머리가 먼저 떠야 하는 시스템에 필요합니다. Parallel은 모든 pod를 동시에 만들고 삭제합니다 — 대칭 샤드 스토어(Cassandra, Elasticsearch)에 더 빠릅니다.
spec:
podManagementPolicy: OrderedReady # default: strict order
# podManagementPolicy: Parallel # create/delete all at once
replicas: 3
# OrderedReady: create pod-0, then pod-1, then pod-2 (each waits for Ready)
# deletion is reverse: pod-2, pod-1, pod-0
# Parallel: all pods created/deleted simultaneously
# identity and storage remain stable either way
# check policy
kubectl get statefulset mysql -o jsonpath='{.spec.podManagementPolicy}'
# parallel is great for sharded stores that don't need bootstrap order롤링 업데이트
StatefulSet의 롤링 업데이트는 역서수 순서로(N-1부터 0까지) 갑니다. partition으로 최고 서수 pod부터 카나리할 수 있습니다. OnDelete는 수동으로 pod를 삭제할 때까지 업데이트를 멈춥니다 — 통제된 마이그레이션에 유용. 순서 때문에 롤아웃이 Deployment보다 느립니다.
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2 # only pods with ordinal >= 2 update
maxUnavailable: 1 # (default 1) allowed down
# type: OnDelete -> only update when pod is manually deleted
# partition enables canaries: set partition=N to update
# only the top N pods; lower to 0 to roll out to all.
kubectl rollout status statefulset/mysql
# waits for all pods to be updated
# StatefulSets also support rollout history/undo,
# but only when the change is in the pod templateHeadless 서비스 연계
spec.serviceName이 참조하는 headless 서비스(clusterIP: None)가 안정적인 pod별 DNS를 가능하게 합니다. 없으면 StatefulSet이 pod를 만들지 않습니다. 클라이언트는 라운드 로빈용으로 서비스 이름을, 프라이머리 고정용으로 pod-0.svc를 해석합니다. Service 생성을 잊지 마세요.
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
clusterIP: None # headless
selector:
app: mysql
ports:
- port: 3306
---
# StatefulSet references this service via spec.serviceName
# this gives each pod a stable DNS:
# mysql-0.mysql.default.svc.cluster.local
# clients can:
# - resolve mysql -> any pod IP (load-balanced by DNS round-robin)
# - resolve mysql-0.mysql -> pod-0's IP (pin to a specific replica)
# required: serviceName MUST match the headless service nameDaemonSet
DaemonSet 매니페스트
DaemonSet이 (스케줄링 제약에 매칭되는) 노드마 다 정확히 하나의 pod를 실행합니다. 노드 수준 에이전트에 완벽합니다: 로그 수집기, 모니터링, 스토리지, CNI, 인그레스 컨트롤러. 새 노드는 자동으로 pod를 얻고, 삭제된 노드의 것은 가비지 컬렉션됩니다.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: log-agent
namespace: kube-system
labels:
app: log-agent
spec:
selector:
matchLabels:
app: log-agent
template:
metadata:
labels:
app: log-agent
spec:
containers:
- name: agent
image: fluent-bit:2.2
resources:
requests:
cpu: 100m
memory: 128Mi
# one pod per (matching) node automatically노드 스케줄링
nodeSelector가 가장 단순한 제약입니다(모든 key=value가 매칭). nodeAffinity가 In/NotIn/Exists 연산자와 preferred/required 규칙을 더합니다. DaemonSet은 어떤 pod처럼 이들을 존중합니다 — tolerations와 결합하면 taint된 컨트롤 플레인 노드에서도 에이전트를 실행할 수 있습니다.
spec:
template:
spec:
nodeSelector: # simplest: must match all
disktype: ssd
# more flexible affinity
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/os
operator: In
values: [linux]
# only run on nodes labeled role=logging
nodeSelector:
role: logging
tolerations: # tolerate tainted nodes
- key: node-role.kubernetes.io/control-plane
operator: Exists업데이트 전략
RollingUpdate(기본값)가 maxUnavailable(숫자나 %)로 제한되며 노드별로 pod를 업데이트합니다. OnDelete는 수동으로 각 pod를 삭제할 때까지 업데이트를 멈춥니다 — 노드별 제어가 필요할 때 유용. maxSurge의 기본은 0입니다(DaemonSet은 여분 pod를 원치 않습니다).
spec:
updateStrategy:
type: RollingUpdate # default
rollingUpdate:
maxUnavailable: 1 # how many nodes update at once
maxSurge: 0 # (default 0) no extra pods
# type: OnDelete # only update when old pod is deleted
# trigger an update (e.g. new image)
kubectl set image daemonset/log-agent agent=fluent-bit:2.3
# watch rollout
kubectl rollout status daemonset/log-agent -n kube-system
# rollout restart (recreate pods on every node)
kubectl rollout restart daemonset/log-agent -n kube-systemTaint & Toleration
Taint 가 pod를 밀어내고, tolerations가 특정 pod가 taint를 무시하게 합니다. 컨트롤 플레인 노드는 NoSchedule로 taint되어 사용자 워크로드가 놓이지 않습니다 — 노드 수준 에이전트가 이를 toleration해 모든 곳에서 실행됩니다. NoExecute는 이미 실행 중인 non-tolerating pod도 축출합니다.
# inspect a node's taints
kubectl describe node node-1 | grep Taints
# Taints: node-role.kubernetes.io/control-plane:NoSchedule
# tolerate control-plane so the agent runs there too
spec:
template:
spec:
tolerations:
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
- key: node.kubernetes.io/disk-pressure
operator: Exists
effect: NoExecute
# taint effects: NoSchedule | NoExecute | PreferNoScheduleDaemonSet 활용
DaemonSet이 노드 수준 인프라의 표준 배포 형태입니다. 역할을 하려 자주 특권 접근(hostNetwork, hostPID, hostPath)이 필요합니다 — 이는 의도적으로, 신뢰된 이미지에만 부여하세요. 가로로 스케일해야 할 앱 워크로드에는 DaemonSet을 절대 쓰지 마세요.
# classic DaemonSet workloads (node-level agents):
# - log collection: fluent-bit, filebeat, promtail
# - monitoring: node-exporter, datadog-agent
# - networking: kube-proxy, CNI plugins, ingress controllers
# - storage: CSI node plugins, Rook/Ceph
# - security: Falco, Tetragon, runtime security
# - GPU/FPGA drivers: nvidia-device-plugin
# storage / device plugins often need:
spec:
template:
spec:
hostNetwork: true # use node network namespace
hostPID: true # see node processes
hostPath: # mount node paths
- path: /var/log
- path: /var/lib/docker/containersDaemonSet 상태
DESIRED가 스케줄링 제약에 매칭되는 노드 수와 같고, CURRENT/READY가 존재하고 readiness를 통과하는 pod 수를 보여줍니다. 각 pod가 어느 노드에 놓였는지 보기 가장 쉬운 방법은 -o wide입니다. DaemonSet은 Deployment처럼 롤아웃 히스토리/undo를 지원합니다.
# desired = number of matching nodes
kubectl get daemonset log-agent -n kube-system
# NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE
# log-agent 5 5 5 5 5
# show which nodes a DaemonSet pod landed on
kubectl get pods -n kube-system -l app=log-agent -o wide
# rollout history
kubectl rollout history daemonset/log-agent -n kube-system
# rollback
kubectl rollout undo daemonset/log-agent -n kube-system
# check a per-node pod's logs
kubectl logs -n kube-system log-agent-abcdeJob & CronJob
Job 매니페스트
Job이 지정한 개수(completions)의 pod가 성공적으로 완료될 때까지 pod를 실행합니다. restartPolicy는 Never나 OnFailure여야 합니다(Always는 장기 실행 워크로드용). backoffLimit이 재시도를 제한하고, activeDeadlineSeconds가 총 실행 시간을 제한합니다.
apiVersion: batch/v1
kind: Job
metadata:
name: pi
spec:
completions: 1 # how many successful pods needed
parallelism: 1 # how many run concurrently
backoffLimit: 6 # retries before marking Failed
activeDeadlineSeconds: 600 # hard timeout
template:
spec:
restartPolicy: Never # OnFailure | Never
containers:
- name: pi
image: perl
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
# kubectl get jobs
# kubectl logs job/piJob 완료 & 병렬성
completions는 Job을 만족하는 성공 pod 수이고, parallelism는 동시 실행 수입니다. Indexed Job은 각 pod에 서수를 부여합니다(env var JOB_COMPLETION_INDEX) — 각 pod가 한 조각을 담당하는 샤드 배치 처리에 좋습니다. NonIndexed(기본값)는 어디서든 N개 성공만 필요합니다.
spec:
completions: 5 # 5 successful pods total
parallelism: 2 # 2 pods run at a time
backoffLimit: 4
# default completionMode: NonIndexed (any 5 successes)
completionMode: Indexed
# Indexed: pods get 0..N-1 in JOB_COMPLETION_INDEX env,
# useful for sharded work (each pod handles one shard)
template:
spec:
restartPolicy: OnFailure
containers:
- name: worker
image: worker:1.0
# set via kubectl
kubectl create job pi --image=perl -- perl -Mbignum=bpi -wle "print bpi(2000)"Job 백오프 & 타임아웃
backoffLimit이 실패 pod를 재시도합니다(지수 백오프). activeDeadlineSeconds가 하드 상한입니다 — 도달하면 재시도가 남아 있어도 Job이 Failed로 표시됩니다. ttlSecondsAfterFinished가 완료된 Job을 자동 정리합니다. podFailurePolicy(1.31+)가 특정 종료 코드에 빠른 실패나 자발적 축출 무시를 가능하게 합니다.
spec:
backoffLimit: 6 # default 6, retries on failure
activeDeadlineSeconds: 3600 # hard wall, even if retries remain
ttlSecondsAfterFinished: 86400 # auto-delete Job 1 day after done
startingDeadlineSeconds: 300 # (CronJob only) miss window
# pod failure handling (v1.31+):
podFailurePolicy:
rules:
- action: FailJob
onExitCodes:
operator: In
values: [42] # exit 42 -> don't retry, fail fast
- action: Count
onPodConditions:
- type: DisruptionTarget # don't count voluntary evictions
template:CronJob 매니페스트
CronJob이 cron 스케줄(5 필드: 분 시 일 월 요일)로 Job을 만듭니다. concurrencyPolicy가 겹치는 실행을 제어합니다: Forbid는 이전이 진행 중이면 새 실행을 건너뛰고, Replace는 옛 것을 죽이고 새 것을 시작합니다. timeZone(1.27+)이 UTC 계산을 필요 없게 합니다.
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup
spec:
schedule: "0 2 * * *" # 5-field cron: 02:00 daily
timeZone: "Asia/Shanghai"
concurrencyPolicy: Forbid # Allow | Forbid | Replace
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
startingDeadlineSeconds: 200
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: backup:1.0
# kubectl get cronjob
# kubectl get jobsCronJob 중단 & 히스토리
suspend: true는 삭제 없이 CronJob을 멈춥니다 — 장애 중에 편리합니다. 히스토리 한도가 Job 목록을 관리 가능하게 유지합니다(기본 성공 3 / 실패 1). kubectl create job --from=cronjob/X가 템플릿을 즉시 실행합니다 — 수동 트리거나 놓친 실행 백필에 완벽합니다.
spec:
schedule: "*/5 * * * *"
suspend: true # pause without deleting the CronJob
successfulJobsHistoryLimit: 3 # default 3
failedJobsHistoryLimit: 1 # default 1
# toggle suspend
kubectl patch cronjob backup -p '{"spec":{"suspend":true}}'
kubectl patch cronjob backup -p '{"spec":{"suspend":false}}'
# trigger a one-off run immediately
kubectl create job --from=cronjob/backup manual-backup
# clean up old jobs manually
kubectl delete jobs -l job-name=backupCronJob 스케줄 & 예외 사례
표준 5 필드 cron입니다. 일-of-월과 요일 둘 다 제한되면 cron은 둘 중 하나만 맞아도(OR 의미) 발화합니다 — 클래식한 함정입니다. CronJob의 예약 시간이 startingDeadlineSeconds보다 오래 놓치면 그 실행은 백필되지 않고 건너뛰어집니다.
# cron syntax (5 fields):
# ┌───────────── minute (0-59)
# │ ┌───────────── hour (0-23)
# │ │ ┌───────────── day of month (1-31)
# │ │ │ ┌───────────── month (1-12)
# │ │ │ │ ┌───────────── day of week (0-6, Sun=0)
# "*/5 * * * *" every 5 minutes
# "0 2 * * *" daily at 02:00
# "0 0 * * 0" weekly Sunday midnight
# "0 0 1 * *" monthly on the 1st
# "30 3-5 * * *" 03:30, 04:30, 05:30
# gotchas:
# - day-of-month AND day-of-week both set => OR (not AND)
# - if startingDeadlineSeconds is missed, the run is skipped
# - control-plane restart can skip a tick if the schedule is missed
# - cron interprets literal fields; prefer timeZone over UTC mathIngress
Ingress 매니페스트
Ingress가 클러스터 밖에서 서비스로의 HTTP/HTTPS 라우트를 노출하며, Ingress 컨트롤러(nginx, traefik, ALB, …)가 관리합니다. ingressClassName이 어떤 컨트롤러가 처리할지 고릅니다. 각 규칙이 host + path를 service+port 백엔드에 매핑합니다.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
- path: /api
pathType: Prefix
backend:
service:
name: api
port:
number: 8080TLS가 있는 Ingress
tls 항목이 하나 이상의 호스트에 TLS 시크릿(kubernetes.io/tls 타입, tls.crt + tls.key 보유)을 바인딩합니다. Ingress 컨트롤러가 TLS를 종료하고 백엔드로 평문 HTTP를 프록시합니다. cert-manager가 cluster-issuer 어노테이션을 기반으로 Let's Encrypt 인증서를 자동 발급·교체할 수 있습니다.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-tls
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
- www.example.com
secretName: web-tls-secret # kubernetes.io/tls secret
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
# auto-issue certs with cert-manager:
# annotations:
# cert-manager.io/cluster-issuer: letsencrypt-prodIngress 규칙 & 기본 백엔드
defaultBackend가 어떤 규칙에도 매칭되지 않는 트래픽(호스트 없음이나 매칭되지 않는 경로)을 처리합니다. 여러 규칙으로 하나의 Ingress가 많은 가상 호스트를 라우팅합니다. 각 규칙이 여러 path 백엔드를 가질 수 있습니다 — 하나의 Ingress가 애플리케이션 전체 라우팅 토폴로지를 앞설 수 있습니다.
spec:
ingressClassName: nginx
defaultBackend: # catch-all for unmatched traffic
service:
name: default-svc
port:
number: 80
rules:
- host: app.example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service: { name: api, port: { number: 8080 } }
- host: blog.example.com # different host -> different svc
http:
paths:
- path: /
pathType: Prefix
backend:
service: { name: blog, port: { number: 80 } }IngressClass
IngressClass가 컨트롤러(예: k8s.io/ingress-nginx)를 선언합니다. Ingress가 spec.ingressClassName으로 이를 참조해 여러 컨트롤러가 공존할 수 있습니다. is-default-class 어노테이션으로 기본으로 표시되는 클래스는 하나뿐입니다 — 명시적 클래스 없는 새 Ingress가 이를 씁니다.
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
name: nginx
annotations:
ingressclass.kubernetes.io/is-default-class: "true"
spec:
controller: k8s.io/ingress-nginx
# an Ingress picks a class via spec.ingressClassName
# (replaces the deprecated kubernetes.io/ingress.class annotation)
# multiple IngressClasses in one cluster:
# - nginx (community ingress-nginx)
# - traefik (Traefik controller)
# - alb (AWS ALB)
# only one IngressClass can be marked default경로 타입
Exact가 경로를 그대로 매칭하고, Prefix가 전체 경로 세그먼트를 매칭합니다(/api는 /api와 /api/foo에 매칭되지만 /apix에는 아님). ImplementationSpecific은 컨트롤러에 맡깁니다 — 예: nginx 정규식. 이식 가능한 동작에는 항상 Prefix나 Exact를 권합니다; ImplementationSpecific은 한 컨트롤러에 묶입니다.
spec:
rules:
- host: app.example.com
http:
paths:
- path: /api/v1
pathType: Exact # only /api/v1 (exact match)
backend: ...
- path: /api
pathType: Prefix # /api, /api/, /api/x (prefix match)
backend: ...
- path: /old
pathType: ImplementationSpecific # controller decides
backend: ...
# Prefix matches path segments, not raw string prefix:
# /api matches /api, /api/, /api/x but NOT /apix
# Exact matches the path verbatim
# ImplementationSpecific defers to the controller어노테이션 (Nginx 컨트롤러)
컨트롤러별 어노테이션이 표준 Ingress 스펙 밖의 동작을 설정합니다. ingress-nginx에는 수십 개가 있습니다: rewrite-target, ssl-redirect, body-size, timeouts, CORS, basic auth, configuration snippets. 이들은 컨트롤러 전용입니다 — 다른 컨트롤러로 옮기면 다시 써야 합니다.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
annotations:
kubernetes.io/ingress.class: nginx # legacy form
nginx.ingress.kubernetes.io/rewrite-target: /$2
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/proxy-body-size: "50m"
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
nginx.ingress.kubernetes.io/cors-allow-origin: "https://app.example.com"
nginx.ingress.kubernetes.io/auth-type: basic
nginx.ingress.kubernetes.io/auth-secret: basic-auth
nginx.ingress.kubernetes.io/configuration-snippet: |
more_set_headers "X-Frame-Options: DENY";
spec:
rules:
- host: app.example.com
http:
paths:
- path: /v1(/|$)(.*)
pathType: ImplementationSpecific
backend:
service: { name: api, port: { number: 8080 } }볼륨 (PV/PVC)
PersistentVolume 매니페스트
PersistentVolume(PV)은 관리자가 프로비저닝하거나 StorageClass가 동적으로 만든 클러스터 스코프의 저장소입니다. accessModes가 마운트 방식을 기술합니다. reclaimPolicy가 PVC가 반납될 때 저장소의 운명을 제어합니다.
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-1
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce # RWO: one node R/W
persistentVolumeReclaimPolicy: Retain # Retain | Delete | Recycle
storageClassName: manual
hostPath: # for dev only (single node)
path: /mnt/data
# nfs:
# server: 10.0.0.1
# path: /export/data
# csi:
# driver: ebs.csi.aws.com
# volumeHandle: vol-xxxxPersistentVolumeClaim 매니페스트
PersistentVolumeClaim(PVC)은 네임스페이스화된 저장소 요청입니다. 컨트롤러가 매칭되는 PV(accessModes, 충분한 용량, 같은 StorageClass)에 바인딩합니다. 기본 StorageClass가 있으면 storageClassName을 비워 두는 것이 동적 프로비저닝을 트리거합니다.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: data-claim
spec:
accessModes:
- ReadWriteOnce
storageClassName: manual
resources:
requests:
storage: 5Gi
volumeMode: Filesystem # Filesystem | Block
selector: # optional: filter PVs by labels
matchLabels:
disktype: ssd
# kubectl get pvc
# STATUS: Pending -> Bound once a matching PV is foundAccess Mode
AccessModes가 마운트 의미를 기술합니다 — 그러나 실제 지원은 저장소 백엔드에 달렸습니다. EBS/GCE PD/Azure Disk는 RWO뿐입니다. RWX(다중 노드 읽기/쓰기)에는 NFS, CephFS, 분산 파일시스템이 필요합니다. RWOP(1.27+)는 같은 노드에서도 하나의 pod로 제한합 니다.
# four access modes (support is driver-specific):
# - ReadWriteOnce (RWO): mounted R/W by ONE node
# - ReadOnlyMany (ROX): mounted R/O by MANY nodes
# - ReadWriteMany (RWX): mounted R/W by MANY nodes
# - ReadWriteOncePod (RWOP): mounted R/W by ONE pod (1.27+)
# examples by backend:
# AWS EBS, GCE PD, Azure Disk: RWO only
# NFS: RWO, ROX, RWX
# CephFS, Portworx: RWO, RWX
# Block volumes: RWO
# RWX is required for pods on different nodes
# to share the same volume (e.g. read-only assets)Reclaim 정책
Retain은 안전을 위해 데이터를 유지합니다 — 수동으로 지우고 PV를 재바인딩해야 합니다. Delete(동적 프로비저닝 기본값)는 PVC가 사라지면 PV와 기저 저장소를 모두 지웁니다. Recycle은 폐기됐습니다. Retain인 Released PV는 재바인딩 전에 claimRef를 지워야 합니다.
# what happens when a PVC is deleted:
# - Retain: PV stays, data preserved; PV must be manually
# reclaimed (delete data, then delete PV) before reuse
# - Delete: PV and the underlying storage are deleted (dynamic only)
# - Recycle: deprecated; ran scrub on the volume
# change policy on an existing PV
kubectl patch pv pv-1 -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
# a released PV (PVC deleted, policy Retain) is stuck:
# phase=Released, claimRef still set
# to reuse: clear claimRef
kubectl patch pv pv-1 --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'Pod의 PVC
PVC는 persistentVolumeClaim.claimName으로 어떤 볼륨처럼 마운트합니다. subPath가 서브디렉터리를 마운트합니다 — 하나의 볼륨을 pod/경로들에 걸쳐 공유할 때 편리합니다. RWO 볼륨은 여러 pod가 마운트할 수 있지만 같은 노드에서만; 크로스 노드 마운트는 multi-attach 오류를 냅니다.
apiVersion: v1
kind: Pod
metadata:
name: db
spec:
volumes:
- name: data
persistentVolumeClaim:
claimName: data-claim
containers:
- name: db
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
subPath: pgdata # mount a subdirectory of the volume
# a PVC is namespaced and bound to ONE PV
# RWO PVCs can be mounted by multiple pods on the SAME node
# (e.g. one writer, several readers on that node)정적 vs 동적 프로비저닝
정적 프로비저닝은 관리자가 PV를 미리 만들어야 합니다 — NFS엔 괜찮지만 규모에서는 고통입니다. 동적 프로비저닝은 PVC가 StorageClass의 프로비저너를 통해 수요에 따른 볼륨 생성을 트리거하게 합니다. 현대 클러스터는 거의 항상 동적 프로비저닝을 씁니다; 정적은 공유/레거시 저장소용입니다.
# STATIC: admin pre-creates PVs; PVCs bind to them.
# Good for: pre-existing NFS exports, manual capacity planning.
# DYNAMIC: PVC requests storage; StorageClass provisions a PV
# automatically (AWS EBS, GCE PD, Ceph, local-path, etc.)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: dynamic-claim
spec:
storageClassName: ebs-sc # triggers dynamic provisioning
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 20Gi
# no PV exists -> provisioner creates one -> binds to PVC
# kubectl get pvc dynamic-claim -> Bound
# kubectl get pv -> shows the dynamically-created PVStorageClass
StorageClass 매니페스트
StorageClass가 동적으로 프로비저닝되는 저장소의 '풍미'를 기술합니다: 프로비저너(CSI 드라이버), 매개변수(디스크 타입, 암호화, fsType), 정책. PVC가 spec.storageClassName으로 이를 참조합니다. 클러스터 하나가 보통 여러 클래스를 갖습니다(빠른 SSD, 대용량 HDD, NFS, …).
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ebs-sc
provisioner: ebs.csi.aws.com
parameters:
type: gp3
fsType: ext4
encrypted: "true"
reclaimPolicy: Delete # Retain | Delete
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
mountOptions:
- noatime
# kubectl get storageclass기본 StorageClass
기본 StorageClass는 정확히 하나입니다(is-default-class: true 어노테이션). storageClassName을 생략한 PVC가 자동으로 이를 씁니다 — 어떤 백엔드를 받을지 신경 쓰지 않는 사용자에게 편리합니다. 어느 클래스가 표시됐는지는 kubectl get sc로 보세요(기본값).
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: standard
annotations:
storageclass.kubernetes.io/is-default-class: "true"
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
# a PVC with no storageClassName uses the default
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: auto
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 5Gi
# (no storageClassName set -> uses 'standard')프로비저너
kubernetes.io/no-provisioner는 정적 바인딩만을 의미합니다(동적 생성 없음). 실제 동적 프로비저닝은 모두 CSI 드라이버를 씁니다 — 클라우드 제공자가 자기 것을 제공하고(ebs.csi.aws.com 등), 셀프호스팅 옵션(Longhorn, Rook/Ceph, local-path)이 베어메탈을 커버합니다. 매개변수는 완전히 프로비저널 전용입니다.
# built-in (no external driver): only static binding
provisioner: kubernetes.io/no-provisioner
# cloud CSI drivers (dynamic):
provisioner: ebs.csi.aws.com # AWS EBS
provisioner: pd.csi.storage.gke.io # GCE PD
provisioner: disk.csi.azure.com # Azure Disk
provisioner: nfs.csi.k8s.io # NFS
# popular self-hosted:
provisioner: driver.longhorn.io # Longhorn
provisioner: rook-ceph.ceph.com # Rook/Ceph
provisioner: rancher.io/local-path # local-path (dev)
# parameters are provisioner-specific
# (e.g. AWS: type=gp3|iops=3000|encrypted=true)볼륨 바인딩 모드
Immediate 는 PVC가 만들어지는 순간 바인딩합니다 — pod가 다른 존에 놓일 수 있어 존형 디스크에는 위험합니다. WaitForFirstConsumer는 pod가 실제로 PVC를 소비할 때까지 바인딩을 미뤄 볼륨이 올바른 존에 놓이게 합니다. 존형 클라우드 디스크에는 항상 WaitForFirstConsumer를 쓰세요.
spec:
volumeBindingMode: WaitForFirstConsumer
# ^ default for many CSI drivers
# alternatives:
# volumeBindingMode: Immediate
# Immediate: PVC binds/provisions as soon as created
# risk: volume created in zone A, pod scheduled in zone B
# -> multi-attach / cross-zone latency issues
# WaitForFirstConsumer: delays binding until a pod using the PVC
# is scheduled. The PV is then created in the pod's zone.
# REQUIRED for topology-constrained backends (EBS, etc.)
# topology constraints come from the CSI driver via
# AllowedTopologiesStorageClass별 reclaim 정책
StorageClass.reclaimPolicy가 동적으로 프로비저닝하는 모든 PV의 정책을 정합니다. Delete(기본값)는 PVC 삭제 시 볼륨을 파괴합니다 — 효율적이지만 프로덕션 데이터에는 위험합니다. 데이터를 지키려 PVC 삭제 전에 PV를 Retain으로 바꾸거나 처음부터 Retain 클래스를 쓰세요.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ebs-temp
provisioner: ebs.csi.aws.com
reclaimPolicy: Delete # default for dynamic volumes
# reclaimPolicy: Retain # keep data after PVC delete
# the StorageClass policy becomes the PV's policy
# when a PV is dynamically provisioned
# to preserve data, either:
# 1. use a Retain StorageClass
# 2. patch the dynamically-created PV to Retain before deleting PVC:
kubectl patch pv pvc-xxxx -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
# then delete PVC safely; data survives볼륨 확장
allowVolumeExpansion: true는 사용자가 spec.resources.requests.storage를 편집해 PVC를 늘리게 합니다. CSI 드라이버가 기저 볼륨을 확장하고, kubelet이 다음 마운트 시 파일시스템을 확장합니다. 축소는 절대 지원되지 않습니다. 대부분의 클라우드 CSI 드라이버가 온라인 확장(언마운트 불필요)을 지원합니다.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ebs-sc
provisioner: ebs.csi.aws.com
allowVolumeExpansion: true # must be true to resize
# then resize by editing the PVC's requested size
kubectl patch pvc data-claim -p '{"spec":{"resources":{"requests":{"storage":"50Gi"}}}}'
# status.conditions shows Resizing / FileSystemResizePending
kubectl describe pvc data-claim
# requirements:
# - StorageClass.allowVolumeExpansion = true
# - driver supports online expansion (most CSI drivers do)
# - shrinking is NOT supported (only grow)
# - FilesystemResize happens after the PV is expandedHelm
Helm 설치 & 릴리스
Helm이 Kubernetes 매니페스트를 '차트'로 패키징하고 '릴리스'로 관리합니다. install이 릴리스를 만들고, upgrade가 변경을 적용하며, upgrade --install은 멱등입니다. 릴리스는 네임스페이스의 Secret/ConfigMap으로 추적됩니다 — rollback이 이렇게 동작합니다.
# add and update a chart repo
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
# search for charts
helm search repo nginx
helm search hub wordpress # searches Artifact Hub
# install a chart (creates a release)
helm install my-nginx bitnami/nginx --namespace web --create-namespace
# upgrade an existing release
helm upgrade my-nginx bitnami/nginx --set replicaCount=3
# upgrade + install in one idempotent command
helm upgrade --install my-nginx bitnami/nginx -f values.yaml
# uninstall
helm uninstall my-nginx -n web
# list releases
helm list -n web
helm list --all-namespaces차트 구조
차트는 템플릿화된 YAML 디렉터리와 기본값입니다. Chart.yaml이 메타데이터를 담고, values.yaml이 기본값을 담으며, templates/가 그 값들로 렌더링되는 Go 템플릿을 담습니다. helm create가 동작하는 차트를 뽑아냅니다. helm lint가 게시 전 스키마/템플릿 오류를 잡습니다.
my-chart/
├── Chart.yaml # chart metadata (name, version, apiVersion)
├── values.yaml # default values (overridable)
├── charts/ # chart dependencies (subcharts)
├── templates/ # Go-templated YAML
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── _helpers.tpl # named templates (partials)
│ └── NOTES.txt # post-install notes
├── templates.yaml # (optional) CRDs to install before templates
└── README.md
# create a new chart skeleton
helm create my-chart
# lint a chart
helm lint my-chart
# package into a .tgz
helm package my-chartValues & 오버라이드
values.yaml이 차트 기본값을 담습니다. 오버라이드는 --set(스칼라용)이나 -f(전체 파일용)로 하세요. helm show values가 차트가 받는 모든 키를 나열합니다. helm template은 클러스터를 건드리지 않고 매니페스트를 렌더링합니다 — 릴리스가 실제로 적용할 것을 diff하는 데 필수입니다.
# values.yaml (chart defaults)
image:
repository: nginx
tag: "1.25"
replicaCount: 2
service:
type: ClusterIP
port: 80
# override on the command line
helm upgrade --install web my-chart \
--set replicaCount=5 \
--set image.tag=1.26 \
--set service.type=LoadBalancer
# override from a file
helm upgrade --install web my-chart -f prod-values.yaml
# see all values a chart supports
helm show values bitnami/nginx
# rendered output (debug, no install)
helm template web my-chart -f prod-values.yaml템플릿 & 내장 객체
템플릿은 Sprig 함수가 있는 Go 템플릿 문법을 씁니다. .Release.Name이 모든 설치를 고유하게 만들고, .Values가 차트 값을 노출하며, .Chart가 Chart.yaml에서 가져옵니다. default 함수가 폴백을 줍니다. .Release.Name을 통한 안전한 렌더링 네이밍으로 하나의 차트가 같은 네임스페이스에서 많은 릴리스를 실행합니다.
# built-in template objects:
# .Values chart values (after overrides)
# .Release release metadata (Name, Namespace, Service, Revision, IsInstall, IsUpgrade)
# .Chart Chart.yaml contents
# .Files files in the chart
# .Capabilities cluster capabilities (KubeVersion, APIVersions)
# .Template current template info
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ .Release.Name }}-app
labels:
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
replicas: {{ .Values.replicaCount | default 1 }}
selector:
matchLabels:
app: {{ .Release.Name }}
template:
metadata:
labels:
app: {{ .Release.Name }}Helm 리포지터리
Helm 3는 클래식 HTTP 차트 리포와 OCI 레지스트리를 모두 지원합니다(helm push/pull oci://…). OCI가 현대적이고 서명 친화적인 경로입니다. helm repo update가 인덱스를 새로 고칩니다; 최신 차트 버전을 얻으려 upgrade 전에 항상 실행하세요. Artifact Hub(helm search hub)가 공개 차트를 색인합니다.
# add a chart repository
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo add jetstack https://charts.jetstack.io
# list configured repos
helm repo list
# update repo indexes
helm repo update
# remove a repo
helm repo remove bitnami
# push to OCI registry (Helm 3+)
helm registry login registry.example.com
helm package my-chart
helm push my-chart-0.1.0.tgz oci://registry.example.com/charts
# pull an OCI chart
helm pull oci://registry.example.com/charts/my-chart --version 0.1.0롤백 & 히스토리
모든 install/upgrade가 Secret으로 저장되는 번호가 매겨진 리비전을 만듭니다. helm rollback이 즉시 이전 리비전으로 전환합니다 — 일반 kubectl apply 대비 Helm의 킬러 기능입니다. helm get values가 실제 배포된 것을 보여주며, 흘러간 상태 디버깅에 매우 유용합니다.
# view release history
helm history my-nginx -n web
# rollback to a previous revision
helm rollback my-nginx 1 -n web
# get rendered manifests of a deployed release
helm get manifest my-nginx -n web
# get the values used at install/upgrade
helm get values my-nginx -n web
helm get values my-nginx -n web --all # incl. chart defaults
# get all info (hooks, manifest, values, notes)
helm get all my-nginx -n web
# wait for resources to be ready on install/upgrade
helm upgrade --install my-nginx bitnami/nginx --wait --timeout 5mNetworkPolicy
NetworkPolicy 매니페스트
NetworkPolicy가 pod용 방화벽 규 칙입니다. 빈 podSelector가 네임스페이스의 모든 pod를 선택하고, 빈 규칙 목록이 그 타입의 모든 트래픽을 거부합니다. NetworkPolicy는 가산적입니다 — 어떤 정책이든 허용하면 pod는 허용됩니다. 지원 CNI가 필요합니다; 일반 flannel은 무시합니다.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: prod
spec:
podSelector: {} # selects ALL pods in the namespace
policyTypes:
- Ingress
- Egress
# no ingress/egress rules => deny all traffic of that type
# effect: pods in 'prod' can't send or receive ANY traffic
# until another policy explicitly allows it
# REQUIRES a CNI that supports NetworkPolicy
# (Calico, Cilium, Weave, kube-router; NOT flannel alone)Ingress 규칙
Ingress 규칙이 선택된 pod로 들어오는 트래픽을 허용합니다. from 항목은 OR되고, 포트도 OR됩니다. podSelector가 같은 네임스페이스의 pod에 매칭되고, namespaceSelector가 전체 네임스페이스에 매칭합니다(자동 추가된 kubernetes.io/metadata.name 라벨을 쓰세요). 한 항목에 둘을 결합하면 AND됩니다.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-web
namespace: prod
spec:
podSelector:
matchLabels:
app: web
policyTypes:
- Ingress
ingress:
- from:
- podSelector: # pods in same namespace
matchLabels:
app: gateway
- namespaceSelector: # whole other namespace
matchLabels:
kubernetes.io/metadata.name: monitoring
- ipBlock: # external CIDR
cidr: 10.0.0.0/8
ports:
- protocol: TCP
port: 8080Egress 규칙
Egress 규칙이 선택된 pod가 무엇과 통신할 수 있는지 제어합니다. 흔한 함정: 기본 거부 egress가 DNS 해석을 깨뜨려 pod가 kube-dns에 닿지 못합니다. 나머지를 거부하기 전에 kube-system 네임스페이스로의 UDP/TCP 53을 항상 허용하세요. ipBlock.except가 예외를 냅니다.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-egress-dns
namespace: prod
spec:
podSelector:
matchLabels:
app: web
policyTypes:
- Egress
egress:
- to:
- namespaceSelector: {} # any namespace (kube-dns)
ports:
- protocol: UDP
port: 53
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 10.0.0.0/8 # allow internet, deny internal
ports:
- protocol: TCP
port: 443
# WARNING: egress deny-all blocks DNS and breaks pods.
# Always allow kube-dns first.셀렉터 & 네임스페이스 선택
맨 podSelector가 정책 자신의 네임스페이스의 pod에 매칭됩니다. namespaceSelector가 전체 네임스페이스에 매칭됩니다. 한 항목에 podSelector와 namespaceSelector를 둘 다 지정하면 AND됩니다(네임스페이스 Y에서 라벨 X인 pod) — 별개 항목으로 두면 OR됩니다. ipBlock이 외부 IP에 매칭됩니다.
spec:
podSelector: # selects pods in THIS namespace
matchLabels:
app: web
ingress:
- from:
# SAME namespace, matching pods
- podSelector:
matchLabels:
app: gateway
# DIFFERENT namespace (whole namespace)
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
# BOTH: pods in another namespace with specific labels
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: backend
podSelector:
matchLabels:
app: api
# external IP range
- ipBlock:
cidr: 192.168.1.0/24기본 정책 (전부 거부/허용)
기본 거부 정책(빈 규칙)이 네임스페이스를 잠가 명시적 허용 목록만 구멍을 엽니다. 기준선으로 deny-all ingress + deny-all egress를 적용한 뒤 타깃된 허용 정책을 추가하세요. 빈 ingress: [{}] 항목이 모든 ingress를 허용합니다 — 옵트아웃용 탈출구입니다.
# --- DEFAULT DENY INGRESS (in a namespace) ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: prod
spec:
podSelector: {}
policyTypes: [Ingress]
---
# --- DEFAULT DENY EGRESS ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-egress
namespace: prod
spec:
podSelector: {}
policyTypes: [Egress]
---
# --- ALLOW ALL INGRESS (whitelist opt-out) ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all-ingress
namespace: prod
spec:
podSelector: {}
policyTypes: [Ingress]
ingress:
- {} # allow from anywhere정책 타입 & 기본 동작
NetworkPolicy는 가산적입니다 — 어떤 정책이든 pod를 선택하면 그 트래픽 타입은 명시적 규칙이 허용하지 않는 한 pod에 대해 기본 거부가 됩니다. 정책이 전혀 없으면 모든 것이 열려 있습니다. pod의 라벨에 매칭되는 정책을 나열해 어떤 것이 트래픽을 지배하는지 보세요.
spec:
policyTypes:
- Ingress
- Egress
# if omitted, defaults are inferred:
# - Ingress is always present (a policy always affects ingress)
# - Egress is implied if any egress rule exists
# key behaviors:
# - policies are ADDITIVE: a pod is allowed if ANY matching
# policy permits the traffic
# - if NO policy selects a pod => all traffic allowed (default open)
# - if at least one policy selects a pod => default deny for that type
# unless an explicit rule allows it
# inspect effective policies for a pod
kubectl get networkpolicy -n prod -l app=webRBAC
Role (네임스페이스)
Role이 단일 네임스페이스 안의 네임스페이스화된 리소스에 권한을 부여합니다. rules가 apiGroups, resources, verbs를 나열합니다. pods/log가 서브리소스이고, pods/exec에는 create 동사가 필요합니다(exec가 서브리소스를 만들기 때문). '*'로 어떤 값이든 와일드카드하세요.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: dev
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
# a Role grants permissions WITHIN one namespace
# verbs: get, list, watch, create, update, patch, delete, deletecollection, "*"
# apiGroups: "" (core), "apps", "batch", "rbac.authorization.k8s.io", ...RoleBinding
RoleBinding이 Role(또는 하나의 네임스페이스로 스코프된 ClusterRole)을 주체에 부여합니다: User, Group, ServiceAccount. 바인딩은 권한이 적용되는 네임스페이스에 삽니다. roleRef는 불변입니다 — 참조된 Role을 바꾸려면 바인딩을 삭제하고 재생성하세요.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: dev
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount
name: my-sa
namespace: dev
- kind: Group
name: dev-team
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
# binds the Role to users, groups, or service accounts
# RoleBinding can also reference a ClusterRole (scoped to its namespace)ClusterRole & ClusterRoleBinding
ClusterRole이 클러스터 스코프 리소스(노드, 네임스페이스, PV)에 권한을 부여합니다 — Role은 이들을 건드릴 수 없습니다. ClusterRole은 재사용을 위해 RoleBinding으로 어떤 네임스페이스에도 바인딩될 수 있습니다(한 번 정의, 여러 번 바인딩). ClusterRoleBinding이 ClusterRole을 클러스터 전체에 부여합니다.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-reader
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: read-nodes
subjects:
- kind: ServiceAccount
name: monitor
namespace: kube-system
roleRef:
kind: ClusterRole
name: node-reader
apiGroup: rbac.authorization.k8s.io
# ClusterRole grants cluster-scoped resources (nodes, PVs, namespaces)
# or can be reused across namespaces via a RoleBinding동사, 리소스 & API 그룹
apiGroups가 리소스를 그룹화합니다 — core는 ''(빈 문자열)이고, apps가 Deployments/StatefulSets를, batch가 Jobs/CronJobs를 갖습니다. 서브리소스(pods/log, pods/exec, pods/portforward)는 별개 권한입니다. resourceNames가 규칙을 특정 인스턴스로 제한합니다. nonResourceURLs가 /healthz, /metrics 등을 커버합니다.
rules:
- apiGroups: [""] # core API group
resources: ["pods", "services", "configmaps", "secrets"]
verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
resources: ["deployments", "replicasets", "statefulsets"]
verbs: ["*"]
- apiGroups: ["batch"]
resources: ["jobs", "cronjobs"]
verbs: ["create", "delete", "get"]
- apiGroups: [""]
resources: ["pods/log", "pods/exec", "pods/portforward"]
verbs: ["get", "create"]
- nonResourceURLs: ["/healthz", "/healthz/*"] # non-resource URLs
verbs: ["get"]
# resourceNames: restrict to specific instances
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["my-config"]
verbs: ["get"]ServiceAccount
ServiceAccount가 pod용 정체입니다. serviceAccountName으로 할당하면 토큰이 /var/run/secrets/kubernetes.io/serviceaccount에 자동 마운트됩니다. 1.24부터 SA에는 영구 토큰 Secret이 없습니다 — 수명이 짧고 시간 제한이 있는 토큰에는 kubectl create token을 쓰세요. automountServiceAccountToken: false가 옵트아웃합니다.
# create a service account
kubectl create serviceaccount my-sa -n dev
# assign a RoleBinding (see RoleBinding example)
# mount the SA in a pod
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
serviceAccountName: my-sa
automountServiceAccountToken: false # opt out of token mount
containers:
- name: app
image: myapp:1.0
# short-lived tokens (1.24+) - no permanent secret
kubectl create token my-sa -n dev --duration=1h
# list SAs
kubectl get sa -n devkubectl auth can-i
kubectl auth can-i가 현재(또는 가장한) 사용자의 RBAC 권한을 검사합니다 — 'forbidden' 오류 디버깅에 필수입니다. --list가 허용된 모든 동사/리소스를 보여줍니다. --as가 테스트용으로 사용자/SA를 가장합니다. 내장 역할(view, edit, admin, cluster-admin)이 흔한 필요를 커버합니다.
# check if you can do something
kubectl auth can-i create pods -n dev
kubectl auth can-i delete deployments -n prod
# check on behalf of another user/SA
kubectl auth can-i list secrets --as=system:serviceaccount:dev:my-sa -n dev
# check all allowed verbs on a resource
kubectl auth can-i --list --as=alice -n dev
# whoami (1.25+)
kubectl auth whoami
# reconcile: detect over-privileged bindings
kubectl get rolebindings,clusterrolebindings --all-namespaces -o wide
# common built-in cluster roles:
# view, edit, admin, cluster-admin프로브 (Liveness/Readiness/Startup)
Liveness 프로브
liveness 프로브가 kubelet 에 언제 컨테이너를 재시작할지 알립니다. failureThreshold 연속 실패하면 kubelet이 컨테이너를 죽이고 재시작 정책이 적용됩니다. 교착이나 복구 불가능한 상태로부터의 회복에 쓰세요 — 의존성 검사는 아닙니다(그건 readiness).
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 15
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
successThreshold: 1
# if the probe fails failureThreshold times in a row,
# kubelet kills and restarts the container (per restartPolicy)Readiness 프로브
readiness 프로브가 pod가 Service로부터 트래픽을 받는지 제어합니다. 실패한 readiness 프로브가 pod의 IP를 엔드포인트에서 제거합니다 — 그러나 재시작하지는 않습니다. 예열(준비될 때까지 라우팅 금지)과 일시적 실패나 정상 종료 중 트래픽 배출에 쓰세요.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
# a failing readiness probe REMOVES the pod from service endpoints,
# but does NOT restart the container.
# use to drain traffic during deploys, warm-up, or transient outages.Startup 프로브
startup 프로브(1.18+)는 시작이 느린 앱(Java, 레거시 서버)용입니다. 실행되는 동안 liveness와 readiness가 비활성화됩니다 — 느린 부팅이 liveness로 죽지 않습니다. startup이 성공하면 liveness/readiness가 활성화됩니다. 부팅용으로는 긴 failureThreshold × periodSeconds 창을 쓰세요.
apiVersion: v1
kind: Pod
metadata:
name: slow-app
spec:
containers:
- name: app
image: myapp:1.0
startupProbe:
httpGet:
path: /startup
port: 8080
failureThreshold: 30
periodSeconds: 10 # up to 300s to start
livenessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 10
# while the startup probe runs, liveness/readiness are disabled.
# once startup succeeds, liveness/readiness take over.프로브 핸들러
세 핸들러 타입: httpGet(성공 = HTTP 2xx/3xx), tcpSocket(성공 = TCP 연결), exec(성공 = exit 0). gRPC 프로브(1.27+ GA)가 gRPC 서비스의 깔끔한 옵션입니다. httpGet을 권합니다 — 앱이 재시작 없이 '건강하 지만 바쁨'(503)을 신호할 수 있습니다. exec은 취약합니다(이미지에 셸/바이너리 필요).
# three handler types:
# 1. HTTP GET (most common) - success = 200-399
livenessProbe:
httpGet:
path: /healthz
port: 8080
httpHeaders:
- name: X-Custom
value: probe
scheme: HTTP
# 2. TCP socket - success = port open
livenessProbe:
tcpSocket:
port: 3306
# 3. Exec - success = exit code 0
livenessProbe:
exec:
command:
- /bin/sh
- -c
- "pg_isready -h localhost"
# gRPC (1.24+, alpha -> GA): use grpc probe
livenessProbe:
grpc:
port: 9090
service: my.package.Health프로브 매개변수
initialDelaySeconds가 첫 프로브를 미룹니다 — 그러나 느린 부팅 처리에는 startup 프로브가 더 깔끔합니다. periodSeconds가 주기이고, failureThreshold × periodSeconds가 액션 전까지 pod가 불건강할 수 있는 시간입니다. 빠른 페일오버에는 좁게, 관용에는 넓게. terminationGracePeriodSeconds가 종료를 제한합니다.
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 15 # wait before first probe (after start)
periodSeconds: 10 # probe every 10s
timeoutSeconds: 2 # max time per probe
successThreshold: 1 # consecutive successes to mark OK
failureThreshold: 3 # consecutive failures to mark failed
terminationGracePeriodSeconds: 30 # (liveness) grace before SIGKILL
# tuning tips:
# - set initialDelaySeconds > typical startup time
# - OR use a startup probe instead (cleaner)
# - shorter period = faster reaction, more load
# - higher failureThreshold = more tolerant of blips프로브 실패 동작
liveness 실패는 컨테이너를 제자리에서 죽이고 재시작합니다(재스케줄되지 않음). readiness 실패는 pod를 서비스에서 제거할 뿐입니다 — 재시작 없음. startup 실패는 liveness처럼 동작합니다. 들쭉날쭉한 liveness는 느린 하류 서비스에 의존하는 프로브에서 흔히 옵니다 — 헬스 검사는 로컬에 두고 저렴하게 유지하세요.
# --- LIVENESS FAIL ---
# container killed -> restarted (per restartPolicy: Always/OnFailure)
# pod stays on the same node (NOT rescheduled)
# CrashLoopBackOff if it keeps failing
# --- READINESS FAIL ---
# pod stays running, but is REMOVED from Service endpoints
# no traffic until it succeeds again
# NOT restarted by kubelet
# --- STARTUP FAIL ---
# container killed and restarted (like liveness)
# liveness/readiness never activate
# after failureThreshold × periodSeconds, pod is stuck restarting
# check probe results:
kubectl describe pod app | grep -A5 "Last State"
kubectl get pod app -o jsonpath='{.status.containerStatuses[*].state}'
# common cause of flapping: liveness probe hitting a slow dependency리소스 & 고급 kubectl
Requests & Limits
requests가 스케줄러가 예약하는 것입니다(노드에 여유 requests가 있어야 pod가 스케줄됨) — 정상 상태 필요량으로 설정하세요. limits가 하드 상한입니다: CPU는 스로틀되고 메모리는 OOMKilled됩니다. cpu는 코어 단위(500m = 0.5)이고, memory는 바이트 단위(Mi/Gi)입니다. 프로덕션에서는 항상 둘 다 설정하세요.
spec:
containers:
- name: app
image: myapp:1.0
resources:
requests: # what the scheduler guarantees (reservation)
cpu: 250m # 250 millicores = 0.25 core
memory: 256Mi # 256 mebibytes
ephemeral-storage: 1Gi
limits: # hard ceiling (enforced)
cpu: "1" # 1 core
memory: 512Mi
ephemeral-storage: 2Gi
# cpu limit: throttled (cfs quota)
# memory limit: OOMKilled if exceeded
# ephemeral-storage limit: evicted if exceeded
# request only (no limit): best-effort burstLimitRange 기본값
LimitRange가 지정하지 않는 pod에 기본 requests/limits를 적용합니다 — ResourceQuota가 requests를 요구할 때 결정적입니다. max/min이 단일 컨테이너의 크기를 제한합니다. maxLimitRequestRatio가 컨테이너가 request 위로 얼마나 튈 수 있는지 제한해 시끄러운 이웃을 막습니다.
apiVersion: v1
kind: LimitRange
metadata:
name: defaults
namespace: prod
spec:
limits:
- type: Container
default: # applied as LIMITS when not set
cpu: 500m
memory: 512Mi
defaultRequest: # applied as REQUESTS when not set
cpu: 100m
memory: 128Mi
max: # max allowed LIMITS
cpu: "4"
memory: 8Gi
min: # min allowed REQUESTS
cpu: 50m
memory: 64Mi
maxLimitRequestRatio: # limit/request ratio cap (burst cap)
cpu: "4"
# a pod with no resources gets default/defaultRequest applied
# a pod with limit=4cpu, request=50m would breach maxLimitRequestRatioHorizontal Pod Autoscaler
HPA가 메트릭 기반으로 복제본을 스케일합니다(CPU/메모리는 metrics-server 경유, 커스텀/외부는 Prometheus Adapter 경유). behavior(v2)가 공격성을 조율합니다: stabilizationWindowSeconds가 플래핑을 막고, policies가 분당 속도를 제한합니다. 스케일업은 보통 빠르고 공격적이며, 스케일다운은 의도적으로 느립니다.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 3
maxReplicas: 50
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization # avg across pods
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior: # (v2) scale up/down tuning
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50 # max 50% down per minute
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 60
# requires metrics-server for CPU/memory
kubectl get hpa web -wPod Disruption Budget
PodDisruptionBudget이 집합의 pod가 한 번에 자발적으로 축출될 수 있는 수를 제한합니다 — 노드 배출과 cluster-autoscaler 액션 중 가용성을 지킵니다. minAvailable이나 maxUnavailable(둘 다 아님)을 쓰세요. 비자발적 중단(하드웨어 실패)은 막지 않습니다 — 그건 복제본만이 합니다.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web-pdb
namespace: prod
spec:
minAvailable: 2 # at least 2 pods always available
# OR
# maxUnavailable: 1 # at most 1 down at a time
selector:
matchLabels:
app: web
# PDB protects against VOLUNTARY disruptions:
# - kubectl drain (node maintenance)
# - cluster autoscaler evictions
# - kubectl delete pod (controller-managed)
# It does NOT prevent INVOLUNTARY disruptions (node failure, kernel panic).
# check PDB status
kubectl get pdb -n prod
kubectl describe pdb web-pdb -n prodTaint, Toleration & Affinity
Taint가 pod를 밀어내고, tolerations가 특정 pod가 이를 무시하게 합니다 — 노드 전용화(GPU, 인그레스, 컨트롤 플레인)에 쓰세요. nodeAffinity가 특정 노드를 선호하거나 요구합니다. podAntiAffinity가 HA를 위해 복제본을 토폴로지 도메인(호스트, 존)에 걸쳐 퍼뜨립니다. taint 제거는 같은 키+효과에 뒤에 대시를 붙여 합니다.
# taint a node
kubectl taint nodes node-1 dedicated=gpu:NoSchedule
# tolerate the taint so a pod can schedule there
spec:
tolerations:
- key: dedicated
operator: Equal
value: gpu
effect: NoSchedule
# prefer specific nodes
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: disktype
operator: In
values: [ssd]
podAntiAffinity: # spread replicas across nodes
requiredDuringSchedulingIgnoredDuringExecution:
- topologyKey: kubernetes.io/hostname
labelSelector:
matchLabels:
app: web
# remove a taint
kubectl taint nodes node-1 dedicated=gpu:NoSchedule-고급 kubectl (patch/wait/top/debug)
patch가 JSON, strategic-merge, merge 타입을 지원합니다. wait이 조건이 충족될 때까지 막습니다 — 스크립트에 완벽합니다. top이 실시간 CPU/메모리를 보여줍니다(metrics-server 필요). kubectl debug가 실행 중인 pod에 임시 컨테이너를 붙이거나(distroless 이미지에 좋음) 노드에서 셸을 엽니다.
# JSON patch (precise field ops)
kubectl patch deployment web --type json -p \
'[{"op":"replace","path":"/spec/replicas","value":3}]'
# strategic merge patch (default for k8s objects)
kubectl patch svc web -p '{"spec":{"type":"NodePort"}}'
# wait for a condition
kubectl wait --for=condition=Ready pod/web --timeout=60s
kubectl wait --for=delete pod/web --timeout=30s
# resource usage (needs metrics-server)
kubectl top nodes
kubectl top pods -n prod
kubectl top pod web --containers
# ephemeral debug container (1.25+)
kubectl debug -it web --image=busybox --target=web
# debug a node
kubectl debug node/node-1 -it --image=ubuntu
# run a one-off pod
kubectl run tmp --rm -it --image=alpine -- sh
# explain a field
kubectl explain pod.spec.containers.resources관련 Kubernetes 스니펫
Copy-paste ready code for common tasks.
Pod Manifest
Define a standalone Pod with a container, env, and probe.
Deployment & Rollout
Manage a replicated, rolling-updated workload.
Service Types
Expose Pods via ClusterIP, NodePort, and LoadBalancer services.
ConfigMap & Secret
Inject configuration and sensitive data into containers.
Ingress Routing
Route external HTTP traffic to services by host and path.
Labels & Selectors
Tag resources and query them with selectors.
kubectl Basics
Common kubectl commands for everyday operations.
Namespaces
Partition a cluster into isolated virtual clusters.
Was this helpful?