Cloud Native › Kubernetes

Kubernetes Probe와 리소스 제한, preStop 무중단 종료 설정

Kubernetes의 startup·readiness·liveness Probe 동작 차이, QoS 클래스와 OOMKilled(137), preStop 훅 기반 무중단 종료 순서를 kind 클러스터에서 검증합니다.

Kubernetes Probe와 리소스 제한, preStop 무중단 종료 설정

로컬 Docker Compose에서는 문제없이 뜨던 백엔드 서비스가 Kubernetes로 올라간 뒤 기동 직후 CrashLoopBackOff에 빠지거나, 배포할 때마다 순간적인 502 에러와 OOMKilled(137)를 겪는 일이 잦습니다. 이 글에서는 3종 Probe(startup, readiness, liveness)의 역할 분리, requests/limits 기반 QoS 클래스와 메모리 초과 종료, 그리고 preStop 훅을 활용한 무중단 종료 순서를 로컬 kind 클러스터에서 직접 재현해 정리합니다.

본문의 모든 명령과 출력은 로컬 3노드 kind 클러스터(kind v0.33.0, Kubernetes v1.37.0, kubectl v1.36.1, containerd://2.3.4)에서 busybox:1.36과 python:3.12-alpine 이미지로 실행해 확인한 결과입니다.


1. Readiness·Liveness·Startup Probe의 역할 분리

단일 컨테이너 환경에서는 Docker HEALTHCHECK와 Spring Boot Actuator 연동처럼 하나의 헬스체크로 상태를 판별하지만, Kubernetes는 장애 복구와 트래픽 제어를 세 가지 Probe로 분리합니다. 같은 실패라도 kubelet이 취하는 조치가 완전히 다르기 때문입니다.

Probe 종류점검 대상실패 시 kubelet 조치적합한 용도피해야 할 안티패턴
startupProbe최초 기동 완료 여부임계치 초과 시 컨테이너 재시작JVM·캐시 워밍업 등 초기 기동이 느린 앱 보호기동이 1~2초 내 끝나는 경량 프로세스에 불필요한 중복 설정
readinessProbe트래픽 수신 가능 여부재시작 없이 EndpointSlice에서 제외DB 풀 초기화 대기, 일시적 과부하 시 트래픽 차단체크 주기를 너무 길게 잡아 장애 Pod로 요청이 계속 유입되는 구성
livenessProbe프로세스 교착·회복 불가 상태컨테이너 종료 후 재시작(RESTARTS 증가)데드락, 이벤트 루프 정지 등 재시작으로만 풀리는 장애외부 DB·Redis·타 API 상태를 포함해 연쇄 재시작을 유발하는 구성

특히 외부 의존성 상태를 livenessProbe에 넣지 않는 원칙이 중요합니다. 외부 DB가 10초간 순단됐을 때 모든 Pod의 livenessProbe가 동시에 실패하면, 멀쩡한 애플리케이션 컨테이너까지 일제히 재시작되면서 기동 부하가 겹치는 연쇄 장애로 이어집니다. 일시적인 의존성 장애로 트래픽만 빼야 할 때는 readinessProbe를 사용하고, livenessProbe는 프로세스 내부가 스스로 복구할 수 없는 교착 상태만 감지하도록 좁혀야 합니다.

readinessProbe와 livenessProbe의 조치 차이를 확인하기 위해 파일 존재 여부(/tmp/ready, /tmp/alive)로 상태를 제어하는 Pod와 ClusterIP Service를 배포해 보았습니다.

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
# probes-demo.yaml
apiVersion: v1
kind: Service
metadata:
  name: probe-svc
  namespace: lab-d4-lifecycle
spec:
  type: ClusterIP
  selector:
    app: probe-demo
  ports:
    - name: http
      port: 80
      targetPort: 8080
---
apiVersion: v1
kind: Pod
metadata:
  name: probe-demo
  namespace: lab-d4-lifecycle
  labels:
    app: probe-demo
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "touch /tmp/ready /tmp/alive && echo 'started' && sleep 3600"]
      ports:
        - containerPort: 8080
      readinessProbe:
        exec:
          command: ["test", "-f", "/tmp/ready"]
        initialDelaySeconds: 2
        periodSeconds: 2
        failureThreshold: 2
      livenessProbe:
        exec:
          command: ["test", "-f", "/tmp/alive"]
        initialDelaySeconds: 2
        periodSeconds: 2
        failureThreshold: 2

Pod가 READY 1/1에 도달한 뒤 /tmp/ready와 /tmp/alive를 순서대로 삭제해 상태와 EndpointSlice, 이벤트를 관찰했습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 초기 상태
NAME         READY   STATUS    RESTARTS   AGE   IP            NODE
probe-demo   1/1     Running   0          3s    10.244.1.12   k8s-lab-worker2
EndpointSlice: addresses=["10.244.1.12"], conditions={"ready":true,"serving":true,"terminating":false}

# 1) /tmp/ready 삭제 (Readiness 실패: 재시작 없이 트래픽만 제외)
$ kubectl exec -n lab-d4-lifecycle probe-demo -- rm /tmp/ready
NAME         READY   STATUS    RESTARTS   AGE
probe-demo   0/1     Running   0          9s
EndpointSlice: addresses=["10.244.1.12"], conditions={"ready":false,"serving":false,"terminating":false}

# 2) /tmp/alive 삭제 (Liveness 실패: kubelet이 컨테이너 재시작)
$ kubectl exec -n lab-d4-lifecycle probe-demo -- rm /tmp/alive
NAME         READY   STATUS    RESTARTS     AGE
probe-demo   1/1     Running   1 (3s ago)   45s

Events:
  Warning  Unhealthy  33s (x2 over 35s)  kubelet  spec.containers{app}: Liveness probe failed:
  Normal   Killing    33s                kubelet  spec.containers{app}: Container app failed liveness probe, will be restarted
  Warning  Unhealthy  5s (x20 over 40s)  kubelet  spec.containers{app}: Readiness probe failed:
  Normal   Created    3s (x2 over 45s)   kubelet  spec.containers{app}: Container created
  Normal   Started    3s (x2 over 45s)   kubelet  spec.containers{app}: Container started

/tmp/ready를 지우면 RESTARTS는 0을 유지한 채 READY만 0/1로 내려가고 EndpointSlice의 ready·serving 조건이 false로 전환됩니다. 반면 /tmp/alive를 지우면 연속 2회 실패 직후 kubelet이 Killing 이벤트를 남기고 컨테이너를 재시작해 RESTARTS가 1로 올라갑니다.


2. 느린 기동 컨테이너를 보호하는 Startup Probe

Spring Boot처럼 클래스 로딩과 Bean 초기화에 수십 초가 걸리는 애플리케이션에 짧은 livenessProbe를 그대로 붙이면, 앱이 아직 뜨는 도중에 kubelet이 장애로 오인해 강제 종료합니다. 과거에는 이를 피하려고 livenessProbe.initialDelaySeconds를 60초 이상으로 크게 늘렸지만, 기동 시간이 일정하지 않거나 평소 장애 감지가 느려지는 단점이 남습니다.

startupProbe를 선언하면 kubelet은 startupProbe가 최소 1회 성공할 때까지 livenessProbe와 readinessProbe 실행을 모두 유예합니다. 초기 기동 여유 시간은 startupProbe의 periodSeconds * failureThreshold로 넉넉히 확보하고, 일단 기동이 끝나면 민감한 livenessProbe로 즉시 전환할 수 있습니다.

기동에 8초가 걸리는 컨테이너에 4초 임계치의 livenessProbe와 최대 20초(2s × 10) 여유를 주는 startupProbe를 함께 적용해 보았습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# startup-probe-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: slow-start-demo
  namespace: lab-d4-lifecycle
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "echo 'initializing (8s)...'; sleep 8; touch /tmp/started /tmp/alive; echo 'ready!'; sleep 3600"]
      startupProbe:
        exec:
          command: ["test", "-f", "/tmp/started"]
        periodSeconds: 2
        failureThreshold: 10
      livenessProbe:
        exec:
          command: ["test", "-f", "/tmp/alive"]
        periodSeconds: 2
        failureThreshold: 2

실행 결과는 다음과 같습니다.

1
2
3
4
5
6
7
8
9
NAME              READY   STATUS    RESTARTS   AGE
slow-start-demo   1/1     Running   0          10s

$ kubectl logs slow-start-demo -n lab-d4-lifecycle
initializing (8s)...
ready!

Events:
  Warning  Unhealthy  2s (x4 over 8s)  kubelet  spec.containers{app}: Startup probe failed:

8초 동안 Startup probe failed가 4회 기록됐지만 livenessProbe가 개입하지 않아 재시작 없이(RESTARTS 0) READY 1/1에 도달했습니다.


3. 리소스 Requests·Limits와 QoS 클래스, OOMKilled(137)

Kubernetes의 resources.requests와 resources.limits는 스케줄링 기준과 런타임 cgroup 제약을 각각 담당합니다.

  • requests: 스케줄러가 Pod를 배치할 노드를 고를 때 보장해야 하는 최소 자원입니다. CPU에서는 cgroup 가중치(cpu.weight)로 변환되어 경합 시 비율을 보장합니다.
  • limits: 컨테이너가 넘을 수 없는 상한입니다. CPU는 상한에 닿으면 커널 CFS 스케줄러가 스로틀링(속도 저하)만 걸지만, 메모리는 압축할 수 없는 자원이므로 상한을 넘는 순간 커널 OOM Killer가 프로세스를 종료(SIGKILL, Exit Code 137)합니다. JVM 힙과 네이티브 메모리 오버헤드 계산은 Docker 컨테이너 리소스 제한과 JVM OOMKilled(137) 대응에서 다룬 cgroup v2 원리와 동일합니다.

Kubernetes는 Pod 내 모든 컨테이너의 requests/limits 조합에 따라 .status.qosClass를 세 등급으로 자동 분류하며, 노드에 메모리 압박이 생기면 이 등급 순서대로 축출(Eviction) 대상을 고릅니다.

QoS 클래스지정 조건노드 메모리 압박 시 축출 순위권장 워크로드
Guaranteed모든 컨테이너의 CPU·메모리 requests == limits3순위 (가장 마지막에 축출)핵심 API, DB, 상태 저장 워크로드
Burstable최소 1개 컨테이너에 requests 또는 limits 지정 (Guaranteed 미충족)2순위 (requests 대비 초과 사용 비율이 큰 순)일반 웹 서버, 트래픽 변동이 큰 서비스
BestEffort모든 컨테이너에 requests와 limits 모두 미지정1순위 (가장 먼저 축출)중단돼도 무방한 일회성 배치·로컬 실험

실제로 세 가지 조합(qos-guaranteed: 100m/64Mi 동일 지정, qos-burstable: 50m→200m / 32Mi→128Mi, qos-besteffort: 미지정)을 배포해 조회하면 정확히 매핑됩니다.

1
2
3
4
5
6
$ kubectl get pods -n lab-d4-lifecycle -l group=qos \
  -o 'custom-columns=NAME:.metadata.name,QOS:.status.qosClass,CPU_REQ:.spec.containers[0].resources.requests.cpu,CPU_LIM:.spec.containers[0].resources.limits.cpu,MEM_REQ:.spec.containers[0].resources.requests.memory,MEM_LIM:.spec.containers[0].resources.limits.memory'
NAME             QOS          CPU_REQ   CPU_LIM   MEM_REQ   MEM_LIM
qos-besteffort   BestEffort   <none>    <none>    <none>    <none>
qos-burstable    Burstable    50m       200m      32Mi      128Mi
qos-guaranteed   Guaranteed   100m      100m      64Mi      64Mi

이어서 메모리 limits를 초과할 때의 종료 상태를 확인하기 위해 limits.memory: 32Mi Pod에서 Python으로 50MiB 배열을 할당해 보았습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# oom-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: oom-demo
  namespace: lab-d4-lifecycle
spec:
  restartPolicy: Never
  containers:
    - name: mem-eater
      image: python:3.12-alpine
      command:
        - python3
        - -c
        - "print('allocating 50MiB...', flush=True); buf = bytearray(50 * 1024 * 1024); print('allocated', len(buf), flush=True)"
      resources:
        requests:
          memory: "16Mi"
        limits:
          memory: "32Mi"
1
2
3
4
5
6
7
8
9
10
$ kubectl get pod oom-demo -n lab-d4-lifecycle
NAME       READY   STATUS      RESTARTS   AGE
oom-demo   0/1     OOMKilled   0          7s

$ kubectl get pod oom-demo -n lab-d4-lifecycle \
  -o jsonpath='reason={.status.containerStatuses[0].state.terminated.reason} exitCode={.status.containerStatuses[0].state.terminated.exitCode}{"\n"}'
reason=OOMKilled exitCode=137

$ kubectl logs oom-demo -n lab-d4-lifecycle
allocating 50MiB...

allocated 로그를 출력하기도 전에 커널이 프로세스를 종료했고, Pod 상태에는 reason=OOMKilled, exitCode=137이 남았습니다.

운영 환경에서 CPU limits를 지나치게 낮게 고정하면 노드에 유휴 CPU가 남아 있어도 CFS 스로틀링으로 p99 응답 지연이 튈 수 있습니다. 지연에 민감한 일반 서비스는 메모리는 requests == limits로 고정해 OOM 예측 가능성을 확보하되, CPU는 requests를 충분히 잡고 limits는 여유 있게 두거나 부하 테스트 후 결정하는 편이 안전합니다.


4. Pod 종료 흐름과 preStop 훅의 무중단 종료 원리

롤링 업데이트나 스케일 인으로 Pod가 Terminating 상태에 들어가면 Kubernetes 내부에서는 두 가지 작업이 비동기 병렬로 동시에 시작됩니다.

sequenceDiagram
    participant API as API Server / EndpointSlice
    participant Proxy as kube-proxy / Gateway
    participant Kubelet as kubelet / Container

    Note over API,Kubelet: kubectl delete pod (Terminating 시작)
    par 네트워크 경로 제거
        API->>Proxy: EndpointSlice에서 Pod IP 제거
        Proxy->>Proxy: iptables / IPVS 규칙 갱신
    and 컨테이너 종료 절차
        Kubelet->>Kubelet: preStop 훅 실행 (예: sleep 5)
        Note over Kubelet: 전파 지연 흡수 후 SIGTERM 전달
        Kubelet->>Kubelet: 진행 중 요청 드레이닝 후 Exit 0
    end

문제는 두 경로의 속도 차이에서 생깁니다. kubelet이 즉시 컨테이너에 SIGTERM을 보내 애플리케이션이 소켓을 닫아버렸는데, 다른 노드의 kube-proxy나 Gateway가 아직 EndpointSlice 변경을 반영하지 못했다면 신규 요청이 이미 닫힌 Pod IP로 전달되어 Connection Refused나 502 Bad Gateway가 발생합니다.

lifecycle.preStop 훅은 SIGTERM을 보내기 직전에 동기적으로 실행됩니다. 여기에 sleep 5~sleep 10 정도의 짧은 대기 시간을 두면, 그 사이 EndpointSlice와 로드밸런서 규칙에서 Pod IP가 빠지고 난 뒤에야 메인 프로세스가 SIGTERM을 받아 안전하게 종료 절차를 밟을 수 있습니다. 물론 컨테이너 내부의 PID 1 프로세스가 SIGTERM을 제대로 수신하도록 Docker PID 1과 Graceful Shutdown 설정처럼 exec 폼이나 init 프로세스 구성을 갖추는 것이 전제입니다.

preStop이 실제로 SIGTERM보다 먼저 끝나고 나서야 시그널이 전달되는지 밀리초 단위 타임스탬프로 확인해 보았습니다.

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
# prestop-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: prestop-demo
  namespace: lab-d4-lifecycle
spec:
  terminationGracePeriodSeconds: 30
  containers:
    - name: app
      image: python:3.12-alpine
      command:
        - sh
        - -c
        - |
          now() { python3 -c "import datetime; print(datetime.datetime.now(datetime.timezone.utc).strftime('%H:%M:%S.%f')[:-3])"; }
          trap 'echo "[$(now)] MAIN: received SIGTERM, draining and exiting cleanly"; exit 0' TERM
          echo "[$(now)] MAIN: started"
          sleep 3600 &
          wait $!
      lifecycle:
        preStop:
          exec:
            command:
              - sh
              - -c
              - |
                now() { python3 -c "import datetime; print(datetime.datetime.now(datetime.timezone.utc).strftime('%H:%M:%S.%f')[:-3])"; }
                echo "[$(now)] PRESTOP: hook started, sleeping 5s for endpoint propagation" > /proc/1/fd/1
                sleep 5
                echo "[$(now)] PRESTOP: hook finished" > /proc/1/fd/1

kubectl logs -f prestop-demo로 스트림을 연 상태에서 kubectl delete pod prestop-demo를 실행한 실제 출력입니다.

1
2
3
4
[07:03:24.569] MAIN: started
[07:03:26.648] PRESTOP: hook started, sleeping 5s for endpoint propagation
[07:03:31.661] PRESTOP: hook finished
[07:03:31.677] MAIN: received SIGTERM, draining and exiting cleanly

preStop이 07:03:26.648에 시작해 정확히 5.013초 뒤인 07:03:31.661에 끝났고, 그로부터 0.016초 뒤(07:03:31.677)에 메인 프로세스가 SIGTERM을 수신해 정상 종료(Exit 0)했습니다.

다만 preStop은 엔드포인트 전파 지연을 흡수해 SIGTERM 시점을 늦추는 역할일 뿐입니다. 이미 들어온 HTTP 요청과 Keep-Alive 연결을 끊지 않고 마무리하려면 애플리케이션 자체의 Graceful Shutdown(예: Spring Boot의 server.shutdown=graceful과 spring.lifecycle.timeout-per-shutdown-phase)이 함께 동작해야 합니다.


5. 운영 함정과 실무 점검 체크리스트

프로덕션에서 자주 발생하는 3가지 함정

  1. terminationGracePeriodSeconds 예산 착각: 기본 30초 유예 시간은 SIGTERM 이후가 아니라 preStop 시작 시점부터 차감됩니다. preStop에서 20초를 쓰고 앱 드레이닝에 15초가 필요하면 총 35초가 되어 30초 시점에 SIGKILL(Exit 137)로 강제 종료됩니다. terminationGracePeriodSeconds > preStop 시간 + 앱 최대 드레이닝 시간 + 여유분으로 넉넉히 잡아야 합니다.
  2. livenessProbe에 외부 의존성 포함: DB나 외부 API 장애 시 모든 Pod가 동시에 재시작 루프에 빠져 복구 시간을 크게 늘립니다. 외부 의존성 검사는 readinessProbe에만 두거나 아예 분리합니다.
  3. preStop 실행 파일 부재: Distroless나 초경량 이미지에는 sh와 sleep 바이너리가 없어 exec: ["sh", "-c", "sleep 5"]가 실패합니다. 이 경우 Kubernetes 1.30+에서 기본 지원되는 lifecycle.preStop.sleep 액션(sleep: { seconds: 5 })을 사용하거나 앱 엔드포인트(httpGet)로 대체해야 합니다.

새 워크로드를 클러스터에 올리기 전 아래 항목을 점검해 두면 배포 중 장애를 크게 줄일 수 있습니다.

  • 기동이 5초 이상 걸리는 애플리케이션에 startupProbe를 두고 livenessProbe의 조기 종료를 차단했는가
  • readinessProbe는 트래픽 수신 가능 여부를, livenessProbe는 프로세스 자체의 회복 불가 상태만 검사하도록 분리했는가
  • 모든 컨테이너에 최소한 requests와 메모리 limits를 지정해 BestEffort 우선 축출을 피했는가
  • preStop 대기 시간(5~10초)과 애플리케이션 Graceful Shutdown 타임아웃의 합보다 terminationGracePeriodSeconds를 충분히 크게 설정했는가
  • 컨테이너 엔트리포인트가 SIGTERM을 정상 수신해 Exit 0으로 종료하는지 kubectl delete pod 로그로 직접 확인했는가

참고 자료

Kubernetes lets you define probes to continuously monitor the health of containers in a Pod. A probe is a diagnostic performed periodically by the kubelet on a container. To perform a diagnostic, the kubelet either executes code within the container or makes a network request. Based on the probe results, Kubernetes can restart unhealthy containers or stop sending traffic to containers that are not ready.
This page describes the lifecycle of a Pod. Pods follow a defined lifecycle, starting in the Pending phase, moving through Running if at least one of its primary containers starts OK, and then through either the Succeeded or Failed phases depending on whether any container in the Pod terminated in failure. While a Pod runs, the kubelet manages containers and translates the Pod's spec for the container runtime. The kubelet also manages executing probes that track the health of your application.
This page introduces Quality of Service (QoS) classes in Kubernetes, and explains how Kubernetes assigns a QoS class to each Pod as a consequence of the resource constraints that you specify for the containers in that Pod. Kubernetes relies on this classification to make decisions about which Pods to evict when there are not enough available resources on a Node. Quality of Service classesKubernetes classifies the Pods that you run and allocates each Pod into a specific quality of service (QoS) class. Kubernetes uses that classification to influence how different pods are handled. Kubernetes does this classification based on the resource requests of the Containers in that Pod, along with how those requests relate to resource limits. This is known as Quality of Service (QoS) class. Kubernetes assigns every Pod a QoS class based on the resource requests and limits of its component Containers. QoS classes are used by Kubernetes to decide which Pods to evict from a Node experiencing Node Pressure. The possible QoS classes are Guaranteed, Burstable, and BestEffort. When a Node runs out of resources, Kubernetes will first evict BestEffort Pods running on that Node, followed by Burstable and finally Guaranteed Pods. When this eviction is due to resource pressure, only Pods exceeding resource requests are candidates for eviction.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.