Docker 安装 MongoDB

通过Docker可以快速安装、体验MongoDB,非常方便实验。

拉取MongoDB官方镜像

[root@test136 ~]# docker pull mongo:4.4.0
4.4.0: Pulling from library/mongo
f08d8e2a3ba1: Pull complete
3baa9cb2483b: Pull complete
94e5ff4c0b15: Pull complete
1860925334f9: Pull complete
9d42806c06e6: Pull complete
31a9fd218257: Pull complete
5bd6e3f73ab9: Pull complete
f6ae7a64936b: Pull complete
80fde2cb25c5: Pull complete
1bec62fe62fc: Pull complete
2cf4970a1653: Pull complete
39fac3226e16: Pull complete
86bca9c64faf: Pull complete
Digest: sha256:df9eca84736a666d5f7e7a09aeb8a6d8d073698d5b7349400f10ee75812e0e95
Status: Downloaded newer image for mongo:4.4.0
docker.io/library/mongo:4.4.0

​官方镜像地址​

指定容器并运行

[root@test136 ~]# docker run -itd --name mongo -p 27017:27017 mongo:4.4.0 --auth
06fcde8648ace815699d88dcbbd0f7fead1f8191db8b06f5eae952a29863a574

参数说明:

  • -p 27017:27017 :映射容器服务的 27017 端口到宿主机的 27017 端口。外部可以直接通过 宿主机 ip:27017 访问到 mongo 的服务。
  • –auth:需要密码才能访问容器服务。

登录容器

[root@test136 ~]# docker exec -it mongo mongo admin
MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("55e767f9-b59d-4538-a622-7edb9936c6c6") }
MongoDB server version: 4.4.0
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:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'}]});
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
> db.auth('admin', '123456') --登录
1
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB

至此就完成了,MongoDB的安装。