1、查看目录
root@wielun:~# tree mongo
mongo
├── conf
│ └── mongod.conf
├── data
├── docker-compose.yml
└── logroot@wielun:~# cd mongo
root@wielun:~/mongo# chmod 777 log
2、配置docker-compose.yml
root@wielun:~/mongo# cat docker-compose.yml
version: '3'
services:mongo:image: mongo:5.0.5privileged: truerestart: alwayscontainer_name: mongohostname: mongoenvironment:TZ: Asia/ShanghaiMONGO_INITDB_ROOT_USERNAME: rootMONGO_INITDB_ROOT_PASSWORD: rootports:- 27017:27017volumes:- /etc/localtime:/etc/localtime:ro- ./conf/mongod.conf:/etc/mongod.conf- ./log:/var/log/mongodb- ./data:/data/dbcommand: mongod --config /etc/mongod.conf
3、配置mongod.conf
root@wielun:~/mongo# cat conf/mongod.conf
# mongod.conf# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/# Where and how to store data.
storage:dbPath: /data/dbjournal:enabled: true
# engine:
# mmapv1:
# wiredTiger:# where to write logging data.
systemLog:destination: filelogAppend: truepath: /var/log/mongodb/mongod.log# network interfaces
net:port: 27017bindIp: 0.0.0.0# how the process runs
processManagement:timeZoneInfo: /usr/share/zoneinfo#security:#authorization: enabled#operationProfiling:#replication:#sharding:## Enterprise-Only Options:#auditLog:#snmp:
4、配置mongo
root@wielun:~/mongo# docker-compose up -d
root@wielun:~/mongo# docker exec -it mongo /bin/bash
root@mongo:/# ps -ef #默认添加了--auth,代表需要账号密码登录
UID PID PPID C STIME TTY TIME CMD
mongodb 1 0 4 12:45 ? 00:00:00 mongod --config /etc/mongod.conf --authroot@mongo:/# mongo -u root -p
MongoDB shell version v5.0.5
Enter password:
...
---
> db.version()
5.0.5
> use admin
switched to db admin
> db.auth("root","root")
1
> show users
{"_id" : "admin.root","userId" : UUID("c5e91caa-4e50-445b-9537-c7066313b52b"),"user" : "root","db" : "admin","roles" : [{"role" : "root","db" : "admin"}],"mechanisms" : ["SCRAM-SHA-1","SCRAM-SHA-256"]
}> db.createUser({user:'root',pwd:'root',
... roles:[
... {
... "role" : "clusterAdmin",
... "db" : "admin"
... },
... {
... "role" : "readAnyDatabase",
... "db" : "admin"
... },
... {
... "role" : "readWrite",
... "db" : "test"
... }
... ]});
Successfully added user: {"user" : "root","roles" : [{"role" : "clusterAdmin","db" : "admin"},{"role" : "readAnyDatabase","db" : "admin"},{"role" : "readWrite","db" : "test"}]
}
> db.auth("root","root")
1
> db.test.insert({ item: "wielun"})
WriteResult({ "nInserted" : 1 })
创建用户:
db.createUser({user:'root',pwd:'root',
roles:[{"role" : "clusterAdmin","db" : "admin"},{"role" : "readAnyDatabase","db" : "admin"},{"role" : "readWrite","db" : "test"}
]});
5、查看结果
这里使用的MongoDB Compass进行连接