温馨提示×

centos如何优化mongodb

小樊
35
2026-07-20 03:23:02
栏目: 云计算

下面从 CentOS 系统层面 + MongoDB 配置层面 给你一套实用的 MongoDB 优化方案,适用于 CentOS 7 / 8 / Rocky / Alma 等相近系统。


一、系统层面优化(非常重要)

1. 关闭 Transparent Huge Pages(必须)

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

2. 调整 ulimit(打开文件数)

MongoDB 对文件句柄要求很高。

# 查看当前限制
ulimit -n

# 修改
vi /etc/security/limits.conf

添加:

* soft nofile 64000
* hard nofile 64000
* soft nproc 64000
* hard nproc 64000

3. 关闭 SELinux(可选但推荐)

SELinux 会影响 MongoDB 性能和稳定性。

setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

4. 使用 XFS 文件系统(强烈推荐)

MongoDB 官方推荐 XFS,避免 ext4。

df -T

如果不是 XFS,建议重新格式化数据盘(注意备份)。


5. 内核参数优化

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

二、MongoDB 配置优化(mongod.conf)

1. 内存限制(防止吃光内存)

storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 8  # 推荐 = 物理内存 * 50% 且不超过 10G

2. 开启 journal(数据安全)

storage:
  journal:
    enabled: true

3. 网络与连接数

net:
  port: 27017
  bindIp: 0.0.0.0
  maxIncomingConnections: 10000

4. 关闭慢查询日志(高并发场景)

operationProfiling:
  mode: off

或只记录慢查询:

operationProfiling:
  mode: slowOp
  slowOpThresholdMs: 200

三、MongoDB 使用优化

1. 创建合适索引(核心)

db.collection.createIndex({ field: 1 })
db.collection.createIndex({ a: 1, b: -1 })

查看慢查询:

db.currentOp()
db.system.profile.find().sort({ ts: -1 }).limit(5)

2. 避免全表扫描

❌ 错误:

db.collection.find({ name: /abc/ })

✅ 正确:

db.collection.find({ name: "abc" })

3. 合理使用投影(减少 IO)

db.collection.find({ age: 18 }, { name: 1, _id: 0 })

四、MongoDB 集群优化(如果是副本集 / 分片)

副本集建议

  • 至少 3 节点
  • 使用 仲裁节点 避免偶数节点
mongod --replSet rs0

分片建议

  • shard key 选择 高频查询字段
  • 避免单调递增 key(如 _id

五、监控与维护

1. 使用 mongostat / mongotop

mongostat --host 127.0.0.1
mongotop

2. 常用监控指标

  • QR / QW(队列)
  • Faults(缺页)
  • Res(内存)
  • Index Miss

六、常见性能问题排查顺序

  1. 是否关闭 THP
  2. 是否索引缺失
  3. 是否内存不足
  4. 是否磁盘 IO 成为瓶颈
  5. 是否有慢查询

七、示例优化配置(生产推荐)

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

如果你愿意,可以告诉我:

  • MongoDB 版本
  • 数据量(GB / 文档数)
  • QPS / 并发
  • 是否副本集或分片

我可以给你 更精准的优化方案(甚至直接帮你调参)。

0