温馨提示×

MongoDB在Debian上的认证如何设置

小樊
36
2025-11-27 11:17:44
栏目: 云计算

在Debian上设置MongoDB的认证,可以按照以下步骤进行:

1. 安装MongoDB

首先,确保你已经安装了MongoDB。如果没有安装,可以使用以下命令进行安装:

sudo apt update
sudo apt install -y mongodb

2. 启动MongoDB服务

启动MongoDB服务并设置为开机自启动:

sudo systemctl start mongod
sudo systemctl enable mongod

3. 配置MongoDB启用认证

编辑MongoDB的配置文件 /etc/mongod.conf,找到 security 部分并启用认证:

security:
  authorization: enabled

4. 重启MongoDB服务

保存配置文件后,重启MongoDB服务以应用更改:

sudo systemctl restart mongod

5. 创建管理员用户

使用 mongo shell 连接到MongoDB,并创建一个管理员用户:

mongo

mongo shell 中执行以下命令:

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

6. 使用管理员用户认证

重新连接到MongoDB并使用新创建的管理员用户进行认证:

mongo -u admin -p your_password --authenticationDatabase admin

7. 创建其他数据库用户

mongo shell 中,切换到目标数据库并创建用户:

use mydatabase
db.createUser({
  user: "myuser",
  pwd: "mypassword",
  roles: ["readWrite", "dbOwner"]
})

8. 使用新用户认证

使用新创建的用户连接到MongoDB:

mongo -u myuser -p mypassword --authenticationDatabase mydatabase

9. 配置防火墙(可选)

如果你有防火墙规则,确保允许MongoDB的默认端口(27017):

sudo ufw allow 27017

10. 验证配置

确保所有配置都正确无误,并且用户可以正常访问数据库。

通过以上步骤,你可以在Debian上成功设置MongoDB的认证。

0