Docker Community Forums

Share and learn in the Docker community.

Mongo and Flask connection error


I am trying to connect to mongo container from a Python-flask container. I am using below configs,


    build: ./application
    container_name: app
    restart: unless-stopped
      - dbservice
      - 5000:5000
    build: ./nginx
    container_name: nginx
    restart: unless-stopped
      - "8080:443"
    image: mongo
    container_name: dbservice
    restart: unless-stopped
      - 27017:27017
      - "/home/admin/Desktop/app/db:/data/db"

And for connecting from mongo client,


When I run the whole thing together, the connection is really inconsistent. i.e: sometimes the flask app connects to the mongo container and sometimes it doesn’t and gives me below errors.

pymongo.errors.ServerSelectionTimeoutError: No servers found yet, Timeout: 30s, Topology Description: <TopologyDescription id: 5fbe9fa507475fa5e28d354c, topology_type: Single, servers: [<ServerDescription (‘dbservice’, 27017) server_type: Unknown, rtt: None>]>


Connection Refused (in the same error format as above)

when the error occurs, the flask app cannot get any db data and it hangs. When the same query made again right after the error ,(i.e: html page of flask app is refreshed) db data is retrieved normally and works normally. (I do not use JS (/frontend) to make any db call either). This behavior changes randomly.

If I use the mongo db and flask without containers, they work as expected without errors. What could be the issue here?

Install the required Flask and PyMongo modules using the following pip3 commands:

pip3 install pymongo
pip3 install Flask-PyMongo
How to install PyMongo and Flask-PyMongo packages for a specific version of Python 3
Optionally specify the Python 3 version to install the packages and then use the below python3.6 or python3.7 commands:

python3 --version && pip3 --version
Here is how to install the Flask modules using pip3 for Python 3.6:


Example installation using Python 3.6

python3.6 -m pip install pymongo
python3.6 -m pip install Flask-PyMongo
How to handle the Flask app returning a ‘ModuleNotFoundError’ error
WARNING: Do not install the isolated bson library for PyMongo using pip or there may be conflicts that will produce ModuleNotFound errors. If these conflicts or errors occur, use pip3 to uninstall the bson, pymongo and Flask-PyMongo modules and then reinstall only the last two.

How to install the Flask command-line tools on Linux using the APT repository
Execute the following command to install the command-line tools for Flask on Linux from the apt repository:

sudo apt install python3-flask
Type flask or flask shell in a terminal window. In the case of multiple installations, execute the flask --version command to determine what version of Python 3 is installed.

This is not a relevant answer. I think you’ve copied this from somewhere else and just pasted here.