0
votes

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

2
Did you verify that Mongo is starting up without errors? If you can connect via the host IP address (you are exposing the port in the config), you could try using that in your node config but the Docker hostname should work. You could try adding a service that you can exec into to check if the "db" host is reachable. Also, longshot, try using a different service name like mongodb.ldg

2 Answers

2
votes

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.

1
votes

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