接下里学习docker安装MongoDB。
下载MongoDB镜像
docker pull mongo
运行安装命令(安装MongoDB容器):
docker run --name mongodb -p 27017:27017 -d mongo --auth
为MongoDB添加管理员用户
进入MongoDB
docker exec -it 51a5b5e05fe4 mongo admin
51a5b5e05fe4 :MongoDB容器的id
创建一个 admin 管理员账号:
db.createUser({ user: 'root', pwd: 'root', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
退出exit
上述操作记录
docker exec -it 51a5b5e05fe4 mongo admin
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("04ebc64f-df58-4931-8a68-4824ed032dd4") }
MongoDB server version: 4.0.10
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
> 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 51a5b5e05fe4 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 51a5b5e05fe4 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 51a5b5e05fe4 mongo admin
对 zy 进行身份认证:
db.auth("zy","zy123456");
切换数据库
use app
添加数据
db.test.save({name:"zhangsan"});
上述操作记录
[root@localhost ~]# docker exec -it 51a5b5e05fe4 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");
> use app
switched to db app
> db.test.save({name:"zhangsan"});
WriteResult({ "nInserted" : 1 })
> exit
bye