在 Debian 上“限制 MongoDB”通常指 限制资源使用、访问权限或网络暴露。下面按常见需求分类说明,你可以按需组合使用。
编辑 MongoDB 的 systemd 服务:
sudo systemctl edit mongod
添加以下内容(示例:限制内存 2G,CPU 50%):
[Service]
MemoryMax=2G
CPUQuota=50%
IOWeight=100
保存后执行:
sudo systemctl daemon-reload
sudo systemctl restart mongod
✅ 优点:
编辑配置文件:
sudo nano /etc/mongod.conf
添加或修改:
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 2
重启:
sudo systemctl restart mongod
⚠️ 注意:
编辑配置:
security:
authorization: enabled
重启后创建管理员:
mongosh
use admin
db.createUser({
user: "admin",
pwd: "strongpassword",
roles: [ { role: "root", db: "admin" } ]
})
登录方式:
mongosh -u admin -p --authenticationDatabase admin
✅ 防止未授权访问
例如只允许读写某个库:
use mydb
db.createUser({
user: "appuser",
pwd: "password",
roles: [ { role: "readWrite", db: "mydb" } ]
})
net:
bindIp: 127.0.0.1
port: 27017
或允许多个 IP:
bindIp: 127.0.0.1,192.168.1.10
重启 MongoDB。
sudo ufw allow from 192.168.1.0/24 to any port 27017
sudo ufw deny 27017
✅ 防止公网直接访问 MongoDB
net:
maxIncomingConnections: 100
默认是 65536,建议按业务调整。
net:
http:
enabled: false
(MongoDB 4.x+ 已默认关闭)
docker run -d \
--memory=2g \
--cpus=1 \
-p 127.0.0.1:27017:27017 \
mongo
✅ 最小安全配置示例
bindIp: 127.0.0.1
authorization: enabled
net.maxIncomingConnections: 100
storage.wiredTiger.engineConfig.cacheSizeGB: 2
✅ 配合 systemd + 防火墙
❌ MongoDB 默认 无认证 + 监听 0.0.0.0 → 非常危险
❌ 只限制内存 ≠ 安全
❌ 公网开放 27017 端口 = 高风险
如果你愿意,可以告诉我:
我可以给你一套 针对你场景的完整限制方案。