在 Ubuntu 上 MongoDB 占用资源(CPU / 内存 / 磁盘 IO)过高,通常不是单一原因,而是以下几类常见情况之一。你可以对照排查:
MongoDB 默认会使用 约 50% 的物理内存 作为 WiredTiger 缓存:
db.serverStatus().wiredTiger.cache
这是正常现象,不是内存泄漏。
✅ 解决方式:
cacheSizeGBstorage:
wiredTiger:
engineConfig:
cacheSizeGB: 2
每个连接都会占用内存:
db.serverStatus().connections
如果 current 很高(几百+),说明应用没用连接池或连接未释放。
✅ 解决:
net:
maxIncomingConnections: 500
这是 CPU 高的核心原因。
查看慢查询:
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find().sort({ ts: -1 }).limit(5)
常见原因:
COLLSCAN)✅ 解决:
db.collection.createIndex({ field: 1 })
explain() 分析db.collection.find({...}).explain("executionStats")
✅ 优化:
MongoDB 频繁写:
✅ 检查:
iostat -x 1
✅ 优化:
MongoDB 在内存紧张时容易卡死或高 CPU。
✅ 检查:
free -h
swapon --show
✅ 查看日志:
journalctl -u mongod
/var/log/mongodb/mongod.log
# 内存
free -h
db.serverStatus().wiredTiger.cache
# CPU
top
db.currentOp()
# 连接
db.serverStatus().connections
# 慢查询
db.system.profile.find().sort({ ts:-1 }).limit(10)
你可以贴出:
mongod.log 报错或警告top / htop 截图我可以帮你精准定位是哪一类问题。