0

Hy, I am pretty new to docker and I am having some issue understanding how containers interact with each other in the docker world created using a docker compose

I have a docker-compose.yaml file that contain 2 services:

  1. A MongoDB service which is suppose to create a MongoDB database
  2. A Node.js app service that is trying to connect to that MongoDB database

When i try to run the docker-compose up command I get an error letting me know there was a issue connecting to my MongoDB instance.

info: Listening on port 3000...
error: uncaughtException: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
  name: 'MongoNetworkError'

This is my docker-compose.yaml file

version: '3.7'
services:
  mongodb:
    container_name: mongodb_container
    image: mongo:latest
    ports:
      - 27017:27017
    volumes:
      - mongodb_data_container:/data/db

  my_app: 
    container_name: my_app_container
    image: my_app:1.0
    ports: 
      - 3000:3000

Can anyone help me out with this issue?

0

1 Answer 1

1

Your are not providing network informations, so I suppose you are using default network. In your app container, "localhost" is your container localhost (not the localhost of your host machine).

Instead of using "localhost", use the container name "mongodb_container" in your app to connect to your db on port "27017" (to be clear : 27017 is the port exposed by your mongo container, not 27017 opened on the host localhost).

Check : https://docs.docker.com/compose/networking/

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the information I was able to connect to the MongoDb data base. But now when i try to send a curl command from within the docker containers - curl mongodb_container:3000/api/user - to the node app i get a connection refused - curl: (7) Failed to connect to mongodb_container port 3000: Connection refused
I don't understand, you are mixing you api port with mongodb container name. If you want to reach your API, you can try to curl on : my_app_container:3000/api/user
Thank you very much. This was indeed my mistake. It all works perfect now.
Nice ! You can accept my answer to close your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.