下面给你一个在 Linux 上配置 MongoDB 的完整流程,以 MongoDB 6.x / 7.x + Ubuntu / Debian / CentOS 为例(其他发行版原理相同)。
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
jammy是 Ubuntu 22.04,20.04 用focal
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
查看状态:
sudo systemctl status mongod
默认配置文件:
/etc/mongod.conf
默认只监听 127.0.0.1,远程访问需修改:
net:
port: 27017
bindIp: 0.0.0.0
⚠️ 生产环境不建议直接
0.0.0.0,应配合防火墙 + 认证
security:
authorization: enabled
然后重启:
sudo systemctl restart mongod
storage:
dbPath: /var/lib/mongodb
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
mongosh
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [{ role: "root", db: "admin" }]
})
登录:
mongosh -u admin -p --authenticationDatabase admin
mongosh "mongodb://admin:StrongPassword@服务器IP:27017/?authSource=admin"
sudo ufw allow 27017
sudo firewall-cmd --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
✅ 启用认证
✅ 不使用默认端口
✅ 限制 bindIp
✅ 使用专用用户运行 MongoDB
✅ 定期备份
✅ 开启 TLS(SSL)
| 问题 | 解决办法 |
|---|---|
mongod: command not found |
未安装或 PATH 问题 |
| 端口被占用 | `netstat -tunlp |
| 无法远程连接 | 检查 bindIp、防火墙、认证 |
如果你告诉我:
我可以给你一份完全定制化的 MongoDB 配置方案。