0

I have a simple python script that's running on Azure Container Instance. I am trying to do an insert to MongoDB Atlas on cloud with Pymongo and i keep getting this error:

pymongo.errors.ServerSelectionTimeoutError: test-shard-00-01.tvyda.mongodb.net:27017: timed out,test-shard-00-00.tvyda.mongodb.net:27017: timed out,test-shard-00-02.tvyda.mongodb.net:27017: timed out, Timeout: 5.0s, Topology Description: <TopologyDescription id: 616838412c3f7b25d8dfc654, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('test-shard-00-00.tvyda.mongodb.net', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('test-shard-00-00.tvyda.mongodb.net:27017: timed out',)>, <ServerDescription ('test-shard-00-01.tvyda.mongodb.net', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('test-shard-00-01.tvyda.mongodb.net:27017: timed out',)>, <ServerDescription ('test-shard-00-02.tvyda.mongodb.net', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('test-shard-00-02.tvyda.mongodb.net:27017: timed out',)>]>

This is the code i have:

conn_str = f"mongodb+srv://{self.mongo_user}:{self.mongo_password}@{self.mongo_cluster}/{self.mongo_db}?retryWrites=true&w=majority"
db_name = self.mongo_db
collection_name = self.mongo_collection
client = pymongo.MongoClient(
conn_str, serverSelectionTimeoutMS=5000, tls=True, tlsAllowInvalidCertificates=True)
db = client[db_name]
collection = db[collection_name]

result = collection.insert_one(some_dict)

I have added the IP of the container instance to the Network Access list in MongoDB cloud.

It is working perfectly fine from Docker desktop that i run on my local machine.

I couldnt fine any solution to this. Any help is appreciated. Thanks.

1 Answers1

0

The IP address (Public), listed on Overview tab in your Container Instance, is only inbound IP address.

To get the outbound IP address which is used by the container to call MongoDB - Atlas you can connect to the container (portal or az cli) and execute:

curl ifconfig.me

If you run alpine container (like me) you have to install curl first:

apk update
apk add curl

Whitelist the output IP address in MongoBD Atlas console and you are good to go.

Note that the outbound IP address can (and probably will) change when you restart the container.

Artur Ferfecki
  • 148
  • 1
  • 2
  • 15