Linux 系统触发 Out of memory: Kill process 内核 OOM 机制与保护调优
深入分析 Linux 内核 OOM Killer 选型牺牲进程的打分算法,提供核心进程免死配置与内存水位治理方案。
故障现象
在生产服务器物理内存及 Swap 耗尽后,关键业务进程(如 MySQL、sshd、核心网关等)突然无故消失,未在应用日志中留下任何 crash 痕迹。查看内核环形缓冲区 dmesg -T 或系统日志 /var/log/messages,看到如下典型内核日志:
[Sun Nov 15 16:30:12 2026] Out of memory: Kill process 12458 (mysqld) score 850 or sacrifice child
[Sun Nov 15 16:30:12 2026] Killed process 12458 (mysqld) total-vm:18942360kB, anon-rss:14892100kB, file-rss:0kB, shmem-rss:0kB
[Sun Nov 15 16:30:13 2026] oom_reaper: reaped process 12458 (mysqld), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB
内核的 Out-of-Memory(OOM)Killer 介入并强制终止了核心数据库进程。
核心机制与根因分析
Linux 内存管理默认采用了过度提交机制(Memory Overcommit)。内核允许申请超过实际物理内存加 Swap 的虚拟内存大小。当所有进程实际使用的物理常驻内存(RSS)逼近物理极限且无法通过回收 Page Cache 满足分配时,内核不得不触发 OOM Killer 挑选进程牺牲。
OOM 打分算法(badness heuristic)
内核为每个用户态进程计算一个坏度分数(/proc/<pid>/oom_score,取值范围 0 至 1000):
- 内存占比决定基础分:进程消耗的物理常驻内存比例越大,基础得分越高;
- oom_score_adj 偏置参数:用户可在
/proc/<pid>/oom_score_adj手动设定-1000到+1000的偏差:- 设置为
-1000:彻底免受 OOM 杀除(OOM-proof); - 设置为
+1000:在系统缺内存时绝对优先被作为牺牲品。
- 设置为
分步排查与定位
1. 抓取 OOM 发生时刻的内存全景快照
在 dmesg 输出中,OOM 触发前会打印一份极其详细的全局物理内存和各 Slab 占用表:
Mem-Info:
active_anon:3214560 inactive_anon:412010 isolated_anon:0
active_file:12400 inactive_file:10800 isolated_file:0
unevictable:0 dirty:12 writeback:0
计算 active_anon + inactive_anon,若匿名页占比超过 95%,说明系统几乎全为不可简单丢弃的堆内存,Page Cache 压缩已无能为力。
2. 检查系统中各常驻进程当前的 oom_score 排名
使用一段 shell 脚本快速列出前 10 个最危险的待宰进程:
printf "%-10s %-10s %-10s %-20s
" "PID" "OOM_SCORE" "OOM_ADJ" "COMMAND"
for pid in $(ls /proc | grep -E '^[0-9]+$'); do
if [ -f "/proc/$pid/oom_score" ]; then
score=$(cat /proc/$pid/oom_score 2>/dev/null || echo 0)
adj=$(cat /proc/$pid/oom_score_adj 2>/dev/null || echo 0)
cmd=$(cat /proc/$pid/comm 2>/dev/null || echo "")
printf "%-10s %-10s %-10s %-20s
" "$pid" "$score" "$adj" "$cmd"
fi
done | sort -k2 -rn | head -n 10
针对性解决方案
方案一:为关键核心守护进程设置 OOM 免疫(oom_score_adj = -1000)
通过 systemd 服务配置保护数据库或 SSH 服务:
[Service]
# 在 systemd unit 文件中声明
OOMScoreAdjust=-1000
更新服务定义:
sudo systemctl daemon-reload
sudo systemctl restart mysqld
检查是否生效:
cat /proc/$(pgrep mysqld)/oom_score_adj
# 必须输出: -1000
方案二:收紧内核过度提交控制策略(vm.overcommit_memory)
对于数据库专用节点,严禁内核无节制超卖虚拟内存:
# /etc/sysctl.d/99-memory.conf
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
overcommit_memory = 2:严格拒绝超出(物理内存 * ratio + swap)的申请,让应用直接在malloc()时抛出ENOMEM并走自身的重试或优雅降级逻辑,而不是由内核粗暴杀死。
方案三:合理配置应急 Swap 空间缓解内存峰值抖动
为无 Swap 的云服务器配置合理的临时换页文件(如 4GB ~ 8GB):
sudo fallocate -l 8G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
常见问答
问:为什么把所有关键进程都设成 -1000 会导致整机彻底死锁? 答:如果内存耗尽且内核找不到任何可杀的普通进程,内核会直接触发全局恐慌(Kernel Panic: Out of memory and no killable processes),导致操作系统瞬间硬重启。


