1

I have a simple python script which fetches certain values from the mongodb database. The script works fine on my local machine(host machine) but when i containarized my aplication it doesnt work. Here is my docker file.

FROM python:3.8-slim-buster
WORKDIR /app
COPY mysript.py .
RUN pip3 install pymongo
CMD [ "python3", "myscript.py"]

My python code

from pymongo import MongoClient
client = MongoClient("mongodb://userName:password@localhost/sampledb")
db = client.sampledb
tutorial1 = {"title": "Working With JSON Data in Python","author": "Lucas"}
tutorial = db.sampledb
result = tutorial.insert_one(tutorial1)

for doc in tutorial.find():
  print(doc)

This code works fine on my local machine but not on the container. However i get an error like

pymongo.errors.ServerSelectionTimeoutError: 192.168.1.12:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 61b38be61c25e1ffbb4b9b0f, topology_type: Unknown, servers: [<ServerDescription ('192.168.1.12', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('192.168.1.12:27017: [Errno 111] Connection refused')>]>

I have tried allowing by docker container IP by ufw firewall since its a connection refused issue but it doesnt work. I have also tried by changing the localhost field from the python code to docker container ip but that also doesnt helped me.

Does someone has any insights on this? Any help would be appreciated.

1
  • How is your setup, 2 docker containers in the same VM ? different VMS? mongo somewhere else, like mongo atlas?
    – paltaa
    Dec 10, 2021 at 17:51

1 Answer 1

1

Are you using dockerized Mongodb like this?

https://hub.docker.com/_/mongo

you must replace localhost in this line of code with mongodb container name:

client = MongoClient("mongodb://userName:password@<mongodb cointaner name or ip>/sampledb")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.