Kubernetes CrashLoopBackOff·Pending·OOMKilled 진단 순서
Kubernetes에서 Pending, ImagePullBackOff, CrashLoopBackOff, OOMKilled(137) 장애가 발생했을 때 5분 안에 원인을 좁히는 진단 순서와 distroless 컨테이너용 kubectl debug 사용법을 kind 클러스터에서 검증합니다.
Kubernetes 배포 직후 Pod가
Pending,ImagePullBackOff,CrashLoopBackOff,OOMKilled중 하나에 멈췄을 때, 증상만 보고 설정을 추측해 수정하면 원인 파악이 길어집니다. 이 글에서는get pods→get events→describe→logs순으로 5분 안에 원인을 특정하는 흐름과 셸이 없는 distroless 컨테이너를 진단하는kubectl debug사용법을 로컬kind클러스터에서 직접 재현해 정리합니다.
본문의 모든 명령과 출력은 로컬 2노드
kind+ Calico 클러스터(Kubernetesv1.37.0,kubectl v1.36.1,containerd://2.3.4)에서 공개 테스트 이미지로 실행해 관찰한 결과입니다.
1. 5분 진단 순서와 장애별 증상 분기
Pod가 정상 기동(Running, READY 1/1)에 도달하기까지는 크게 스케줄링(노드 배정) → 이미지 Pull → 컨테이너 실행 유지 세 단계를 거칩니다. 장애가 어느 단계에서 멈췄는지만 먼저 가르면 확인해야 할 명령과 필드가 즉시 좁혀집니다.
flowchart TD
A["1. kubectl get pods -o wide"] --> B{"NODE 배정 여부"}
B -->|"미배정 (Pending)"| C["describe: FailedScheduling"]
B -->|"배정됨 (ImagePull)"| D["describe: Pull 오류"]
B -->|"배정됨 (Crash/OOM)"| E["describe Exit Code + logs"]
E -->|"셸 없는 distroless"| F["kubectl debug --target"]
실제 장애가 겹쳐 발생할 때는 개별 Pod를 하나씩 열기 전에 kubectl get pods -o wide와 시간순 이벤트 목록(kubectl get events --sort-by='.lastTimestamp')을 먼저 확인하는 편이 빠릅니다. 아래 표는 4대 장애가 각 단계에서 남기는 핵심 단서를 정리한 것입니다.
상태 (STATUS) | 막힌 단계 | NODE 배정 | describe 핵심 확인 필드 | 1차 확인 명령 |
|---|---|---|---|---|
Pending | 스케줄링 | <none> | PodScheduled: False, FailedScheduling 이벤트 | kubectl describe pod |
ImagePullBackOff | 이미지 Pull | 배정됨 | Waiting (ImagePullBackOff), Failed to pull image | kubectl describe pod |
CrashLoopBackOff | 앱 실행·종료 | 배정됨 | Last State: Terminated, Reason: Error, Exit Code: 1 | kubectl logs --previous |
OOMKilled | 메모리 상한 초과 | 배정됨 | Terminated, Reason: OOMKilled, Exit Code: 137 | kubectl describe pod |
로컬 kind 클러스터의 전용 네임스페이스(lab-d4-debug)에 4가지 장애 Pod와 정상 distroless Pod를 동시에 배포한 뒤 22초·38초 시점에 조회한 결과입니다.
1
kubectl get pods -n lab-d4-debug -o wide
1
2
3
4
5
6
7
8
9
10
# 배포 22초 후
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-crashloop 0/1 Error 2 (14s ago) 22s 192.168.25.134 k8s-lab2-worker <none> <none>
pod-distroless 1/1 Running 0 22s 192.168.25.136 k8s-lab2-worker <none> <none>
pod-imagepull 0/1 ImagePullBackOff 0 22s 192.168.25.133 k8s-lab2-worker <none> <none>
pod-oom 0/1 CrashLoopBackOff 1 (12s ago) 22s 192.168.25.135 k8s-lab2-worker <none> <none>
pod-pending 0/1 Pending 0 22s <none> <none> <none> <none>
# 배포 38초 후 (pod-oom 재실행 직후)
pod-oom 0/1 OOMKilled 2 (28s ago) 38s 192.168.25.135 k8s-lab2-worker <none> <none>
pod-pending만 IP와 NODE가 <none>이고, 나머지 4개 Pod는 모두 k8s-lab2-worker에 스케줄링된 상태입니다. 이어서 네임스페이스 전체 이벤트를 시간순으로 정렬하면 4대 장애의 발생 순서와 원인이 한 화면에 모입니다.
1
kubectl get events -n lab-d4-debug --sort-by='.lastTimestamp'
1
2
3
4
5
6
7
8
9
LAST SEEN TYPE REASON OBJECT MESSAGE
38s Normal Scheduled pod/pod-oom Successfully assigned lab-d4-debug/pod-oom to k8s-lab2-worker
38s Warning FailedScheduling pod/pod-pending 0/2 nodes are available: 1 Insufficient cpu, 1 Insufficient memory, 1 node(s) had untolerated taint(s).
38s Normal Scheduled pod/pod-imagepull Successfully assigned lab-d4-debug/pod-imagepull to k8s-lab2-worker
36s Normal BackOff pod/pod-imagepull Back-off pulling image "nginx:nonexistent-tag-9999"
36s Warning Failed pod/pod-imagepull Error: ImagePullBackOff
16s Warning BackOff pod/pod-crashloop Back-off restarting failed container app in pod pod-crashloop_lab-d4-debug(...)
13s Warning BackOff pod/pod-oom Back-off restarting failed container worker in pod pod-oom_lab-d4-debug(...)
10s Warning Failed pod/pod-imagepull Failed to pull image "nginx:nonexistent-tag-9999": rpc error: code = NotFound ... docker.io/library/nginx:nonexistent-tag-9999: not found
2. 스케줄링과 이미지 단계: Pending과 ImagePullBackOff
Pending: 노드에 배정되지 못한 상태
Pending은 컨테이너가 아직 시작되지 않았으므로 kubectl logs를 쳐도 출력이 없습니다. kubectl describe pod의 Conditions와 하단 Events에서 default-scheduler가 남긴 FailedScheduling 메시지를 바로 읽어야 합니다.
워커 노드 가용량을 초과하는 requests.cpu: "64", requests.memory: "512Gi"를 요청한 pod-pending의 describe 출력입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Node: <none>
Status: Pending
Containers:
web:
Requests:
cpu: 64
memory: 512Gi
Conditions:
Type Status
PodScheduled False
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedScheduling 38s default-scheduler 0/2 nodes are available: 1 Insufficient cpu, 1 Insufficient memory, 1 node(s) had untolerated taint(s). preemption: 0/2 nodes are available: 2 Preemption is not helpful for scheduling.
클러스터 2개 노드 중 1개(control-plane)는 taint 때문에 제외되었고, 나머지 워커 노드 1대는 CPU와 메모리가 부족해 배정이 거부되었음을 정확히 보여줍니다.
참고로 이번 실험에서 직접 재현하지 않은 확장 사례로, PersistentVolumeClaim이 Bound 상태가 아니거나 nodeSelector·affinity 조건을 만족하는 노드가 없을 때도 Pod는 Pending에 머무릅니다. PVC 바인딩과 스토리지 설계는 Kubernetes PV·PVC·StorageClass와 StatefulSet 글에서 별도로 다루었습니다.
ImagePullBackOff: 스케줄링 후 이미지 다운로드 실패
ImagePullBackOff는 노드 배정(PodScheduled: True)까지는 성공했지만 kubelet이 컨테이너 런타임(containerd)을 통해 이미지를 가져오지 못해 지수 백오프(exponential backoff)로 재시도 중인 상태입니다. 처음 실패할 때는 ErrImagePull이 뜨고, 재시도 대기 구간에 들어가면 ImagePullBackOff로 바뀝니다.
존재하지 않는 태그(nginx:nonexistent-tag-9999)를 지정한 pod-imagepull의 describe 결과입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
Status: Pending
Containers:
web:
Image: nginx:nonexistent-tag-9999
State: Waiting
Reason: ImagePullBackOff
Ready: False
Restart Count: 0
Events:
Normal Scheduled 38s default-scheduler Successfully assigned lab-d4-debug/pod-imagepull to k8s-lab2-worker
Warning Failed 36s kubelet spec.containers{web}: Error: ImagePullBackOff
Warning Failed 10s (x2 over 36s) kubelet spec.containers{web}: Failed to pull image "nginx:nonexistent-tag-9999": rpc error: code = NotFound desc = failed to pull and unpack image "docker.io/library/nginx:nonexistent-tag-9999": failed to resolve reference "docker.io/library/nginx:nonexistent-tag-9999": docker.io/library/nginx:nonexistent-tag-9999: not found
Warning Failed 10s (x2 over 36s) kubelet spec.containers{web}: Error: ErrImagePull
여기서 rpc error: code = NotFound가 이미지 경로 또는 태그 오타를 뜻합니다. 이번 실험은 공개 레지스트리(Docker Hub)의 태그 부재만 실측했지만, 실무 프라이빗 레지스트리(ECR, GCR, GHCR 등)에서 imagePullSecrets가 누락되거나 토큰이 만료되면 NotFound 대신 unauthorized 또는 pull access denied 계열 메시지가 기록됩니다.
3. 런타임 종료 단계: CrashLoopBackOff와 OOMKilled(137)
컨테이너가 일단 시작된 뒤 반복적으로 종료되면 kubelet은 재시작 간격을 늘려가며 CrashLoopBackOff 상태로 전환합니다. 이때 가장 먼저 구분해야 할 것은 애플리케이션이 스스로 에러 코드(Exit Code: 1 등)로 종료했는지, 커널 OOM Killer가 강제 종료(Exit Code: 137)했는지입니다.
CrashLoopBackOff: 종료 코드와 직전 로그 확인
필수 환경변수(DATABASE_URL)가 비어 있으면 표준 에러에 로그를 남기고 exit 1로 종료하는 pod-crashloop의 describe 결과입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
State: Terminated
Reason: Error
Exit Code: 1
Started: Sat, 05 Dec 2026 23:58:18 +0900
Finished: Sat, 05 Dec 2026 23:58:19 +0900
Last State: Terminated
Reason: Error
Exit Code: 1
Started: Sat, 05 Dec 2026 23:58:04 +0900
Finished: Sat, 05 Dec 2026 23:58:05 +0900
Ready: False
Restart Count: 2
Events:
Warning BackOff 16s (x2 over 29s) kubelet spec.containers{app}: Back-off restarting failed container app in pod pod-crashloop_lab-d4-debug(...)
애플리케이션이 왜 exit 1을 반환했는지 확인하려면 직전 종료 컨테이너의 로그를 kubectl logs --previous로 조회합니다. 2초간 실행 후 종료되도록 구성한 확인용 Pod(pod-crashloop-check)가 1회 재시작된 직후(Running, RESTARTS 1)에 두 명령을 비교한 결과입니다.
1
2
kubectl logs pod-crashloop-check -n lab-d4-debug --previous
kubectl logs pod-crashloop-check -n lab-d4-debug
1
2
3
4
5
6
# --previous 출력 (직전 종료 컨테이너)
[BOOT] 15:01:02 starting api-server...
[FATAL] 15:01:04 required env DATABASE_URL is missing
# 플래그 없는 logs 출력 (방금 새로 뜬 컨테이너)
[BOOT] 15:01:05 starting api-server...
kubectl logsvskubectl logs --previous시점 주의
이번Kubernetes v1.37.0+containerd://2.3.4실측에서 컨테이너가 재시작되어State: Running또는Waiting (CrashLoopBackOff)상태일 때는--previous가 직전 종료 로그를 정상 반환했습니다. 반면 현재 컨테이너 자체가State: Terminated로 표시되는 순간에는 플래그 없는kubectl logs <pod>가 가장 최근 종료된 컨테이너의 로그를 바로 출력했고, 이때--previous를 주면 그보다 한 번 더 이전 컨테이너가 이미 GC되어unable to retrieve container logs for containerd://...에러가 반환되는 현상을 확인했습니다. 실무에서는--previous를 먼저 실행하되unable to retrieve가 나오면 플래그 없이kubectl logs <pod>를 함께 확인하는 습관이 안전합니다.
참고로 사이드카 등이 함께 들어 있는 멀티 컨테이너 Pod에서는 -c <container-name> 옵션을 생략하면 어떤 컨테이너 로그를 볼지 지정하라는 오류가 발생합니다(이번 실험에서는 단일 컨테이너 Pod만 실측했습니다).
OOMKilled: Exit Code: 137과 cgroup 메모리 상한
pod-oom은 limits.memory: 32Mi로 제한된 python:3.12-alpine 컨테이너 안에서 50MiB bytearray를 할당하도록 구성했습니다. 배포 직후에는 CrashLoopBackOff로 보이다가 재실행 직후 OOMKilled가 표시되며, describe에서는 Reason: OOMKilled와 Exit Code: 137(128 + SIGKILL 9)이 명확히 남습니다.
1
2
3
4
5
6
7
8
9
10
11
State: Terminated
Reason: OOMKilled
Exit Code: 137
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
Restart Count: 2
Limits:
memory: 32Mi
Requests:
memory: 16Mi
1
kubectl logs pod-oom -n lab-d4-debug
1
[WORKER] Allocating 50MiB inside 32Mi limit...
커널이 SIGKILL로 프로세스를 즉시 끊었기 때문에 애플리케이션 로그에는 스택 트레이스나 예외 메시지 없이 직전 출력 한 줄만 남습니다. 따라서 로그가 갑자기 끊겼다면 반드시 describe의 Exit Code와 Reason을 확인해야 합니다.
이 결과는 Linux cgroup v2 메모리 상한에 의한 커널 OOM Killer 동작입니다. 반면 JVM 프로세스가 -Xmx 한도 안에서 자체 OutOfMemoryError를 던지고 종료하는 확장 사례에서는 커널이 죽인 것이 아니므로 Exit Code: 137 대신 Exit Code: 1이 나올 수 있습니다. 컨테이너 메모리 상한과 JVM 힙·오버헤드 계산, 그리고 Probe 설정이 재시작에 미치는 영향은 Docker 컨테이너 리소스 제한 설정과 JVM OOMKilled(137) 대응과 Kubernetes Probe와 리소스 제한, preStop 무중단 종료 설정에서 자세히 다루었습니다.
4. 셸 없는 distroless 컨테이너 진단: kubectl debug
보안과 이미지 경량화를 위해 프로덕션에서는 gcr.io/distroless/* 같은 최소 이미지를 자주 사용합니다. 이런 컨테이너에는 /bin/sh, ps, netstat, curl이 모두 들어 있지 않아 kubectl exec가 동작하지 않습니다.
실제로 gcr.io/distroless/python3-debian12 이미지로 띄운 pod-distroless에 kubectl exec를 실행하면 즉시 실패합니다.
1
kubectl exec -n lab-d4-debug pod-distroless -- sh -c "ps aux"
1
error: Internal error occurred: Internal error occurred: error executing command in container: failed to exec in container: failed to start exec "...": OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH
이때 기존 Pod를 재시작하거나 디버깅 도구가 든 새 이미지를 다시 빌드하지 않고도 진단할 수 있는 공식 기능이 Ephemeral Containers(kubectl debug, Kubernetes 1.25+ GA)입니다. --target=<container> 옵션을 주면 임시 디버그 컨테이너가 타깃 컨테이너와 프로세스·네트워크 네임스페이스를 공유한 채 같은 Pod 안에 붙습니다.
1
2
3
4
kubectl debug -it -n lab-d4-debug pod-distroless \
--image=busybox:1.36 \
--target=app \
-- sh -c 'ps aux; netstat -tlnp; wget -qO- http://127.0.0.1:8080/ | head -n 8'
실측에서 busybox:1.36 임시 컨테이너(debugger-mxpnl)를 붙여 확인한 출력입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--- ps aux ---
PID USER TIME COMMAND
1 root 0:00 /usr/bin/python3.11 -m http.server 8080
17 root 0:00 sh -c ...
27 root 0:00 ps aux
--- netstat -tlnp ---
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 1/python3.11
--- HTTP check to 127.0.0.1:8080 ---
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Directory listing for /</title>
</head>
distroless 이미지에 셸이 전혀 없는데도 ps aux에서 타깃 앱의 PID 1(/usr/bin/python3.11 -m http.server 8080)과 8080 리슨 소켓, 로컬 루프백(127.0.0.1:8080) HTTP 응답까지 한 번에 검증할 수 있습니다.
kubectl debug 사용 시 알아둘 제약과 주의점
- 비대화형 실행 시 로그 확인: 대화형 터미널에서는
-it로 바로 출력과 셸 조작이 가능합니다. 반면 CI 스크립트나 TTY가 없는 비대화형 셸에서kubectl debug -i ... -- sh -c '...'처럼 짧은 일회성 명령을 실행하면 터미널 attach 전에 명령이 먼저 종료될 수 있습니다. 이때 실행 결과는 사라지지 않고 임시 컨테이너 로그(kubectl logs <pod> -c <debugger-name>)에 그대로 남습니다. - 언제
kubectl debug를 쓰지 말아야 하는가: Ephemeral Container는 한 번 Pod에 추가되면 Pod가 삭제될 때까지 스펙에서 제거되지 않으며, 컨테이너가 계속 죽고 있는CrashLoopBackOff상태에서는 타깃 프로세스 네임스페이스 공유(--target)가 안정적으로 유지되지 않습니다. 또한 운영 클러스터에서는 RBAC(pods/ephemeralcontainersupdate 권한)과 Pod Security Admission 정책에 따라 임시 컨테이너 주입이 차단될 수 있습니다. 크래시가 반복되는 Pod는--target대신kubectl debug <pod> --copy-to=debug-pod --share-processes -- sleep 3600처럼 복사본을 만들어 명령을 바꿔 기동하는 편이 안전합니다.
5. 로컬 kind 클러스터 재현 매니페스트
위 5가지 시나리오를 로컬 kind 클러스터에서 그대로 재현할 수 있는 매니페스트(faults.yaml)입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# faults.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-imagepull
namespace: lab-d4-debug
spec:
containers:
- name: web
image: nginx:nonexistent-tag-9999
---
apiVersion: v1
kind: Pod
metadata:
name: pod-pending
namespace: lab-d4-debug
spec:
containers:
- name: web
image: nginx:1.27-alpine
resources:
requests:
cpu: "64"
memory: "512Gi"
---
apiVersion: v1
kind: Pod
metadata:
name: pod-crashloop
namespace: lab-d4-debug
spec:
containers:
- name: app
image: busybox:1.36
command:
- sh
- -c
- |
echo "[BOOT] starting api-server..."
if [ -z "$DATABASE_URL" ]; then
echo "[FATAL] required env DATABASE_URL is missing" >&2
sleep 1
exit 1
fi
sleep 3600
---
apiVersion: v1
kind: Pod
metadata:
name: pod-oom
namespace: lab-d4-debug
spec:
containers:
- name: worker
image: python:3.12-alpine
command:
- python
- -c
- |
import time
print("[WORKER] Allocating 50MiB inside 32Mi limit...", flush=True)
buf = bytearray(50 * 1024 * 1024)
time.sleep(60)
resources:
requests:
memory: "16Mi"
limits:
memory: "32Mi"
---
apiVersion: v1
kind: Pod
metadata:
name: pod-distroless
namespace: lab-d4-debug
spec:
containers:
- name: app
image: gcr.io/distroless/python3-debian12
args: ["-m", "http.server", "8080"]
ports:
- containerPort: 8080
네임스페이스를 분리해 배포하고 확인이 끝나면 네임스페이스 단위로 깔끔하게 정리합니다.
1
2
3
4
5
6
kubectl create namespace lab-d4-debug
kubectl apply -f faults.yaml
kubectl wait --for=condition=Ready pod/pod-distroless -n lab-d4-debug --timeout=90s
# 진단 완료 후 정리
kubectl delete namespace lab-d4-debug --timeout=90s
6. 운영 함정과 장애 대응 체크리스트
프로덕션 이벤트 보관 기한 주의
Kubernetes의 기본 이벤트(Event)는 etcd에 약 1시간(기본--event-ttl=1h)만 유지됩니다. 야간이나 새벽에 발생한FailedScheduling·OOMKilled원인은 아침에kubectl get events로 조회해도 이미 사라졌을 수 있으므로, 운영 클러스터에서는 이벤트 exporter나 중앙 로그 수집 파이프라인으로 이벤트를 별도 적재해 두어야 합니다.
장애 알림을 받았을 때 아래 5단계 순서대로 확인하면 추측성 재배포 없이 원인을 빠르게 좁힐 수 있습니다.
get pods -o wide로 단계 분류:NODE가<none>이면 스케줄링(Pending), 배정됐다면 이미지 Pull 또는 런타임 종료 단계로 즉시 분기합니다.get events --sort-by='.lastTimestamp'로 타임라인 확보: 여러 Pod가 동시에 흔들릴 때 가장 먼저 발생한Warning이벤트부터 역추적합니다.describe pod에서Reason과Exit Code확인:FailedScheduling,NotFound/unauthorized,Exit Code: 1(앱 오류),Exit Code: 137(OOMKilled) 중 정확히 무엇인지 수치와 원문으로 확정합니다.logs --previous와 일반logs병행 조회:State: Terminated시점에--previous가unable to retrieve를 반환하면 플래그 없이kubectl logs를 확인하고, 멀티 컨테이너 Pod라면-c <container>를 명시합니다.- distroless·경량 이미지는
kubectl debug --target활용:kubectl exec가executable file not found로 막히면 임시 컨테이너로 프로세스·포트·로컬 엔드포인트를 점검하고, 비대화형 실행 시에는kubectl logs <pod> -c <debugger-name>으로 출력을 회수합니다.