Docker-Compose:无法连接到Mongo

时间:2018-03-23 15:17:54

标签: mongodb docker networking flask docker-compose

我试图使用Docker来容纳使用Flask Web服务器和MongoDB数据库的Web应用程序。

在Flask服务器中,我尝试使用名为MONGO_URI的环境变量连接到Mongo:

db = MongoClient(os.environ['MONGO_URI'], connect=False)['cat_database']

在容器中,我尝试通过设置引用服务名称的MONGO_URI环境变量来连接到Mongo。完整的docker-compose.yml:

完整的docker-compose.yml:

version: '2'

services:
  mongo_service:
    image: mongo

  web:
    # link the web container to the mongo_service container
    links:
      - mongo_service
    # explicitly declare service dependencies
    depends_on:
      - mongo_service
    # set environment variables
    environment:
      PYTHONUNBUFFERED: 'true'
    volumes:
      - docker-data/app/
    # use the image from the Dockerfile in the cwd
    build: .
    command:
      - echo "success!"
    ports:
      - '8000:8000'

完整Dockerfile:

# Specify base image
FROM andreptb/oracle-java:8-alpine

# Specify author / maintainer
MAINTAINER Douglas Duhaime <douglas.duhaime@gmail.com>

# Add the cwd to the container's app directory
ADD . "/app"

# Use /app as the container's working directory
WORKDIR "/app"

# Test that the mongo_service host is defined

RUN apk add --update --no-cache curl

RUN curl "mongo_service:27017"

返回:

  

无法解析主机:mongo_service

有谁知道我做错了什么,或者我能做些什么来让服务器连接到Mongo?我非常感谢别人可以提出的建议!

Docker版本:Docker version 17.12.0-ce, build c97c6d6
Docker-compose版本:docker-compose version 1.18.0, build 8dd22a9

1 个答案:

答案 0 :(得分:2)

depends_on部分仅适用于controlling startup order

还需要linksnetworks部分才能让容器与每个订单进行通信。

更新docker-compose.yml文件的web部分,以添加指向mongo_service容器的链接:

...
  web:
    depends_on:
      - mongo_service
    links:
      - mongo_service
    environment:
      PYTHONUNBUFFERED: 'true'
...

更新

最终的RUN指令将在构建时执行。您需要使用CMD来代替它在运行时执行:

CMD curl "mongo_service:27017"