第一步
获得mongo镜像,命令如下,
# 拉取mongo镜像 docker pull mongo # 查看本地库mongo镜像 docker images mongo
第二步
启动mongo镜像,如下
# 启动mongo镜像 docker run -itd -p --name mongo-server mongo bash # 查看mongo进程 docker ps -a
第三步
进入容器并启动mongo,如下
# 进入mongo容器,其中‘mongo-server'是mongo容器别名 docker exec -it mongo-server bash # 启动mongo服务 mongod & # 在容器中查看mongo进程 ps -ef | grep mongo
启动以后会看到如下日志(最后几行),
2022-06-13t07:25:56.318+0000 i ftdc [initandlisten] initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2022-06-13t07:25:56.328+0000 i index [initandlisten] build index on: admin.system.version properties: { v: 2, key: { version: 1 }, name: "ipatible_with_version_32", ns: "admin.system.version" }
2022-06-13t07:25:56.328+0000 i index [initandlisten] building index using bulk method; build may temporarily use up to 500 megabytes of ram
2022-06-13t07:25:56.329+0000 i index [initandlisten] build index done. scanned 0 total records. 0 secs
2022-06-13t07:25:56.329+0000 i mand [initandlisten] setting featurpatibilityversion to 3.4
2022-06-13t07:25:56.329+0000 i network [thread1] waiting for connections on port 27017第四步
本地验证测试,输入mongo启动mongo命令行客户端,如下内容
root@01ff7ed6377c:/# mongo
mongodb shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
2022-06-13t07:34:00.289+0000 i network [thread1] connection accepted from 127.0.0.1:55650 #2 (1 connection now open)
2022-06-13t07:34:00.290+0000 i network [conn2] received client metadata from 127.0.0.1:55650 conn2: { application: { name: "mongodb shell" }, driver: { name: "mongodb internal client", version: "3.4.4" }, os: { type: "linux", name: "pretty_name="debian gnu/linux 8 (jessie)"", architecture: "x86_64", version: "kernel 3.10.0-327.28.3.el7.x86_64" } }接着输入测试命令,
> show dbs; admin 0.000gb local 0.000gb >
第五步
在局域网访问docker中的mongo,由于启动的时候是使用的随机端口映射,意思是宿主机产生一个随机端口去映射mongo的27017端口,通过‘docker ps -a'命令查看宿主机随机端口,如下,
docker ps -a container id image  mand created status ports names 01ff7ed6377c mongo "docker-entrypoint.sh" 15 minutes ago up 15 minutes 0.0.0.0:32773->27017/tcp mongo-server
如上,宿主机随机端口为32773,通过配置robomongo客户端连接mongo,如下,
结果正常。
如果要停止mongo可以使用如下命令,
# 登入mongo mongo # 选择使用admin库,在其他的库不行 use admin # 关闭mongo db.shutdownserver()
通过‘ps -ef | grep momgo'查看mongo进程是否存在,如果不存在说明关闭成功。









