dockerpullmongo:latest---安装mongodb
docker run -p27017:27017-v /usr/local/mongodb/datadb:/data/db--name mongodb -d mongo --auth
---带密码启动
第二种启动
dockerrun -d --name mongo -v /usr/local/mongodb/datadb:/data/db -p27017:27017-e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=root --privileged=truemongo
进入容器设置admin密码
dockerexec-it mongodb mongo admin
db.createUser({user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db:'admin'},"readWriteAnyDatabase"]});---设置admin密码
尝试登录admin
>db.auth('admin','123456')
新建用户库
>usetest>db.createUser({user:"hua",pwd:"123456",roles:[{role:'readWrite',db:'test'}]})
登录用户
dockerexec-it mongodb bash ---进入容器mongo -u hua -p 123456test---登录test库创建集合> db.createCollection("test"){"ok": 1 }> show collectionstest
备份数据库
dockerexec-itmongodbbash---进入容器mongodump-h127.0.0.1--port27017-u=hua-p=123456-dtest-o/data/db
tar -zcvf test.tar.gz /data/db/test--压缩数据库文件docker cp f92f51b8c5a7:/data/db/test.tar.gz /home---从容器中拷贝文件到宿主目录/homecd /usr/local/mongodb/datadb---也可到宿主这目录找到备份数据库tar -zxvf /home/test.tar.gz 解压
恢复数据库
docker cp /home/test/test.bson f92f51b8c5a7:/data/db/test/mongorestore -h localhost:27017 -u hua -p 123456 -dtest--dir /data/db --authenticationDatabase=test