在 CentOS 上优化 MongoDB 配置,通常从系统层、MongoDB 配置、存储与索引、监控几个方面入手。下面给你一套实用、可落地的优化建议(适用于 CentOS 7/8 + MongoDB 4.x/5.x/6.x)。
MongoDB 官方明确要求关闭 THP,否则会导致延迟抖动。
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
永久生效(systemd):
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 && echo never > /sys/kernel/mm/transparent_hugepage/defrag"
[Install]
WantedBy=multi-user.target
EOF
systemctl enable disable-thp
systemctl start disable-thp
编辑 /etc/security/limits.conf:
mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 32000
mongod hard nproc 32000
如果使用 systemd,还需在:
/etc/systemd/system/mongod.service.d/limits.conf
[Service]
LimitNOFILE=64000
LimitNPROC=32000
然后:
systemctl daemon-reexec
/dev/sdb /data xfs defaults,noatime,nodiratime 0 0
开发/测试环境:
setenforce 0
sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
生产环境建议配置策略而不是关闭。
常见路径:/etc/mongod.conf
storage:
dbPath: /data/db
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 8 # 物理内存的 50%~70%
collectionConfig:
blockCompressor: snappy
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 0.0.0.0
maxIncomingConnections: 65536
operationProfiling:
mode: slowOp
slowOpThresholdMs: 100
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8
经验值:
storage:
journal:
commitIntervalMs: 100
explain("executionStats")db.setProfilingLevel(1, 100)
db.system.profile.find().sort({ts:-1}).limit(10)
如果是生产环境:
w: "majority"rs.status()
rs.conf()
db.serverStatus()
db.stats()
mongostat
mongotop
| 问题 | 原因 | 解决 |
|---|---|---|
| CPU 高 | 缺索引 | 建索引 |
| 磁盘 IO 高 | 日志/数据同盘 | 分离 |
| 延迟抖动 | THP | 关闭 |
| 内存爆 | cacheSize 过大 | 调小 |
| 连接数满 | 连接未释放 | 连接池 |
storage:
dbPath: /data/db
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 10
net:
maxIncomingConnections: 65536
operationProfiling:
mode: slowOp
slowOpThresholdMs: 50
如果你愿意,可以告诉我:
我可以直接帮你定制一份 mongod.conf + 系统参数方案。