Can't connect to mongo docker image with mongoose
Asked Answered
P

4

7

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.

Paraldehyde answered 4/3, 2018 at 11:47 Comment(0)
P
14

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)
  })
Paraldehyde answered 4/3, 2018 at 12:11 Comment(0)
T
1

you have to look at the port part of your container in the inspector, and my opinion is that you have to put : mongodb://0.0.0.0:27017/

enjoy !

Thorne answered 3/8, 2022 at 23:16 Comment(0)
S
0

I think without mounting volumes in db service , container won't be able to continue its process. it will start for just a second and then it will be terminated. so that's why you are getting an error.

Speck answered 3/5, 2021 at 6:28 Comment(0)
P
0

Here is the fix: In docker-compose.yml:

services:
  mongodb:
    image: mongo:7
    restart: unless-stopped
    container_name: mongo-server
    ports:
      - 27017:27017
    volumes:
      - ./data:/data/db

Remember at the container_name, name it whatever you want, and then, in the mongoose connection:

mongoose.connect("mongodb://mongo-server:27017/your_table_name")

Change "mongo-server" that match container_name. Hope it helps.

Procumbent answered 17/1 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.