2
votes

When trying to connect my express app to a mongo container with docker-compose the connection is refused. I am able to connect to the db container with robo3T using localhost:27017 and the l/p setup with the dbSetup.js, but when express tries to connect I get an error:

{ MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 172.19.0.2:27017]

// mongoose
const options = {
  autoIndex: true, // Don't build indexes
  reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
  reconnectInterval: 500, // Reconnect every 500ms
  poolSize: 10, // Maintain up to 10 socket connections
  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0
};
console.log(options);
mongoose.connect('mongodb://blogUser:blogUserPassword@mongo/blog', options).then(
  () => { console.log("connected !!!"); },
  err => { console.log(err);  }
);

The Docker-Compose

version: '3'

services:
  mongo:
    container_name: mongo
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_INITDB_ROOT_USERNAME}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_INITDB_ROOT_PASSWORD}
    volumes:
      - ./dbSetup.js:/docker-entrypoint-initdb.d/dbSetup.js
      - /data/db:/data/db
    ports:
      - "27017:27017"

  blog_api:
    container_name: blog_api
    build: ../blog.com/api
    restart: always
    expose: 
      - 3000
    ports:
      - "3000:3000"
    links:
      - mongo
    depends_on:
      - mongo
1
What happens if you start mongo first? E.g., docker-compose up mongo then after it successfully starts, docker-compose up?ldg
That worked the magic. Thank you.BHalvy82

1 Answers

5
votes

If you can run the app after the mongo service is running, it means mongo is taking longer to start up and be connection-ready than when your app tries to connect. If your app doesn't ever connect it may not be restarting properly - you probably want it to exit if it doesn't connect and then make sure you have your Docker restart policy set accordingly ("always", "on-failure", etc.) see docs. Assuming mongo eventually starts up, your app will eventually connect.

You can also look into using healthchecks in which case you could see if the database is actually connecting rather than starting up. The depends_on flag will only check to see that the container is up, it doesn't check to see if the apps in the container are running much less if they are working properly.