插件窝 干货文章 Linux日志“Out of memory”错误处理

Linux日志“Out of memory”错误处理

内存 bash Memory sudo 801    来源:    2025-05-06

Linux "Out of Memory" 错误处理指南

问题概述

当Linux系统出现"Out of memory"错误时,表示系统内存资源已耗尽,内核无法为进程分配所需内存。这通常会导致进程被终止或系统变得不稳定。

诊断步骤

1. 检查系统内存状态

free -h
top
htop
vmstat 1 5

2. 查看OOM killer日志

dmesg | grep -i "out of memory"
dmesg | grep -i "killed process"
journalctl -k | grep -i "oom"

3. 识别内存消耗大的进程

ps aux --sort=-%mem | head -n 10

解决方案

1. 临时解决方案

  • 终止占用内存过多的进程:

    kill -9 [PID]
    
  • 清理缓存:

    sync; echo 1 > /proc/sys/vm/drop_caches
    

2. 长期解决方案

A. 增加交换空间(Swap)

  1. 检查现有交换空间:

    swapon --show
    free -h
    
  2. 创建交换文件:

    sudo fallocate -l 4G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    
  3. 永久生效(添加到/etc/fstab):

    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
    

B. 调整OOM killer行为

  1. 查看当前OOM killer设置:

    cat /proc/sys/vm/overcommit_memory
    cat /proc/sys/vm/overcommit_ratio
    
  2. 修改设置(0-允许overcommit, 1-不允许, 2-基于比例):

    sudo sysctl vm.overcommit_memory=1
    
  3. 永久生效:

    echo 'vm.overcommit_memory=1' | sudo tee -a /etc/sysctl.conf
    

C. 优化应用程序

  • 限制特定进程的内存使用:

    systemctl set-property [service_name] MemoryMax=2G
    
  • 使用cgroups限制内存:

    cgcreate -g memory:/limited_group
    cgset -r memory.limit_in_bytes=1G limited_group
    

D. 系统级优化

  1. 调整swappiness(0-100, 默认60):

    sudo sysctl vm.swappiness=10
    
  2. 调整vfs_cache_pressure(默认100):

    sudo sysctl vm.vfs_cache_pressure=50
    

预防措施

  1. 监控系统:

    • 设置内存使用警报
    • 使用监控工具如Prometheus, Nagios等
  2. 定期维护:

    • 检查并优化内存泄漏的应用程序
    • 定期重启长时间运行的服务
  3. 硬件升级:

    • 增加物理内存
    • 考虑使用更高效的存储设备
  4. 应用优化:

    • 优化数据库配置
    • 调整JVM/其他运行时内存参数
    • 实现应用级的内存管理

通过以上措施,可以有效解决和预防Linux系统中的"Out of memory"问题。