Docker Community Forums

Share and learn in the Docker community.

Docker container not able to connect to remote MongoDB

(Abhinav272727) #1

I have a flask based python code which simply connects to remote 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


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():
        client = MongoClient(<mongodbURL>)
        return client.get_database(<DBname>)

    except Exception as 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"

    def hello_world():
        return "Hello World"


if __name__ == '__main__':

(Yingxindocker) #2

Hi, have you fixed this problem yet?