docker pull mongo
下载如下
Using default tag: latest
Trying to pull repository docker.io/library/mongo ...
latest: Pulling from docker.io/library/mongo
9ff7e2e5f967: Pull complete
59856638ac9f: Pull complete
6f317d6d954b: Pull complete
a9dde5e2a643: Pull complete
815c6aedc001: Pull complete
8566b2594855: Pull complete
01c9fe451980: Pull complete
5c9e7bc12cea: Pull complete
c64dd2c4159a: Pull complete
c283cca25ace: Pull complete
051b3304da4a: Pull complete
ab4327c34933: Pull complete
80003bc32b79: Pull complete
Digest: sha256:05f12b17aa35948848c0d3f0198ce10c7f3e37438724911d0d8f9b6643535599
Status: Downloaded newer image for docker.io/mongo:latest
docker images mongo
docker run --name mongodb -p 27017:27017 -d mongo --auth
为MongoDB添加管理员用户
进入MongoDB
docker exec -it f61df2709f78 mongo admin
f61df2709f78是你的MongoDB容器的id
创建一个 admin 管理员账号:
db.createUser({ user: 'root', pwd: 'root', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
退出
exit
操作如下
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("176dd8db-5cd5-4165-8e06-b8eb9a62501a") }
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 f61df2709f78 mongo admin
对 admin 进行身份认证:
PS:就是上一步创建的管理员账号密码
db.auth("root","root");
创建 用户、密码和数据库:
db.createUser({ user: 'swen', pwd: 'swen123456', roles: [ { role: "readWrite", db: "app" } ] });
操作如下
[root@bogon ~]# docker exec -it f61df2709f78 mongo admin
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("ee4b71ce-cd2d-4a60-97a7-9a2ea7c30017") }
MongoDB server version: 4.0.10
> db.auth("root","root");
1
> db.createUser({ user: 'swen', pwd: 'swen123456', roles: [ { role: "readWrite", db: "app" } ] });
Successfully added user: {
"user" : "swen",
"roles" : [
{
"role" : "readWrite",
"db" : "app"
}
]
}
> exit
bye
登录 APP 数据库
以 admin 用户身份进入mongo :
docker exec -it f61df2709f78 mongo admin
对 swen 进行身份认证:
db.auth("swen","swen123456")
切换数据库
use app
操作如下
[root@bogon ~]# docker exec -it f61df2709f78 mongo admin
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("d551ced7-b8c8-48d3-a5f5-32a4813e3d7c") }
MongoDB server version: 4.0.10
> db.auth("swen","swen123456")
1
> use app
switched to db app
> db.test.save({name:"zhangsan"})
WriteResult({ "nInserted" : 1 })
> exit
bye