docker-compose to run django with mongodb

前端 未结 4 703
执念已碎
执念已碎 2021-02-13 20:25

I am facing problem using docker-compose to link a django container with postgres and mongo containers? I am trying to use \"docker-compose up\" which starts up the mongo and po

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-13 20:53

    I ran into a similar problem but with another service (not 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
    • 27017 being the port of the exposed service.
    • More about docker-compose environment variables
    • 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

    Now docker-compose containers are reachable by other services using a hostname similar to their alias. 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:

    import mongoengine
    
    mongoengine.connect(host="db2")
    

提交回复
热议问题