一、下载镜像
% docker pull mongo
二、创建容器
% docker run -itd --name mongo -p 27017:27017 mongo --auth
三、设置账号和密码
% docker exec -it mongo mongo admin
MongoDB shell version v5.0.3
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("6db25575-f0fc-4312-90b3-d46971d9bd37") }
MongoDB server version: 5.0.3
================
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.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
https://community.mongodb.com
> db.createUser({ user:'pony',pwd:'666',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
Successfully added user: {
"user" : "pony",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
"readWriteAnyDatabase"
]
}
四、访问容器
1 docker命令形式
% docker exec -it mongo mongo pony
> db.auth('pony', '666')
2 mongo命令形式
% mongo 127.0.0.1:27017/admin -u pony -p 666