5

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?

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, weirdly enough the flask service still can't find mongo server. Running a quick requests: import requests requests.get( hostname=mongo-server, port=27017) gives me timeout, unless i change the hostname with the docker gateway, which I can't seem to resolve automatically
My bad, "--host=0.0.0.0" is the culprit, letting it run on default (localhost), allows me to ping the mongoserver now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.