今天起了一台mongo,完整记录下。
docker pull
docker pull mongo # 下载latest,根据个人需要去查tag吧~
docker pull mongo:4.0.3 # 我们只使用4.0.3版本 :-)
docker volume create
mongo的数据最好独立出来存储,使用volume是最佳选择
docker volume create mongodbdata
docker run
docker run --name mongodb -p 27017:27017 -v mongodbdata:/data/db -d mongo:4.0.3 --auth
指令 | 说明 |
---|---|
--name | 容器命名 |
-p 27017:27017 | 映射端口,因为需要外网访问 |
-v mongodbdata:/data/db | 将上面的volume映射到容器内目录/data/db, 它是mongo数据存储目录。 |
-d | demon后台服务模式 |
--auth | 开启密码认证,如果不用权限,省略此项 |
配置密码权限
因为我想外网开放,所以必须要启用auth。默认没有任何账户的。
控制台登陆进去
docker exec -it 4 bash
创建root用户
按如下console设置用户密码
$ docker exec -it 4 bash
root@46ac2c8cfb4e:/# mongo
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c3b2148b-681d-44f9-9afe-178ec6bd1f75") }
MongoDB server version: 4.0.3
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
> show dbs;
2019-08-13T03:04:22.908+0000 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0, lsid: { id: UUID(\"c3b2148b-681d-44f9-9afe-178ec6bd1f75\") }, $db: \"admin\" }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:67:1
shellHelper.show@src/mongo/shell/utils.js:860:19
shellHelper@src/mongo/shell/utils.js:750:15
@(shellhelp2):1:1
> use admin
switched to db admin
> db.createUser({ user: 'username1', pwd: 'password1', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })
Successfully added user: {
"user" : "username1",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
创建普通用户
# mongo -u username1 -p password1 --authenticationDatabase admin
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("ae1948e9-79af-43d2-a029-b38996a34160") }
MongoDB server version: 4.0.3
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB
> use user
switched to db user
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB
> db.createUser({ user: 'user', pwd: 'password', roles: [ { role: "readWrite", db: "user" } ] })
Successfully added user: {
"user" : "user",
"roles" : [
{
"role" : "readWrite",
"db" : "user"
}
]
}
普通用户登陆
# mongo -u user -p password user
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017/user
Implicit session: session { "id" : UUID("5f3fc348-f608-4c64-8bc8-5ffad80e6abb") }
MongoDB server version: 4.0.3
> show dbs;
>