docker安装MongoDB,配置用户名密码。

下载MongoDB镜像

docker pull mongo

运行安装命令(安装MongoDB容器):

docker run --name mongodb -p 27017:27017 -d mongo --auth

为MongoDB添加管理员用户

查看 MongoDB容器的id

docker container ls -a

进入MongoDB

“e6a75d006536”:MongoDB容器的id

docker exec -it e6a75d006536 mongo admin

 

创建一个 admin 管理员账号

db.createUser({ user: 'root', pwd: 'root', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });

退出

exit

上述操作记录 

[root@localhost data]# docker exec -it e6a75d006536 mongo admin
MongoDB shell version v4.4.2
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2f957900-cf82-4c5f-b307-0c9608a547d9") }
MongoDB server version: 4.4.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
	https://community.mongodb.com
> db.createUser({ user: 'root', pwd: 'root', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
Successfully added user: {
	"user" : "root",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
> exit
bye

创建普通用户、密码和数据库

以 admin 用户身份进入mongo

docker exec -it e6a75d006536 mongo admin

对 admin 进行身份认证:
PS:就是上一步创建的管理员账号密码

db.auth("root","root");

创建 用户、密码和数据库:

db.createUser({ user: 'zy', pwd: 'zy123456', roles: [ { role: "readWrite", db: "app" } ] });

退出

exit

上述操作记录 

[root@localhost ~]# docker exec -it e6a75d006536 mongo admin
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("eccdd06a-f2e0-40f8-924d-173a3cbb7198") }
MongoDB server version: 4.0.10

> db.auth("root","root");
1
> db.createUser({ user: 'zy', pwd: 'zy123456', roles: [ { role: "readWrite", db: "app" } ] });
Successfully added user: {
	"user" : "swen",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "app"
		}
	]
}
> exit
bye

登录 APP 数据库

以 admin 用户身份进入mongo :

docker exec -it e6a75d006536 mongo admin

对 zy 进行身份认证:

db.auth("zy","zy123456");

切换数据库

use app

添加数据

db.test.save({name:"zhangsan"});

上述操作记录

[root@localhost ~]# docker exec -it e6a75d006536 mongo admin
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("48474e4e-b226-401c-ab00-62b1bae80def") }
MongoDB server version: 4.0.10
> db.auth("zy","zy123456");
1
> use app
switched to db app
> db.test.save({name:"zhangsan"});
WriteResult({ "nInserted" : 1 })
> exit
bye

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页