'pymongo.errors.ServerSelectionTimeoutError: db:27017: timed out, Timeout: 30s,

I am trying to run a Flask and MongoDb application and getting following error. Here are the logs that I could fetch using sudo docker logs <container-name>

    self._select_servers_loop(
  File "/usr/local/lib/python3.10/site-packages/pymongo/topology.py", line 227, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: db:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 626fc61ba785d70a66a1ea12, topology_type: Unknown, servers: [<ServerDescription ('db', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('db:27017: timed out')>]>

I get the above error in log when I try to access localhost. When I try to access localhost in browser I see connection was reset error and then I see the above logs being generated.

Here is my app.py file

from flask_restful import Api, Resource
import os
from pymongo import MongoClient

app = Flask(__name__)
api = Api(app)


client = MongoClient("mongodb://db:27017", port=27017, directConnection=True)
db = client.aNewDB
UserNum = db["UserNum"]

UserNum.insert_one({
    'num_of_users':0
})

class Visit(Resource):
    def get(self):
        prev_num = UserNum.find({})[0]['num_of_users']
        new_num = prev_num + 1
        UserNum.update_one({}, {"$set":{"num_of_users":new_num}})
        return str("Hello user" + str(new_num))

api.add_resource(Visit,"/")

if __name__=="__main__":
    port = int(os.environ.get('PORT',5000))
    app.run(host='0.0.0.0', port=port)

Here is my docker-compose.yml:

services:
  web:
    build: ./web
    ports:
      - "5000:5000"
    depends_on:
      - db
  db:
    build: ./db
    ports:
      - '27017-27019:27017-27019'

Any help much be appreciated.



Solution 1:[1]

I was facing similar issue. In my case I had connected mongoDB replica to my Local via tunneling, I could access it using the Compass application. But couldn't access it via Pymongo. I was using Localhost:Port, user_id & password. Later on just copied the connection string from compass and tried, It Worked!

client= MongoClient('mongodb://USER:PASSWORD@localhost:PORT/?authSource=admin&readPreference=secondary&directConnection=true&ssl=false')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gaurav pandey