Unable to connect python program to mongodb server from Docker Container

Hello All, I, m getting timeout error when I m running Python program from Docker Container.
Python program to connect with mongodb running at port 27017

Error : 2023-11-18 19:20:54 pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 30s, Topology Description: <TopologyDescription id: 6558c120a96a5a1d07c5b059, topology_type: Unknown, servers: [<ServerDescription (‘localhost’, 27017) server_type: Unknown, rtt: None, error=AutoReconnect(‘localhost:27017: [Errno 111] Connection refused (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)’)>]>.

(In host machine it is working fine)

Python

import pymongo

myclient = pymongo.MongoClient("mongodb://admin:password@localhost:27017/")

dblist = myclient.list_database_names()
if "Student" in dblist:
  print("The database exists.")
  mydb = myclient["Student"]
  mycol = mydb["details"]
  mydict = { "name": "John", "address": "Highway 37" ,"city":"dehradun"}
  x = mycol.insert_one(mydict)
else:
    print("hello")
    mydb = myclient["Student"]
    mycol = mydb["details"]
    mydict = { "name": "John", "address": "Highway 37" }
    x = mycol.insert_one(mydict)
myclient.close()

Dockerfile

From python:3
ENV MONGO_DB_USERNAME=admin
ENV MONGO_DB_PWD=password
RUN mkdir -p /home/project
RUN python -m pip install pymongo
COPY . /home/project
CMD ["pip3 install","pymongo"]
CMD ["python","/home/project/main_code.py"]

command used to build : docker build -t my_python_app:2.0 .

Compose.yaml

version: '3'
services:
  app:
    image:  my_python_app:2.0
    ports:
    - 3000:3000
  mongodb:
    image: mongo
    ports:
    - 27017:27017
    environment:
    - MONGO_INITDB_ROOT_USERNAME=admin
    - MONGO_INITDB_ROOT_PASSWORD=password
    volumes:
    - mongo_data:/data/db
  mongo-express:
    image: mongo-express
    ports:
    - 8080:8081
    environment:
    - ME_CONFIG_MONGODB_ADMINUSERNAME=admin
    - ME_CONFIG_MONGODB_ADMINPASSWORD=password
    - ME_CONFIG_MONGODB_SERVER=mongodb
volumes:
  mongo_data:
    driver: local

command to run : docker-compose -f compose.yaml up -d

You are connecting to localhost:27017 within your app container - that’s not you host‘s localhost, but the one inside the container.

And as containers are about isolation, that way you can’t connect to other services.

Use the service name instead mongodb:27017, as Docker DNS makes the containers automatically available by their service name.

1 Like