下面是在 Ubuntu 上配置 MongoDB 的常用做法(以 Ubuntu 22.04 / 20.04 为例,MongoDB 6.x / 7.x 通用思路)。
sudo apt update
sudo apt upgrade -y
curl -fsSL https://pgp.mongodb.com/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
若为 20.04,把
jammy改为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
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
net:
port: 27017
bindIp: 127.0.0.1 # 若远程访问改为 0.0.0.0(需配合安全配置)
security:
authorization: enabled
修改后重启:
sudo systemctl restart mongod
进入 MongoDB:
mongosh
创建管理员:
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
启用鉴权(/etc/mongod.conf):
security:
authorization: enabled
重启:
sudo systemctl restart mongod
登录:
mongosh -u admin -p --authenticationDatabase admin
sudo ufw allow 27017
⚠️ 公网暴露 MongoDB 非常危险,建议:
# 启动
sudo systemctl start mongod
# 停止
sudo systemctl stop mongod
# 重启
sudo systemctl restart mongod
# 查看日志
tail -f /var/log/mongodb/mongod.log
如果你需要:
可以告诉我你的使用场景。