拉取最新版本的 MongoDB 镜像:
bash
$ sudo docker pull mongo:latest
在本地预先创建好 db
和 configdb
目录, 用于映射 MongoDB 容器内的 /data/db
和 /data/configdb
目录。
使用以下命令来运行 MongoDB 容器:
shell
$ sudo docker run -itd --name mongo --privileged=true -p 27017:27017 -v /home/ubuntu/docker/mongo/db:/data/db -v /home/ubuntu/docker/mongo/configdb:/data/configdb docker.io/mongo:latest --auth
-itd
(以交互的方式,新建一个模拟终端运行容器)-i
(在后台运行容器,并且打印容器ID)-t
(分配一个伪TTY)-d
(保持STDIN打开状态)
--name
(给容器起一个名字方便管理)--privileged=true
(使容器内的 root 拥有真正的 root 权限)-p 27017:27017
(将容器的27017端口映射到主机的27017端口)-v /home/ubuntu/docker/mongo/db:/data/db
(文件挂载目录)-v /home/ubuntu/docker/mongo/configdb:/data/configdb
(配置文件路径)--auth
(需要密码才能访问容器服务)
通过 docker ps
命令查看容器的运行信息:
shell
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b0fb7817a762 mongo:latest "docker-entrypoint.s..." 50 seconds ago Up 50 seconds 0.0.0.0:27017->27017/tcp, :::27017->27017/tcp mongo
使用以下命令添加用户并设置密码:
shell
$ sudo docker exec -it mongo mongosh admin
Current Mongosh Log ID: 65085540d0acf268bdf76e9c
Connecting to: mongodb://127.0.0.1:27017/admin?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.6
Using MongoDB: 7.0.1
Using Mongosh: 1.10.6
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.
admin> db.createUser({user:'admin', pwd:'用户admin的密码', roles:[{role:'userAdminAnyDatabase',db:'admin'},{role:'readWriteAnyDatabase',db:'admin'}]});
{ ok: 1 }
admin> db.auth('admin', '用户admin的密码')
{ ok: 1 }
admin> exit
使用 mongosh
连接和断开 MongoDB 数据库:
shell
$ sudo docker exec -it mongo mongosh --port 27017 -u 'admin' -p '用户admin的密码' --authenticationDatabase 'admin'
Current Mongosh Log ID: 65085721cfe61730ead44cfd
Connecting to: mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&authSource=admin&appName=mongosh+1.10.6
Using MongoDB: 7.0.1
Using Mongosh: 1.10.6
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
test> exit
上面创建用户时少添加了 dbAdminAnyDatabase
角色, 所以现在修改用户的权限:
shell
$ sudo docker exec -it mongo mongosh admin
Current Mongosh Log ID: 6508588447e7463f155ee1da
Connecting to: mongodb://127.0.0.1:27017/admin?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.6
Using MongoDB: 7.0.1
Using Mongosh: 1.10.6
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
admin> db.auth('admin', '用户admin的密码')
{ ok: 1 }
admin> db.updateUser('admin', {roles:[{role:'userAdminAnyDatabase',db:'admin'},{role:'readWriteAnyDatabase',db:'admin'},{role:'dbAdminAnyDatabase',db:'admin'}]});
{ ok: 1 }
admin> exit