下面从 CentOS 系统层面 + MongoDB 配置层面 给你一套实用的 MongoDB 优化方案,适用于 CentOS 7 / 8 / Rocky / Alma 等相近系统。
MongoDB 官方强烈建议关闭 THP,否则会导致内存碎片和性能下降。
# 临时关闭
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
# 永久关闭(CentOS 7)
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 对文件句柄要求很高。
# 查看当前限制
ulimit -n
# 修改
vi /etc/security/limits.conf
添加:
* soft nofile 64000
* hard nofile 64000
* soft nproc 64000
* hard nproc 64000
SELinux 会影响 MongoDB 性能和稳定性。
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
MongoDB 官方推荐 XFS,避免 ext4。
df -T
如果不是 XFS,建议重新格式化数据盘(注意备份)。
vi /etc/sysctl.conf
添加:
vm.swappiness = 1
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5
net.core.somaxconn = 4096
net.ipv4.tcp_fin_timeout = 30
生效:
sysctl -p
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8 # 推荐 = 物理内存 * 50% 且不超过 10G
storage:
journal:
enabled: true
net:
port: 27017
bindIp: 0.0.0.0
maxIncomingConnections: 10000
operationProfiling:
mode: off
或只记录慢查询:
operationProfiling:
mode: slowOp
slowOpThresholdMs: 200
db.collection.createIndex({ field: 1 })
db.collection.createIndex({ a: 1, b: -1 })
查看慢查询:
db.currentOp()
db.system.profile.find().sort({ ts: -1 }).limit(5)
❌ 错误:
db.collection.find({ name: /abc/ })
✅ 正确:
db.collection.find({ name: "abc" })
db.collection.find({ age: 18 }, { name: 1, _id: 0 })
mongod --replSet rs0
_id)mongostat --host 127.0.0.1
mongotop
storage:
dbPath: /data/mongo
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 8
systemLog:
destination: file
path: /var/log/mongo/mongod.log
logAppend: true
net:
port: 27017
bindIp: 0.0.0.0
maxIncomingConnections: 10000
operationProfiling:
mode: slowOp
slowOpThresholdMs: 200
如果你愿意,可以告诉我:
我可以给你 更精准的优化方案(甚至直接帮你调参)。