tR4x
tR4x

Reputation: 75

mongoose connection failure using docker-compose

I have a Node express server consuming a Mongo database.

I'm trying to create a container for each of them using docker-compose.

Here's my docker-compose.yml file:

version: "2"
 services:
  server:
    container_name: server
    restart: always
    build: .
    ports:
      - "3000:3000"
    depends_on:
      - db
  db:
    container_name: db
    image: mongo
    volumes:
      - /var/lib/mongodb:/data/db
    ports:
      - "27017:27017"

And my Dockerfile:

FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app
RUN npm install
COPY . /usr/src/app
RUN npm run build-run
EXPOSE 3000

I saw on many tutorials that, when using Docker to create a Mongo container, the connection string should be updated in mongoose.connect to use Docker containers naming resolution.

So I changed my connection string according to my docker-compose file:

private readonly CONNECTION_STRING: String = 'mongodb://db/search-people-db'

public connect(): void {
    mongoose.connect(this.CONNECTION_STRING)

    this._db.on('error', (err) => {
        console.log(`mongoose server failed to start: ${err}`)
    })

    this._db.once('open', () => {
        console.log(`mongoose server running using ${this.CONNECTION_STRING}`)
    })
}'

However, when running sudo docker-compose up, I keep getting the following error:

Mongoose server failed to start: MongoNetworkError: failed to connect to server [db:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND db db:27017]

What am I doing wrong ? Thanks in advance

Upvotes: 0

Views: 2061

Answers (2)

Siamak S
Siamak S

Reputation: 31

MongoDB's container boots up but MongoDB itself needs more time start. so your application will not connect to it until it's fully started.

as Docker's documents suggested, you should set a wait time for your application and then run your code. I suggest to make mongoose try to reconnect if couldn't connect at the first time or let the application crash if it couldn't connect. Docker will run your container again.

Upvotes: 2

kaxi1993
kaxi1993

Reputation: 4700

Replace depends_on with links in your docker-compose.yml and try to run command again.

Upvotes: 1

Related Questions