Docker-Compose:无法连接到 Mongo

duh*_*ime 3 networking mongodb flask docker docker-compose

我正在尝试使用 Docker 来容器化使用 Flask Web 服务器和 MongoDB 数据库的 Web 应用程序。

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

db = MongoClient(os.environ['MONGO_URI'], connect=False)['cat_database']
Run Code Online (Sandbox Code Playgroud)

在容器内,我尝试通过设置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'
Run Code Online (Sandbox Code Playgroud)

完整的 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"
Run Code Online (Sandbox Code Playgroud)

这将返回:

无法解析主机:mongo_service

有谁知道我做错了什么,或者我可以做些什么来让服务器连接到 Mongo?如果其他人可以提供任何建议,我将不胜感激!

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

cod*_*key 5

depends_on部分仅用于控制启动顺序

还需要一个链接网络部分来允许容器与每个订单对话。

更新webdocker-compose.yml 文件的部分以添加到mongo_service容器的链接:

...
  web:
    depends_on:
      - mongo_service
    links:
      - mongo_service
    environment:
      PYTHONUNBUFFERED: 'true'
...
Run Code Online (Sandbox Code Playgroud)

更新

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

CMD curl "mongo_service:27017"
Run Code Online (Sandbox Code Playgroud)