Jesus Benavent
Jesus Benavent

Reputation: 183

Dockerized Mongodb refuses connection when accesed from other container

I am using docker-compose to run 2 images: a flask webserver and a mongodb database.

If I launch just the mongodb database container (official image) and run the flask app locally it works (connecting to localhost:27017). I can also access to the mongodb at localhost:27017 with the graphical interface MongodbCompass.

But when I launch the docker-compose with the 2 services, my connection is refused: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused

From the containerized flask app I have tried to connect both to localhost:27017 and mongo:27017 (this is the name of the service) with error. What makes me crazy is that in this case, I am still able to connect to localhost:27017 with MongodbCompass.

This is my docker-compose file:

version: '3'

services:

  mongo:
    image: mongo
    volumes:
      - /mnt/usb/data:/data/db
    ports:
      - 27017:27017

  frontend:
    build: frontend/.
    ports:
      - 80:8080
    depends_on:
      - mongo

Upvotes: 1

Views: 611

Answers (2)

Saleh Parsa
Saleh Parsa

Reputation: 1433

You defined dependency in your yml file by adding depends_on in your frontend configuration. Technically depends_on express dependency on the order according to documentation. However, what you need is a way to have communication via localhost between two containers.

In compose default behavior by your existing configuration, applications and database can communicate together via hostname. For instance, from Frontend you can reach to database by hostname monogo:27017, please check this documentation for further details. If you look after creating a connection between two containers via localhost you may need to consider using link between them

Upvotes: 0

Ali Hallaji
Ali Hallaji

Reputation: 4392

at first you need to expose port 27017 like this:

expose:
    - 27017

then you have to link it to your container:

links:
    - mongodb:mongodb-host 

left one is the name of container and right one is hostname in the container. you can access mongo in your container with mongodb-host hostname.

Upvotes: 0

Related Questions