DEV Community

Cui Mingda
Cui Mingda

Posted on

How to deploy local mongoDB based on Docker

基于Docker在本地部署mongoDB数据库

下载mongoDB镜像

docker pull mongo
Enter fullscreen mode Exit fullscreen mode

也可以下载特定版本,TODO:如何看到所有的版本列表?

docker pull mongo:4.0.4
Enter fullscreen mode Exit fullscreen mode

这时候就可以直接启动mongoDB了,mongo是镜像的名字,mongodb是container的名字,但这个时候运行是前台运行。

docker run --name mongodb mongo
Enter fullscreen mode Exit fullscreen mode

按ctrl+C退出以后,container就停止运行了,如果要找到这个container,需要-a参数:

docker ps -a
Enter fullscreen mode Exit fullscreen mode

关闭并删除,这里应该已经关闭了,只要删除就好

docker stop mongodb
docker rm mongodb
Enter fullscreen mode Exit fullscreen mode

重新在后台运行,并设置版本号

docker run -d -p 27017-27019:27017-27019 --name mongodb mongo
Enter fullscreen mode Exit fullscreen mode

这个时候应该可以看到运行的进程

docker ps
Enter fullscreen mode Exit fullscreen mode

登录到对应的服务器

docker exec -it mongodb bash
Enter fullscreen mode Exit fullscreen mode

进入到mongoDB命令行

mongo
Enter fullscreen mode Exit fullscreen mode

显示数据库列表

show dbs
Enter fullscreen mode Exit fullscreen mode

选择一个数据库,比如abc,如果这个数据库不存在,貌似就直接创建

use abc
Enter fullscreen mode Exit fullscreen mode

在people表中插入一条记录

db.people.save({ firstName: "Mingda", lastName: "Cui" })
db.people.save({ firstName: "Shanshan", lastName: "Jin" })
Enter fullscreen mode Exit fullscreen mode

查询所有记录

db.people.find()
Enter fullscreen mode Exit fullscreen mode

查询特定记录

db.people.find({ lastName: "Jin" })
Enter fullscreen mode Exit fullscreen mode

Top comments (0)