sub_o
sub_o

Reputation: 2802

Can't connect to mongo from flask in docker containers

I have a python script that runs the following

import mongoengine
client = mongoengine.connect('ppo-image-server-db', host="db", port=27017)
db = client.test_db

test_data = {
    'name' : 'test'
}

db.test_data.insert_one( test_data )
print("DONE")

And I have a docker-compose.yml that looks like the following

version: '2'
networks:
    micronet:

services:
    user-info-service:
        restart       : always
        build         : .
        container_name: test-user-info-service
        working_dir   : /usr/local/app/test
        entrypoint    : ""
        command       : ["manage", "run-user-info-service", "--host=0.0.0.0", "--port=5000"]
        volumes       :
            - ./:/usr/local/app/test/
        ports         :
            - "5000:5000"
        networks      :
            - micronet
        links:
            - db

    db:
        image           : mongo:3.0.2
        container_name  : test-mongodb
        volumes         :
            - ./data/db:/data/db
        ports           :
            - "27017:27017"

However every time when I run docker-compose build and docker-compose up, the python script is not able to find the host (in this case 'db'). Do I need any special linking or any environment variables to pass in the mongo server's IP address?

I could still access the dockerized mongo-db using robomongo

Please note that I'm not creating any docker-machine for this test case yet.

Could you help me to point out what's missing in my configuration?

Upvotes: 5

Views: 3502

Answers (1)

Israel Zinc
Israel Zinc

Reputation: 2769

Yes,

What you need is to tell docker that one application depends on the other. Here is how I built my docker-compose:

version: '2'
services:
  mongo-server:
    image: mongo
    volumes:
    - .data/mdata:/data/db # mongodb persistence

  myStuff:
    build: ./myStuff
    depends_on:
    - mongo-server

Also, in the connection url, you need to use the url "mongo-server". Docker will take care of connecting your code to the mongo container.

Example:

private val mongoClient: MongoClient = MongoClient("mongodb://mongo-server:27017")

That should solve your problem

Upvotes: 6

Related Questions