在 Debian 上优化 MongoDB,可以从 系统层、MongoDB 配置、存储、应用层 四个方面来做。下面给你一套 生产环境常用优化方案,适用于 Debian 10/11/12。
推荐使用 XFS(首选) 或 ext4:
mkfs.xfs /dev/sdb
挂载参数(/etc/fstab):
defaults,noatime,nodiratime
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
编辑:
vim /etc/security/limits.conf
添加:
mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 64000
mongod hard nproc 64000
systemctl edit mongod
确认:
LimitNOFILE=64000
LimitNPROC=64000
位置一般在:
/etc/mongod.conf
MongoDB 默认会使用大量内存(WiredTiger 缓存):
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 4 # 建议设置为物理内存的 50% 左右
例如:
storage:
journal:
enabled: true
生产环境 不要关闭 journal。
net:
port: 27017
bindIp: 0.0.0.0 # 生产环境建议只绑定内网 IP
maxIncomingConnections: 1000
不使用的功能建议关闭:
setParameter:
enableLocalhostAuthBypass: false
MongoDB 对随机 IO 非常敏感。
storage:
dbPath: /data/mongo
systemLog:
path: /var/log/mongodb/mongod.log
并确保:
/data/mongo 在 SSD/var/log 在系统盘已经在第一步完成 ✅
db.collection.createIndex({ field: 1 })
查看慢查询:
db.setProfilingLevel(1, { slowms: 100 })
db.collection.find({}).explain("executionStats")
目标:
COLLSCAN ❌
IXSCAN ✅
Debian 自带版本 较旧,建议用官方源:
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | gpg --dearmor > /usr/share/keyrings/mongodb-server-7.0.gpg
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/debian bookworm/mongodb-org/7.0 main" > /etc/apt/sources.list.d/mongodb-org.list
apt update
apt install -y mongodb-org
Debian 稳定版内核偏旧,IO 性能一般:
apt install linux-image-amd64
mongostat
mongotop
系统:
iostat -x 1
htop
free -h
❌ 关闭 journal
❌ 不设 cacheSizeGB
❌ 使用 HDD
❌ 用 root 运行 MongoDB
❌ 索引缺失
[ ] 关闭 THP
[ ] 调整 ulimit
[ ] 使用 XFS + SSD
[ ] 设置 cacheSizeGB
[ ] 使用索引
[ ] 官方 MongoDB 版本
如果你愿意,可以告诉我:
我可以给你 一份针对你环境的定制优化配置。