S Andrew
S Andrew

Reputation: 7218

Docker container not able to connect to remote MongoDB

I have a flask based python code which simply connects to mongodb.It has two routes Get Post. Get simply prints hello world and using Post we can post any json data which is later saved in MongoDB This python code is working fine. MongoDB is hosted on cloud.

I have now created a Dockerfile:

FROM tiangolo/uwsgi-nginx-flask:python3.6-alpine3.7

RUN pip3 install pymongo

ENV LISTEN_PORT=8000
EXPOSE 8000

COPY /app /app

Using command to run

docker run --rm -it -p 8000:8000 myflaskimage

After starting the container for this docker image, I am getting response of GET but no response from POST. I am using Postman software to post json data. I get below error:

pymongo.errors.ServerSelectionTimeoutError: No servers found yet

I am bit confused as to why the python code is working fine but when I put the same in docker and start container, it throws error. Do we have to include anything in Dockerfile to enable connections to MongoDB.

Please help. Thanks

Python Code:

from flask import Flask, request
from pymongo import MongoClient

app = Flask(__name__)

def connect_db():
    try:
        client = MongoClient(<mongodbURL>)
        return client.get_database(<DBname>)

    except Exception as e:
        print(e)


def main():
    db = connect_db()
    collection = db.get_collection('<collectionName>')

    @app.route('/data', methods=['POST'])
    def data():
        j_data = request.get_json()
        x = collection.insert_one(j_data).inserted_id
        return "Data added successfully"

    @app.route('/')
    def hello_world():
        return "Hello World"

main()

if __name__ == '__main__':
   app.run()

Upvotes: 9

Views: 2182

Answers (1)

cgrim
cgrim

Reputation: 5031

You probably don't have internet connection from the container. I had a similar issue when connecting from containerized java application to public web service.

At first I would try to restart docker:

systemctl restart docker

If it does not help then look into resolv.conf in you container:

docker run --rm myflaskimage cat /etc/resolv.conf

If it shows nameserver 127.x.x.x then you can try:

1) on the host system comment dns=dnsmasq line in /etc/NetworkManager/NetworkManager.conf file with a # and restart NetworkManager using systemctl restart network-manager

2) or explicitly set DNS for docker adding this into the /etc/docker/daemon.json file and restarting the docker:

{
    "dns": ["my.dns.server"]
}

Upvotes: 1

Related Questions