1
votes

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
2
Mongo database is probably not up yet when frontend service starts. Read this stackoverflow.com/questions/31746182/… to learn how to delay frontend service start only after mongo service is up.norbjd
Thanks, but with the "depends_on" I am assuring that mongo is up when frontends starts. Anyway I have found the problem in the way I was setting up the database config so It is solved.Jesus Benavent
depends_on does not guarantee that mongo database is ready to accept connections when frontend starts. It only guarantees the startup order (mongo, then frontend) : take a look at the example in the docs (docs.docker.com/compose/compose-file/#/dependson#depends_on) : depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.norbjd

2 Answers

0
votes

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.

0
votes

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