在 Debian 上优化 MongoDB,通常从 系统层、MongoDB 配置、存储、网络和应用使用方式 四个方面入手。下面给你一套比较完整、可落地的优化建议(适用于 MongoDB 4.x / 5.x / 6.x 在 Debian 10/11/12)。
mkfs.xfs /dev/sdX
MongoDB 官方强烈推荐 XFS,尤其是 WiredTiger 引擎。
MongoDB 明确不推荐透明大页。
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
开机自动关闭
cat > /etc/systemd/system/disable-thp.service <<EOF
[Unit]
Description=Disable Transparent Huge Pages
[Service]
Type=oneshot
ExecStart=/bin/sh -c "echo never > /sys/kernel/mm/transparent_hugepage/enabled"
ExecStart=/bin/sh -c "echo never > /sys/kernel/mm/transparent_hugepage/defrag"
[Install]
WantedBy=multi-user.target
EOF
systemctl enable disable-thp
systemctl start disable-thp
MongoDB 需要大量文件描述符。
vim /etc/security/limits.conf
mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 64000
mongod hard nproc 64000
避免内存抖动:
swapoff -a
如需永久关闭:
vim /etc/fstab
# 注释 swap 行
配置文件一般在:
/etc/mongod.conf
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 8 # 建议:物理内存的 50% 左右
例如 16G 内存:cacheSizeGB = 8
net:
port: 27017
bindIp: 0.0.0.0
maxIncomingConnections: 1000
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
verbosity: 0
/var/lib/mongodb # 数据
/var/log/mongodb # 日志
避免 IO 竞争。
mount -o remount,noatime /data
db.collection.createIndex({ field: 1 })
查看慢查询:
db.setProfilingLevel(1, { slowms: 100 })
explain("executionStats")db.collection.find({ x: 1 }).explain("executionStats")
db.collection.insertOne(doc, { writeConcern: { w: 1 } })
mongostat --host 127.0.0.1
mongotop
htop
iostat -x 1
| 问题 | 建议 |
|---|---|
| MongoDB 占用内存过高 | 合理设置 cacheSizeGB |
| IO 很高 | 用 SSD + XFS |
| 查询慢 | 检查索引 |
| 连接数过多 | 连接池 + 限制 maxIncomingConnections |
如果你愿意,可以告诉我:
我可以帮你给出 更精确的配置方案。