0

I'm working on a node js api and I'm using mongodb. Right now I'm facing one problem when I try to connect to the database, I'm getting this error MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 the api is running on a docker container and the database is local, I'm not running mongo on docker container.

this is my connection string mongodb://localhost:27017/database

and this is my docker file

FROM node
RUN apk add dumb-init
ENV PORT=4000
WORKDIR /usr/src/app
COPY package-lock.json /usr/src/app/
RUN npm ci
COPY . /usr/src/app/
USER node
EXPOSE 4000
CMD ["dumb-init", "node", "/usr/src/app/app.js"]

UPDATE

Forgot to add the docker-compose.yml

Here it is:

version: '2.1'

services:
  api:
    build:
      context: .
      dockerfile: ./Dockerfile.api
    ports:
      - "4000:4000"
      - "27017:27017"
    extra_hosts:
      "host.docker.internal": host-gateway
    volumes:
      - ./var/:/var
    restart: on-failure

Can someone tell what is wrong or what else is missing?

GeekDev
  • 385
  • 3
  • 16
  • 1
    How are you running the container? If you're not publishing a port (`-p :`) the service will not be available on `localhost` on your host. – larsks Aug 31 '22 at 23:50
  • Does this answer your question? [From inside of a Docker container, how do I connect to the localhost of the machine?](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach) – Phil Sep 01 '22 at 00:13
  • @Iarsks I'm running the image using `docker-compose up -d`! @Phil I'm going to take a look on that question... – GeekDev Sep 01 '22 at 00:43

1 Answers1

0

Make the hostname for your connection string to mongodb host.docker.internal instead of localhost

i.e: mongodb://host.docker.internal:27017/database

https://docs.docker.com/desktop/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host

Tjad Clark
  • 552
  • 3
  • 17