| |

Docker 39 🐳 Out-Of-Memory (OOM) Killer Behaviors and OOM Score Adjustments in Containers

⏱️ Estimated read: 17 min | |

When a container reaches its memory limit, the Linux kernel does not gracefully ask it to free memory. It sends SIGKILL. The process dies immediately, without cleanup, without flushing buffers, without closing connections. The container exits with code 137 (128 + 9), and docker inspect reports OOMKilled: true. This is the cgroup OOM killer, and it is the kernel’s last resort when memory cannot be reclaimed any other way. Understanding how it selects its victim, and how that selection can be influenced, is the difference between a container that dies predictably and one that takes down the host.

The OOM killer is not a Docker feature. It is a Linux kernel mechanism. Docker configures cgroups — the kernel’s resource isolation primitives — and the kernel enforces the limits. When a container’s memory cgroup reaches its limit, the kernel invokes the OOM killer to free memory. The killer computes a badness score for every eligible process and kills the one with the highest score. The score is based on memory usage, but it is adjusted by a per-process value called oom_score_adj. This is the knob that lets an operator say “prefer this process” or “protect this process” .

For containers, the OOM killer behaves differently depending on the memory limit. A container with an explicit --memory limit has its own cgroup, and the OOM killer is scoped to that cgroup. A container without a limit shares the host’s memory, and the host-level OOM killer may select any process on the system — including the Docker daemon. Docker mitigates this by adjusting the daemon’s OOM priority, making it less likely to be killed than containers, but the protection is not absolute .

This chapter covers three areas. First, why the OOM killer exists in containers — the cgroup memory limit, the exit code 137, and the difference between container-level and host-level OOM kills. Second, how the OOM killer selects its victim — the badness score, the oom_score_adj range, and the heuristics that determine which process dies. Third, how to adjust OOM scores in containers — the --oom-score-adj flag, the --oom-kill-disable option and its dangers, and the patterns for protecting critical processes. The chapter ends with a complete example session, a quick reference, best practices, common pitfalls, real-world examples, and diagrams showing the OOM selection process.

Key point: The cgroup OOM killer selects the process with the highest badness score, which is based on memory usage adjusted by oom_score_adj. The range is -1000 (never kill) to +1000 (always kill first). Setting --oom-score-adj on a container changes the score for its main process. --oom-kill-disable prevents the OOM killer from killing the container, but only safe when --memory is set; without a limit, it can cause the host to run out of memory.


Why the OOM killer exists in containers

The cgroup memory limit. When a container is started with --memory, Docker creates a memory cgroup with that limit. Every process inside the container belongs to that cgroup. When the cgroup’s memory usage reaches the limit, the kernel cannot allocate more memory for the container’s processes. It tries to reclaim memory by evicting page cache, swapping out anonymous pages, and compacting memory. If those attempts fail, it invokes the OOM killer for that cgroup. The killer selects a process inside the cgroup and kills it, freeing its memory so the remaining processes can continue .

The exit code 137 problem. A process killed by SIGKILL exits with code 137. Docker reports this as the container’s exit code, and docker inspect shows OOMKilled: true if the kill came from the cgroup OOM killer. The true flag is the critical signal: it distinguishes an OOM kill from an external SIGKILL, such as docker kill or a docker stop timeout escalation. Both produce exit code 137, but the remediation is different. An OOM kill means the container needed more memory than its limit allowed. An external kill means something outside the container decided to terminate it .

The host-level OOM problem. A container without a --memory limit is not isolated from the host’s memory. It can consume all available memory on the host, and when the host runs out, the host-level OOM killer selects a process from any cgroup on the system. That process could be another container, a system service, or the Docker daemon itself. Docker adjusts the daemon’s oom_score_adj to make it less likely to be killed, but the protection is not guaranteed. The only reliable way to prevent a container from participating in a host-level OOM event is to give it a memory limit .

The child-process problem. In a container running multiple processes — a shell wrapper, a supervisor, and worker processes — the OOM killer may kill a child process instead of PID 1. If PID 1 survives, the container does not exit, and docker inspect shows OOMKilled: false. The container continues running in a degraded state, missing a worker, and the only evidence is an increment in the cgroup’s memory.events counter. This is a subtle failure mode that requires inspecting the cgroup, not just the container state .

The trade-off. OOM scoring is a blunt instrument. The badness score is a heuristic, not a policy engine. Setting oom_score_adj to protect a process makes it less likely to be killed, but if every process is protected, the killer has no good candidate and may kill something critical anyway. Setting it too high makes a process the first target, even if it is not the largest memory consumer. The score is a preference, not a guarantee. The kernel still kills something when memory runs out; the score only determines the order.


a. The badness score and oom_score_adj

The OOM killer assigns each eligible process a badness score between 0 and 1000. The score is roughly proportional to the process’s memory usage relative to the allowed memory in its context. A process using all allowed memory scores 1000. A process using half scores 500. The process with the highest score is killed .

The oom_score_adj value is added to the badness score before comparison. The range is -1000 to +1000. A value of -1000 makes the process score 0, meaning it will never be killed by the OOM killer. A value of +1000 makes it score the maximum, meaning it is the first candidate. The value 0 is the default, meaning the score is purely based on memory usage .

The score is computed in the context of the OOM event. If the OOM is triggered by a cgroup memory limit, the “allowed memory” is that limit, and only processes in that cgroup are considered. If the OOM is host-level, the allowed memory is the host’s total memory, and all processes are candidates. This context matters: a process with oom_score_adj = -500 in a container with a 512MB limit is protected relative to other processes in that container, but it has no protection against a host-level OOM killer .

The root process in a container receives a 3% memory bonus in the badness score, making it slightly more likely to be killed than a non-root process with the same memory usage . This is a historical artifact of the kernel’s design, not a deliberate container policy.

b. Adjusting OOM scores in containers

Docker exposes the OOM score adjustment through the --oom-score-adj flag on docker run. The value applies to the container’s main process (PID 1) and is inherited by child processes unless they override it .

docker run -d --memory="512m" --oom-score-adj=-500 myapp

The -500 makes the container’s main process roughly half as likely to be killed as a process with the default score, relative to other processes in the same cgroup. This is useful for protecting a critical service from being killed by a runaway worker inside the same container.

The --oom-kill-disable flag takes a different approach. It disables the OOM killer for the container’s cgroup entirely. Without an OOM killer, the kernel cannot free memory by killing a process. The container’s processes will hang, waiting for memory that never arrives. This is why --oom-kill-disable is dangerous. Docker’s documentation explicitly warns that it should only be used when --memory is also set. Without a memory limit, disabling the OOM killer on a container means the host can run out of memory, and the host-level OOM killer will kill something else — possibly the Docker daemon or another container .

# SAFE: memory limit is set
docker run -d --memory="512m" --oom-kill-disable myapp

# DANGEROUS: no memory limit, host can run out of memory
docker run -d --oom-kill-disable myapp

When --oom-kill-disable is used with a memory limit, the container cannot be killed by the cgroup OOM killer. But the processes inside will block on memory allocation and hang. This is sometimes preferable to a crash, but it requires external monitoring to detect the hang and restart the container.

The --oom-score-adj flag can be set on the Docker daemon as well, but Docker’s documentation warns against setting it to extreme negative values. The daemon’s OOM priority is already adjusted to be less likely to be killed than containers. Circumventing this protection can make the daemon a target for the OOM killer, which would bring down every container on the host .

c. Protecting critical processes inside a container

The OOM score adjustment is not limited to the container’s main process. Any process inside the container can have its oom_score_adj set, and the value can be changed at runtime by writing to /proc/<pid>/oom_score_adj. This allows a container to protect a critical subprocess from being killed by a runaway worker .

A common pattern is a container running a primary application process and a pool of worker processes. The workers are memory-hungry and may spike, while the primary process must survive. The entrypoint script sets a low oom_score_adj on the primary process before dropping privileges and spawning the workers:

#!/bin/sh
# Set OOM protection on the primary process (PID 1)
echo -500 > /proc/1/oom_score_adj

# Drop privileges and start the application
su-exec appuser /app/primary

The workers inherit the default oom_score_adj of 0 (or their parent’s value, if not changed). When memory pressure occurs, the kernel prefers to kill the workers, which have a higher score, over the primary process, which has a lower score .

The choom command provides a command-line interface for adjusting oom_score_adj on a running process or a newly executed command. This can be used inside a container to adjust scores after the container is running .


Complete Example Session

# ============================================
# PART 1: OOM KILL DETECTION
# ============================================

# Exit code 137 and OOMKilled: true indicates
# a cgroup OOM kill.

docker run -d --name oom-test --memory="64m" nginx

# After the container is killed:
docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}}' oom-test
# true 137


# ============================================
# PART 2: DISTINGUISHING OOM KILL FROM EXTERNAL SIGKILL
# ============================================

# Both produce exit code 137, but OOMKilled differs.

docker run -d --name external-kill --memory="512m" nginx
docker kill external-kill

docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}}' external-kill
# false 137


# ============================================
# PART 3: CHECKING OOM SCORE
# ============================================

# Inside a running container, read the OOM score.

docker run -d --name score-check --memory="512m" nginx
docker exec score-check cat /proc/1/oom_score
# (a value between 0 and 1000)


# ============================================
# PART 4: SETTING OOM SCORE ADJ AT CREATION
# ============================================

# Protect the main process from being killed first.

docker run -d --name protected \
  --memory="512m" \
  --oom-score-adj=-500 \
  nginx

docker exec protected cat /proc/1/oom_score_adj
# -500


# ============================================
# PART 5: DISABLING THE OOM KILLER (WITH LIMIT)
# ============================================

# Disable the OOM killer only when --memory is set.

docker run -d --name no-oom-kill \
  --memory="256m" \
  --oom-kill-disable \
  nginx

# The container cannot be killed by the cgroup OOM
# killer. Its processes may hang on memory allocation.


# ============================================
# PART 6: PROTECTING A CRITICAL PROCESS IN ENTRYPOINT
# ============================================

# Entrypoint script sets OOM protection on PID 1
# before spawning workers.

#!/bin/sh
echo -500 > /proc/1/oom_score_adj
su-exec appuser /app/primary


# ============================================
# PART 7: CGROUP OOM COUNTER (CGROUP V2)
# ============================================

# The cgroup memory.events file shows OOM kill count.

cat /sys/fs/cgroup/system.slice/docker-<container_id>.scope/memory.events
# oom 1
# oom_kill 1


# ============================================
# PART 8: CGROUP OOM CONTROL (CGROUP V1)
# ============================================

# On cgroup v1, memory.oom_control shows OOM status.

cat /sys/fs/cgroup/memory/docker/<container_id>/memory.oom_control
# oom_kill_disable 0
# under_oom 0


# ============================================
# PART 9: THE DAEMON'S OOM SCORE
# ============================================

# Docker adjusts the daemon's OOM priority.
# Do not override this with extreme negative values.

cat /proc/$(pidof dockerd)/oom_score_adj
# (a negative value set by Docker)


# ============================================
# PART 10: THE COMPLETE PATTERN
# ============================================

# A container with memory limit, OOM protection
# on the main process, and a worker pool.

docker run -d --name app \
  --memory="1g" \
  --memory-swap="1g" \
  --oom-score-adj=-500 \
  myapp

# The main process is protected. If a worker
# exhausts memory, the OOM killer targets the
# worker, not the main process.

The ten parts show OOM kill detection, distinguishing OOM from external SIGKILL, checking OOM score, setting --oom-score-adj, disabling the OOM killer with a limit, protecting a critical process in an entrypoint, the cgroup v2 OOM counter, the cgroup v1 OOM control, the daemon’s OOM score, and a complete pattern.


Quick Reference

OOM Score and Adjustment

ItemValue
Badness score range0 (never kill) to 1000 (always kill)
oom_score_adj range-1000 to +1000
Default0
-1000Disables OOM killing for the process
+1000Maximum preference for killing
Root bonus3% extra memory in badness score

Docker Flags

FlagEffect
--oom-score-adjAdjust OOM score for PID 1
--oom-kill-disableDisable OOM killer for the cgroup
--memoryHard memory limit (required for safe --oom-kill-disable)

Exit Code 137

CauseOOMKilledFix
Cgroup OOM killtrueIncrease --memory
External SIGKILLfalseCheck docker kill, stop timeout
Child process OOMfalseCheck cgroup memory.events

OOM Score Files

FilePurpose
/proc/<pid>/oom_scoreCurrent badness score
/proc/<pid>/oom_score_adjAdjustment value (read/write)
/proc/<pid>/oom_adjDeprecated, scaled version

Best Practices

✅ Do This:

# Set memory limits to scope the OOM killer
--memory="512m" --memory-swap="512m"                                    # ✅
# Use --oom-score-adj to protect critical processes
--oom-score-adj=-500                                                     # ✅
# Set OOM protection in the entrypoint before dropping privileges
echo -500 > /proc/1/oom_score_adj                                        # ✅
# Check OOMKilled flag to distinguish OOM from external kill
docker inspect -f '{{.State.OOMKilled}}'                                # ✅
# Monitor cgroup memory.events for child-process OOM
cat /sys/fs/cgroup/.../memory.events                                     # ✅

❌ Don’t Do This:

# Don't use --oom-kill-disable without --memory
--oom-kill-disable  # host can run out of memory                         # ❌
# Don't set extreme negative values on the daemon
dockerd --oom-score-adj=-1000  # daemon can't be killed                   # ❌
# Don't assume exit 137 always means OOM
# Check OOMKilled flag                                                   # ❌
# Don't protect every process
# If all processes have -1000, the killer has no candidate                # ❌

Common Pitfalls

PitfallWhy It HappensFix
Container killed with exit 137Exceeded memory limitIncrease --memory or fix leak
OOMKilled: false but exit 137External SIGKILL or child-process OOMCheck daemon logs and cgroup events
Host OOM kills system processNo container memory limitSet --memory on every container
--oom-kill-disable hangs containerNo OOM killer, processes blockUse only with --memory, monitor for hangs
OOM protection ineffectiveHost-level OOM ignores cgroup scoresSet memory limits to scope OOM
Child process killed but container aliveMulti-process containerCheck memory.events and restart workers

Real-World Examples

1. Detect OOM Kill

docker inspect -f '{{.State.OOMKilled}}' container

2. Protect Main Process

docker run --oom-score-adj=-500 --memory="1g" app

3. Disable OOM Killer (Safe)

docker run --memory="512m" --oom-kill-disable app

4. Entrypoint Protection

#!/bin/sh
echo -500 > /proc/1/oom_score_adj
exec /app/primary

5. Cgroup v2 OOM Counter

cat /sys/fs/cgroup/system.slice/docker-<id>.scope/memory.events

6. Cgroup v1 OOM Control

cat /sys/fs/cgroup/memory/docker/<id>/memory.oom_control

7. Check OOM Score

docker exec container cat /proc/1/oom_score

8. Check OOM Adjustment

docker exec container cat /proc/1/oom_score_adj

9. Daemon OOM Score

cat /proc/$(pidof dockerd)/oom_score_adj

10. Memory Swap Disabled

docker run --memory="512m" --memory-swap="512m" app

Visual

The OOM Selection Process

┌──────────────────────────────────────────────────────────────┐
│  OOM SELECTION PROCESS                                       │
│                                                              │
│  Memory cgroup reaches limit                                 │
│    │                                                         │
│    ▼                                                         │
│  Kernel tries to reclaim memory                              │
│    │                                                         │
│    ├── evict page cache                                      │
│    ├── swap anonymous pages                                  │
│    └── compact memory                                        │
│    │                                                         │
│    ▼                                                         │
│  Reclaim fails                                               │
│    │                                                         │
│    ▼                                                         │
│  OOM killer invoked for cgroup                               │
│    │                                                         │
│    ▼                                                         │
│  For each process in cgroup:                                 │
│    badness = memory_usage_ratio * 1000                       │
│    score = badness + oom_score_adj                           │
│    │                                                         │
│    ▼                                                         │
│  Kill process with HIGHEST score                             │
│                                                              │
│  Range: 0 (never) to 1000 (always)                           │
│  oom_score_adj: -1000 to +1000                               │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Container vs Host OOM

┌──────────────────────────────────────────────────────────────┐
│  CONTAINER vs HOST OOM                                       │
│                                                              │
│  Container WITH --memory limit:                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Memory cgroup isolated                              │    │
│  │  OOM killer scoped to cgroup                         │    │
│  │  Only container processes are candidates             │    │
│  │  Other containers are unaffected                     │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  Container WITHOUT --memory limit:                           │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  No cgroup isolation                                 │    │
│  │  Host-level OOM killer invoked                       │    │
│  │  ANY process on the host is a candidate              │    │
│  │  Includes Docker daemon, other containers            │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  Docker adjusts the daemon's score to protect it,            │
│  but the protection is not absolute.                         │
│                                                              │
└──────────────────────────────────────────────────────────────┘

oom_score_adj Range

┌──────────────────────────────────────────────────────────────┐
│  oom_score_adj RANGE                                         │
│                                                              │
│  -1000 ──────────────────────── 0 ──────────────────── +1000 │
│    │                            │                        │   │
│    │                            │                        │   │
│  NEVER KILL                 DEFAULT                KILL FIRST│
│    │                            │                        │   │
│  Score = 0                  Score = badness        Score = max│
│                                                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  -500: half as likely to be killed                   │    │
│  │   0: default, based on memory usage                  │    │
│  │  +500: 50% more likely to be killed                  │    │
│  │  -1000: OOM killing disabled for this process        │    │
│  │  +1000: maximum priority for killing                 │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  The value is added to the badness score before comparison.  │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Exit Code 137 Decision Tree

┌──────────────────────────────────────────────────────────────┐
│  EXIT CODE 137 DECISION TREE                                 │
│                                                              │
│  Container exits with code 137                               │
│    │                                                         │
│    ▼                                                         │
│  docker inspect .State.OOMKilled                             │
│    │                                                         │
│    ├── true ──► CGROUP OOM KILL                              │
│    │           Container exceeded memory limit               │
│    │           Fix: increase --memory                        │
│    │                                                         │
│    └── false ──► NOT CGROUP OOM                              │
│                  │                                           │
│                  ├── docker kill / stop timeout              │
│                  │   Check daemon logs                       │
│                  │                                           │
│                  ├── Host-level OOM (no limit)               │
│                  │   Check dmesg | grep oom                  │
│                  │                                           │
│                  └── Child-process OOM (PID 1 survived)      │
│                      Check cgroup memory.events              │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
Badness score0 (never kill) to 1000 (always kill)
oom_score_adj-1000 to +1000; added to badness score
Default score0; based on memory usage
-1000Disables OOM killing for the process
--oom-score-adjDocker flag to adjust PID 1’s score
--oom-kill-disableDisables OOM killer for cgroup (requires --memory)
Exit code 137SIGKILL; OOMKilled: true if cgroup OOM
Host OOMNo memory limit → host-level killer
Child-process OOMPID 1 survives; check memory.events

Key takeaways:

  • The cgroup OOM killer selects the process with the highest badness score. The score is based on memory usage relative to the allowed memory, adjusted by oom_score_adj. The range is -1000 (never kill) to +1000 (always kill first) .
  • Exit code 137 and OOMKilled: true indicate a cgroup OOM kill. Both an OOM kill and an external SIGKILL produce exit code 137, but only the OOM kill sets OOMKilled to true. This is the critical distinction for diagnosis .
  • A container without a --memory limit participates in host-level OOM. The host-level OOM killer can select any process on the system, including the Docker daemon. Docker adjusts the daemon’s score to protect it, but the only reliable protection is a memory limit on every container .
  • --oom-score-adj adjusts the OOM score for PID 1. A negative value makes the main process less likely to be killed, protecting it from runaway workers inside the same container .
  • --oom-kill-disable requires --memory to be safe. Without a limit, disabling the OOM killer on a container means the host can run out of memory, and the host-level killer will target something else. With a limit, the container hangs instead of dying .
  • Child processes can be OOM-killed without the container exiting. In a multi-process container, the OOM killer may kill a worker while PID 1 survives. OOMKilled is false, and the only evidence is the cgroup’s memory.events counter .
  • OOM scores are preferences, not guarantees. The kernel still kills something when memory runs out. The score determines the order, not whether a kill occurs. Setting every process to -1000 leaves the killer with no candidate .
  • The root process receives a 3% memory bonus in the badness score. This is a kernel heuristic, not a Docker policy. It makes root processes slightly more likely to be killed than non-root processes with the same memory usage .

Remember: The OOM killer is the kernel’s last resort when memory cannot be reclaimed. In containers, it is scoped to the cgroup when a memory limit is set, and it selects its victim by the highest badness score adjusted by oom_score_adj. The exit code 137 and the OOMKilled flag are the signals that distinguish a cgroup OOM kill from an external SIGKILL. The --oom-score-adj flag protects the main process, and --oom-kill-disable prevents the kill entirely but requires a memory limit to be safe. The score is a preference, not a guarantee — the kernel still kills something when memory runs out. The only reliable way to prevent a container from participating in a host-level OOM is to give it a memory limit.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!