温馨提示×

如何配置ubuntu mongodb

小樊
39
2026-09-26 00:43:10
栏目: 云计算

下面按从零开始在 Ubuntu 上配置 MongoDB的思路,给你一套常用、可靠、适合生产/开发的配置流程(以 Ubuntu 22.04 / 24.04 + MongoDB 7.x 为例)。


一、安装 MongoDB(官方源,推荐)

1. 导入 MongoDB 官方 GPG Key

sudo apt update
sudo apt install -y gnupg curl
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor

2. 添加 MongoDB APT 源

echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

3. 安装 MongoDB

sudo apt update
sudo apt install -y mongodb-org

4. 启动并设置开机自启

sudo systemctl start mongod
sudo systemctl enable mongod

检查状态:

sudo systemctl status mongod

二、基础配置(/etc/mongod.conf)

MongoDB 主配置文件位置:

/etc/mongod.conf

常见配置示例(核心)

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
  logAppend: true

net:
  port: 27017
  bindIp: 127.0.0.1   # 只允许本机

security:
  authorization: enabled

修改后重启:

sudo systemctl restart mongod

三、创建管理员用户(重要)

1. 先无认证登录

mongosh

2. 创建管理员

use admin
db.createUser({
  user: "admin",
  pwd: "StrongPassword",
  roles: [{ role: "root", db: "admin" }]
})

3. 开启认证(如果还没开)

security:
  authorization: enabled

重启:

sudo systemctl restart mongod

四、创建业务数据库和用户(推荐)

use mydb
db.createUser({
  user: "appuser",
  pwd: "AppPassword",
  roles: [{ role: "readWrite", db: "mydb" }]
})

登录方式:

mongosh -u appuser -p AppPassword --authenticationDatabase mydb

五、允许远程访问(如需要)

1. 修改配置

net:
  bindIp: 0.0.0.0

⚠️ 务必配合防火墙 + 认证使用

2. 防火墙

sudo ufw allow from 你的IP to any port 27017

六、常用管理命令

# 查看日志
sudo tail -f /var/log/mongodb/mongod.log

# 备份
mongodump --uri="mongodb://user:pwd@localhost:27017/mydb"

# 恢复
mongorestore --uri="mongodb://user:pwd@localhost:27017/mydb" dump/

七、常见问题

✅ 启动失败
→ 看日志:/var/log/mongodb/mongod.log

✅ 权限错误
→ 检查 dbPath 目录权限:

sudo chown -R mongodb:mongodb /var/lib/mongodb

如果你需要:

  • Docker 方式
  • MongoDB 副本集(Replica Set)
  • 生产安全加固
  • Ubuntu + MongoDB + Node/Python 示例

告诉我你的使用场景,我可以直接给你对应配置。

0 踩