简体   繁体   English

docker-compose 使用 mongodb 运行 django

[英]docker-compose to run django with mongodb

I am facing problem using docker-compose to link a django container with postgres and mongo containers?我在使用 docker-compose 将 django 容器与 postgres 和 mongo 容器链接时遇到问题? I am trying to use "docker-compose up" which starts up the mongo and postgres containers (as I need to link both) but still the django app is not able to connect to mongodb on default settings.我正在尝试使用“docker-compose up”来启动 mongo 和 postgres 容器(因为我需要链接两者),但 django 应用程序仍然无法在默认设置下连接到 mongodb。 My django-compose.yml file contents are copied below:我的 django-compose.yml 文件内容复制如下:

    db1:
      image: postgres
    db2:
      image: mongo
      ports:
        - "27017:27017"
    web:
      build: .
      command: python manage.py runserver 0.0.0.0:8000
      volumes:
        - .:/code
      ports:
        - "8000:8000"
      links:
        - db1
        - db2

It does connect with postgres with default settings.它确实与具有默认设置的 postgres 连接。 I can also telnet to the mongodb port locally.我也可以在本地 telnet 到 mongodb 端口。 Still, I get this error on starting the web container:尽管如此,我还是在启动 Web 容器时遇到此错误:

File "/usr/local/lib/python2.7/site-packages/mongoengine/connection.py", line 124, in get_connection web_1 |文件“/usr/local/lib/python2.7/site-packages/mongoengine/connection.py”,第124行,get_connection web_1 | raise ConnectionError("Cannot connect to database %s :\\n%s" % (alias, e)) web_1 | raise ConnectionError("无法连接到数据库 %s :\\n%s" % (alias, e)) web_1 | mongoengine.connection.ConnectionError: Cannot connect to database default : web_1 | mongoengine.connection.ConnectionError:无法连接到数据库默认值:web_1 | [Errno 111] Connection refused [Errno 111] 连接被拒绝

PS: I had successfully started a django-postgres connected app on my localhost, but it failed connecting to db, on an AWS instance. PS:我已经在我的本地主机上成功启动了一个 django-postgres 连接的应用程序,但它无法连接到 AWS 实例上的 db。 That is another problem I still need to get to root of.这是我仍然需要解决的另一个问题。

I ran into a similar problem but with another service (not MongoDB). 我遇到了类似的问题但是使用了另一个服务(不是MongoDB)。 I'm not sure of what I'm doing wrong but this is how I could solve it : 我不确定我做错了什么,但这就是我能解决的问题:

import os
import mongoengine

MONGODB_HOST = os.environ.get('DB2_PORT_27017_TCP_ADDR', '127.0.0.1')
mongoengine.connect(host=MONGODB_HOST)
  • With DB2 being the name of your service in docker-compose.yml DB2docker-compose.yml中服务的名称
  • 27017 being the port of the exposed service. 27017是暴露服务的端口。
  • More about docker-compose environment variables 有关docker-compose环境变量的更多信息
  • I'd put that in my settings file. 我把它放在我的设置文件中。 But you are free to put it wherever you think it's appropriate depending on your project architecture 但是根据您的项目架构,您可以自由地将它放在您认为合适的任何位置

UPDATE UPDATE

Now docker-compose containers are reachable by other services using a hostname similar to their alias. 现在,使用与其别名类似的主机名,其他服务可以访问docker-compose容器。 link documentation : 链接文档

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified. 链接服务的容器可以在与别名相同的主机名上访问,如果未指定别名,则可以访问服务名称。

And that way you can connect to MongoDB like this: 这样你可以像这样连接到MongoDB:

import mongoengine

mongoengine.connect(host="db2")

You should specify host name like in the docker compose file, instead of IP address. 您应该在docker compose文件中指定主机名,而不是IP地址。

I've faced similar problems in connecting from a Tornado Web app to Mongo DB. 从Tornado Web应用程序连接到Mongo DB,我遇到了类似的问题。 Here is my docker-compose.yml: 这是我的docker-compose.yml:

web:
  build: .
  ports:
   - "8888:8888"
  volumes:
   - .:/code
  links:
   - db
db:
  image: mongo:3.0

Here is my connection string: 这是我的连接字符串:

motorengine.connect("db", host='db', port=27017, io_loop=io_loop)

My error was to specify IP address instead of host name (db) like in the docker compose file. 我的错误是在docker compose文件中指定IP地址而不是主机名(db)。

The problem you face is that the application container and the DB container start independently from each other and most importantly, the app container won't wait until the DB container is started. 您面临的问题是应用程序容器和数据库容器彼此独立地启动,最重要的是,应用程序容器不会等到数据库容器启动。 There is as of docker compose 1.1.0 no feature which would allow to consider such dependencies. 至于docker compose 1.1.0没有允许考虑这种依赖性的特性。

This is a well known problem and has been discussed already. 这是一个众所周知的问题,已经讨论过了。 Consensus seems to be that this should not be solved on a docker compose level but in docker itself. 共识似乎是这不应该在docker compose级别上解决,而是在docker本身。 There is a proposal already for the groundwork in docker. 已有一个建议用于码头工人的基础工作。

In my case, I just built this kind of intelligence in the application itself. 就我而言,我只是在应用程序本身中构建了这种智能。 I check for port connectivity until successful and then start the rest of the application. 我检查端口连接,直到成功,然后启动应用程序的其余部分。

I was able to containerize Django and MongoDB, connect both containers. 我能够容纳Django和MongoDB,连接两个容器。 I used Dockerfiles to build both containers and docker run to start the containers and have them connected. 我使用Dockerfiles构建容器和docker run来启动容器并将它们连接起来。 Just follow the steps in this repo . 只需按照此回购中的步骤操作即可。 It was necessary for me to use Dockerfiles to have more power over the installed versions of the needed libraries because the latest versions of Django and mongoengine are not compatible. 由于最新版本的Django和mongoengine不兼容,因此我必须使用Dockerfiles对所需库的已安装版本拥有更多功能。 The stable working versions are 稳定的工作版本是

Django==1.10.0
pymongo==2.7.1
six==1.10.0
mongoengine==0.9.0

I managed to make this connection with the following configuration:我设法通过以下配置建立了这种连接:

docker-compose.yml docker-compose.yml

version: "3.9"
services:
mongodb:
  environment:
    MONGO_INITDB_DATABASE: mydatabase
    MONGO_INITDB_ROOT_USERNAME: root
    MONGO_INITDB_ROOT_PASSWORD: password
  hostname: mongodb
  image: mongo
  ports:
    - "27017:27017"
  volumes: 
    - ./data-mongodb:/data/db
  
api:
  build: .
  command: "python manage.py runserver 0.0.0.0:8000"
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  depends_on:
    - mongodb

Dockerfile文件

# syntax=docker/dockerfile:1
FROM python:3
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
COPY . /code/

requirements.txt要求.txt

asgiref==3.4.1
Django==3.2.7
django-annoying==0.10.6
djangorestframework==3.12.4
djongo==1.3.6
psycopg2==2.9.1
psycopg2-binary==2.9.1
pymongo==3.12.1
pytz==2021.3
six==1.16.0
sqlparse==0.2.4

settings.py设置.py

DATABASES = {
    'default': {
      'ENGINE': 'djongo',
      'NAME': 'mydatabase',
      'CLIENT': {
          'host': 'mongodb://mongodb:27017',
          'username': 'root',
          'password': 'password',
          'authSource': 'admin',
          'authMechanism': 'SCRAM-SHA-1',
      }
  }
}

In this, the model used is from Djongo instead of from django.db import models在此,使用的模型来自 Djongo 而不是from django.db import models

models.py模型.py

from djongo import models

After the build , you need to enter the api container and run the ./manage.py migrate构建完成后,需要进入api容器并运行./manage.py migrate

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

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