Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't connect to mongo docker image with mongoose

I'm trying to run a simple docker setup with node and mongo:

Dockerfile:

 FROM node:8.9.4-alpine
 RUN mkdir /app
 WORKDIR /app
 COPY package.json /app/
 COPY package-lock.json /app/
 RUN npm install
 ADD . /app/

docker-compose.yml:

version: '3'

services:
  db:
    image: 'mongo'
    ports:
      - "27017:27017"
  api:
    build: .
    restart: always
    command: sh -c "npm install && npm run start"
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    environment:
      PORT: 3000
    depends_on:
      - db

Now in my app.js I'm connecting to mongo like that:

mongoose.connect('mongodb://localhost:27017')
  .catch(err => {
    console.log(err)
  })

However I'm getting a failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

The mongo container seems to boot up and run fine giving me waiting for connections on port 27017.

What's wrong with my setup? I also tried swapping out localhost for mongo when connecting, but it had no effect either.

like image 342
Philip Feldmann Avatar asked Dec 18 '22 00:12

Philip Feldmann


1 Answers

I didn't realise I named my database container db instead of mongo, so all I had to do was to switch that name out in my app.js:

mongoose.connect('mongodb://db:27017')
  .catch(err => {
    console.log(err)
  })
like image 85
Philip Feldmann Avatar answered Dec 20 '22 13:12

Philip Feldmann