docker启动mongo 启动脚本如下
docker stop mongodb && docker rm mongodb
docker run -p 27017:27017 \
--name mongodb \
--network common-network \
-v /mydata/mongo/db:/data/db \
-v /mydata/mongo/mongo.conf:/data/configdb/mongo.conf \
-e TZ=Asia/Shanghai \
-d mongo -f /data/configdb/mongo.conf
如果不存在mongo镜像会先拉取镜像,之后创建容器并启动容器
mongo.conf
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
storage:
dbPath: /data/db
net:
port: 27017
bindIp: 0.0.0.0
容器启动后进入容器,并启动mongo客户端
docker exec -it mongodb mongo
如果端口和ip需要指定 如下
docker exec -it mongodb mongo --host 127.0.0.1 --port 27017
查看原始用戶:
> use admin
switched to db admin
> show users
{
"_id" : "admin.root",
"userId" : UUID("62da72a9-5aba-44ae-a367-0919e8dbe8b6"),
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
删除默认的用户
> db.dropUser("root")
新增用户
> db.createUser({user:"root",pwd:"root",roles:[{role:"root",db:"admin"}]});
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
认证新增的用户
> db.auth("root","root")
1
创建一个db
> use appdb
switched to db appdb
创建管理给db的用户
> db.createUser({user:"appdb",pwd:"appdb",roles:[{role:"dbOwner",db:"appdb"}]});
Successfully added user: {
"user" : "appdb",
"roles" : [
{
"role" : "dbOwner",
"db" : "appdb"
}
]
}
> db.auth("appdb","appdb")
1
1.数据库用户角色:read、readWrite;
2.数据库管理角色:dbAdmin、dbOwner、userAdmin;
3.集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4.备份恢复角色:backup、restore
5.所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6.超级用户角色:root
开启认证权限登陆
docker exec -it mongodb mongo --host 127.0.0.1 --port 27017 -uappdb -pappdb --authenticationDatabase=appdb
[root@node01 mongo]# docker exec -it mongodb mongo --host 127.0.0.1 --port 27017 -uappdb -pappdb --authenticationDatabase=appdb
MongoDB shell version v5.0.5
connecting to: mongodb://127.0.0.1:27017/?authSource=appdb&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("3480a2cd-7683-4b4e-bf90-1e033db9bb53") }
MongoDB server version: 5.0.5
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
> show dbs
appdb 0.000GB
>