简体   繁体   中英

Can't connect to MongoDB on Docker Container

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?

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

ie: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM