好的阿杰,我帮你整理一份 Linux 系统内存不足导致服务崩溃的排查方法,涵盖从排查、分析到解决的全流程,适合运维或开发人员参考。
1️⃣ 判断内存不足的表现
当系统内存不足时,常见现象包括:
- 服务崩溃或重启(OOMKilled)
- 系统卡顿,响应缓慢
- 日志报错:
Out of memory: Kill process 1234 (java) score 987 or sacrifice child
- 高 Swap 使用率
dmesg
或/var/log/messages
出现 OOM 相关记录
2️⃣ 查看系统内存状态
1. free
命令
free -h
输出示例:
total used free shared buff/cache available
Mem: 7.8G 6.5G 200M 1.2G 1.1G 900M
Swap: 2.0G 1.8G 200M
used
+buff/cache
≈ 实际占用available
表示可用内存
2. vmstat
命令
vmstat 2 5
- 查看内存、Swap、CPU 等情况
si/so
> 0 表示 Swap 频繁交换,内存紧张
3. top
或 htop
- 查看占用内存高的进程
RES
列表示实际物理内存占用VIRT
列表示虚拟内存大小
4. cat /proc/meminfo
- 查看内存详细信息:
grep -E "MemTotal|MemFree|Buffers|Cached|SwapTotal|SwapFree" /proc/meminfo
3️⃣ 查找内存占用异常的进程
1. 使用 top
/ htop
- 按
%MEM
排序,找占用内存高的进程
2. 使用 ps
命令
ps aux --sort=-%mem | head -n 10
- 列出前 10 个内存占用最高的进程
3. 使用 smem
(更精确)
smem -r -k | sort -nrk 4 | head -n 10
PSS
(Proportional Set Size)更合理,适合共享内存的程序
4️⃣ 分析内存泄漏或异常增长
- 检查日志
- Java 应用:查看 GC 日志,OOM 堆栈
- Web 服务:异常请求日志
- 抓取内存快照
- Java:
jmap -heap <pid>
- Python:
tracemalloc
或objgraph
- 监控工具
prometheus + grafana
或zabbix
- 监控内存使用趋势、峰值
5️⃣ 排查 OOM Killer
Linux 内核会在内存耗尽时杀掉进程(OOM Killer):
dmesg | grep -i "killed process"
示例:
Out of memory: Kill process 1234 (java) score 987 or sacrifice child
score
越高,被杀概率越大- 可以调整 OOM 优先级:
echo -17 > /proc/<pid>/oom_adj # 高优先级进程不被杀
6️⃣ 排查 Swap 使用情况
swapon -s
查看 Swapfree -h
查看 Swap 占用- Swap 频繁使用说明物理内存不足,可考虑:
- 增加内存
- 优化服务内存消耗
- 调整 swappiness(默认 60):
sysctl vm.swappiness=10
7️⃣ 内存不足的优化方法
- 优化应用程序
- Java:调整堆内存参数
- Python:释放不再使用的对象
- C/C++:检查内存泄漏
- 调整 Linux 系统参数
vm.overcommit_memory
:sysctl vm.overcommit_memory=2
- 调整
ulimit
限制进程内存
- 增加物理内存或 Swap
- 临时缓解内存不足
- 不解决根本问题
- 使用内存监控和告警
- Prometheus、Grafana、Zabbix
- 当内存占用 > 80% 时告警
8️⃣ 总结排查步骤
- 确认服务崩溃原因:日志 / dmesg
- 查看系统内存状态:free / vmstat / top
- 找出占用内存高的进程:ps / top / smem
- 分析应用内存消耗:heap dump / tracemalloc
- 检查 OOM Killer 和 Swap 使用情况
- 优化应用和系统配置,必要时扩容
发表回复