Docker 部署 MongoDB 服务

2023-09-17  本文已影响0人  何小有

拉取最新版本的 MongoDB 镜像:

$ sudo docker pull mongo:latest

在本地预先创建好 dbconfigdb 目录, 用于映射 MongoDB 容器内的 /data/db/data/configdb 目录。

使用以下命令来运行 MongoDB 容器:

$ 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

通过 docker ps 命令查看容器的运行信息:

$ 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

使用以下命令添加用户并设置密码:

$ 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 数据库:

$ 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 角色, 所以现在修改用户的权限:

$ 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
上一篇下一篇

猜你喜欢

热点阅读