【发布时间】:2018-09-02 07:53:45
【问题描述】:
我正在尝试使用 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
【问题讨论】:
-
当您在这两个服务上执行
docker ps然后docker inspect <HASH>时,某处应该有一个Network部分。这里有什么问题吗?当您执行docker exec -it <CONTAINERNAME> bash时,您可以使用例如中列出的任何名称 ping 另一个容器吗?上述Network部分中的“别名”? (另外我觉得你从.构建这两个服务有点奇怪,但应该没问题。)
标签: mongodb docker networking flask docker-compose