[英]How to access MongoDB from PyMongo when using separate docker-compose yaml's?
I have two separate Docker containers, and separate docker-compose YAML's , too.我有两个单独的 Docker 容器和单独的 docker-compose YAML 容器。 One ('mongodb') for running the MongoDB, the other ('logger') for data scraping in Python.
一个('mongodb')用于运行 MongoDB,另一个('logger')用于在 Python 中抓取数据。 The latter should write some results into MongoDB.
后者应该将一些结果写入 MongoDB。
I used separate yaml's to be able to stop easily one container while not stopping the other one.我使用了单独的 yaml,以便能够轻松停止一个容器而不停止另一个容器。
To resolve this task I used docker-compose' bridge network capability.为了解决这个任务,我使用了 docker-compose 的桥接网络功能。 So I used the following two yaml's:
所以我使用了以下两个yaml:
networks:
wnet:
driver: bridge
services:
mongodb:
image: mongo:4.0.9
container_name: mongodb
ports:
- "27018:27017"
volumes:
- mongodb-data:/data/db
logging: *default-logging
restart: unless-stopped
networks:
- wnet
volumes:
mongodb-data:
name: mongodb-data
and和
networks:
wnet:
driver: bridge
services:
logger:
build:
context: .
image:logger:$VERSION
container_name:logger
environment:
- TARGET=$TARGET
volumes:
- ./data:/data
restart: unless-stopped
networks:
- wnet
The Python container should now persist the scraped data within the MongoDB database. Python 容器现在应该将抓取的数据保存在 MongoDB 数据库中。 So I tried the following variants:
所以我尝试了以下变体:
from pymongo import MongoClient
client = MongoClient(port=27018, host='mongodb') # V1
client = MongoClient(port=27018) # V2
db = client['dbname']
Then, executing one of the following commands throws the error:然后,执行以下命令之一会引发错误:
db.list_collection_names()
db.get_collection('aaa').insert_one({ 'a':1 })
The response I get is我得到的回应是
pymongo.errors.ServerSelectionTimeoutError: mongodb:27018: [Errno -2] Name or service not known
Any idea?任何想法?
Thanks.谢谢。
What finally worked is to refer to the network (defined in container mongodb
) by its composed name ( mongodb + wnet
= mongodb_wnet
), and to add the external
option.最终起作用的是通过其组合名称(
mongodb + wnet
= mongodb_wnet
)引用网络(在容器mongodb
中定义),并添加external
选项。 This makes the YAML file of the logger
container look like:这使得
logger
容器的 YAML 文件看起来像:
services:
logger:
build:
context: .
image: logger:$VERSION
container_name: logger
environment:
- TARGET=$TARGET
volumes:
- ./data:/data
restart: unless-stopped
networks:
- mongodb_wnet
networks:
mongodb_wnet:
external: true
However, as mentioned by @BellyBuster, it might be a good idea to use one single docker-compose file .但是,正如@BellyBuster 所提到的,使用一个 docker-compose 文件可能是个好主意。 I was not aware that it is quite easy to start, stop, and build single containers belonging to the same YAML.
我不知道启动、停止和构建属于同一个 YAML 的单个容器非常容易。
SO has also enough posts on that, eg How to restart a single container with docker-compose and/or docker compose build single container . SO 也有足够的帖子,例如How to restart a single container with docker-compose和/或docker compose build single container 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.