【发布时间】:2019-04-06 04:35:31
【问题描述】:
我正在使用 docker-compose 运行 2 个图像:一个烧瓶网络服务器和一个 mongodb 数据库。
如果我只启动 mongodb 数据库容器(官方图片)并在本地运行烧瓶应用程序,它可以工作(连接到 localhost:27017)。我还可以通过图形界面 MongodbCompass 访问 localhost:27017 的 mongodb。
但是当我使用 2 个服务启动 docker-compose 时,我的连接被拒绝:pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused
从容器化烧瓶应用程序中,我尝试同时连接到 localhost:27017 和 mongo:27017(这是服务的名称),但出现错误。让我抓狂的是,在这种情况下,我仍然能够使用 MongodbCompass 连接到 localhost:27017。
这是我的 docker-compose 文件:
version: '3'
services:
mongo:
image: mongo
volumes:
- /mnt/usb/data:/data/db
ports:
- 27017:27017
frontend:
build: frontend/.
ports:
- 80:8080
depends_on:
- mongo
【问题讨论】:
-
frontend服务启动时,Mongo 数据库可能尚未启动。阅读此stackoverflow.com/questions/31746182/…,了解如何在mongo服务启动后仅延迟frontend服务启动。 -
谢谢,但是有了“depends_on”,我保证在前端启动时 mongo 已经启动。无论如何,我在设置数据库配置的方式中发现了问题,所以它已经解决了。
-
depends_on不保证mongo数据库在frontend启动时已准备好接受连接。它只保证启动顺序(mongo, thenfrontend):看一下文档中的示例(docs.docker.com/compose/compose-file/#/dependson#depends_on):depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.