简体   繁体   English

Docker-Compose:无法连接到Mongo

[英]Docker-Compose: Can't Connect to Mongo

I'm trying to use Docker to containerize a web application that uses a Flask web server and a MongoDB database. 我正在尝试使用Docker来容器化使用Flask Web服务器和MongoDB数据库的Web应用程序。

Within the Flask server, I attempt to connect to Mongo using an environment variable named MONGO_URI : 在Flask服务器中,我尝试使用名为MONGO_URI的环境变量连接到Mongo:

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

Within the container, I attempt to connect to Mongo by setting a MONGO_URI environment variable that references a service name. 在容器中,我尝试通过设置引用服务名称的MONGO_URI环境变量来连接到Mongo。 Full docker-compose.yml: 完整的docker-compose.yml:

Full 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'

Full Dockerfile: 完整的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"

This returns: 返回:

Could not resolve host: mongo_service 无法解析主机:mongo_service

Does anyone know what I'm doing wrong, or what I can do to get the server to connect to Mongo? 有人知道我做错了什么,或者我可以做些什么来使服务器连接到Mongo? I'd be very grateful for any advice others can offer! 我非常感谢其他人可以提供的任何建议!

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

The depends_on section is only for controlling startup order . depends_on部分仅用于控制启动顺序

A links or networks section is also required to allow the containers to talk to each order. 还需要一个链接网络部分,以允许容器与每个订单进行对话。

Update the web section of the docker-compose.yml file to add the link to the mongo_service container: 更新docker-compose.yml文件的web部分,以将链接添加到mongo_service容器:

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

Update 更新

The final RUN instruction will execute at build time. 最终的RUN指令将在构建时执行。 You need to use CMD instead for it to execute at runtime: 您需要使用CMD来使其在运行时执行:

CMD curl "mongo_service:27017"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM