如何使用pymongo连接到Docker容器内的Mongo?

时间:2019-05-14 10:32:17

标签: python mongodb docker

我从Docker网站提取了官方的mongo映像,并启动了一个名为dataiomongo的mongo容器。

我现在想使用pymongo连接到容器内的mongodb。

这是我写的python脚本:

from pprint import pprint
from pymongo import MongoClient

client = MongoClient('localhost', port=27017)

db = client.admin

server = db.command("serverStatus")
pprint(server)

出现的错误是:

Traceback (most recent call last):
  File "D:/dataio/test_mongo.py", line 8, in <module>
    server = db.command("serverStatus")
  File "D:\dataio\venv\lib\site-packages\pymongo\database.py", line 655, in command
    read_preference) as (sock_info, slave_ok):
  File "C:\Python27\Lib\contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "D:\dataio\venv\lib\site-packages\pymongo\mongo_client.py", line 1135, in _socket_for_reads
    server = topology.select_server(read_preference)
  File "D:\dataio\venv\lib\site-packages\pymongo\topology.py", line 226, in select_server
    address))
  File "D:\dataio\venv\lib\site-packages\pymongo\topology.py", line 184, in select_servers
    selector, server_timeout, address)
  File "D:\dataio\venv\lib\site-packages\pymongo\topology.py", line 200, in _select_servers_loop
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 10061] No connection could be made because the target machine actively refused it

如何连接到Docker容器内的mongodb?

3 个答案:

答案 0 :(得分:1)

运行mongo

首先,您需要运行mongo

$ docker run --rm --name my-mongo -it -p 27017:27017 mongo:latest

作为守护程序

$ docker run --name my-mongo -d mongo:latest

使用另一个容器连接到先前的容器。

$ docker run -it --link my-mongo:mongo --rm mongo:latest sh -c 'exec mongo "$MONGO_PORT_27017_TCP_ADDR:$MONGO_PORT_27017_TCP_PORT/test"'

将数据插入数据库

Insert the data into the db

使用python连接数据库

client = MongoClient()
client.server_info()
db = client.yourdbname

答案 1 :(得分:0)

确保通过-p 27017:27017标志将27017容器端口绑定到主机端口。

答案 2 :(得分:0)

我认为您错过了-p 27017:27017标志。 docker run -p 27017:27017 --name mymongo -d mongo