温馨提示×

如何 Ubuntu 配置 MongoDB

小樊
43
2026-09-16 23:06:21
栏目: 云计算

下面是在 Ubuntu 上配置 MongoDB 的常用做法(以 Ubuntu 22.04 / 20.04 为例,MongoDB 6.x / 7.x 通用思路)。


一、安装 MongoDB

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 导入 MongoDB 官方 GPG 密钥

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

3. 添加 MongoDB 源

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

4. 安装 MongoDB

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 非常危险,建议:

  • 使用 SSH 隧道
  • 或绑定内网 IP
  • 或启用认证 + 防火墙

六、常用命令

# 启动
sudo systemctl start mongod

# 停止
sudo systemctl stop mongod

# 重启
sudo systemctl restart mongod

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

如果你需要:

  • ✅ Docker 方式
  • ✅ 远程访问配置
  • ✅ 副本集 / 集群
  • ✅ 云服务器安全方案

可以告诉我你的使用场景。

0 踩