简体   繁体   English

无法使用 mongoose 连接到 mongo docker 映像

[英]Can't connect to mongo docker image with mongoose

I'm trying to run a simple docker setup with node and mongo:我正在尝试使用 node 和 mongo 运行一个简单的 docker 设置:

Dockerfile: 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: 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:现在在我的app.js中,我像这样连接到 mongo:

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]但是我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 . mongo 容器似乎启动并运行良好,让我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.我还尝试在连接时将localhost换成mongo ,但它也没有效果。

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:我没有意识到我将我的数据库容器命名为 db 而不是 mongo,所以我所要做的就是在我的 app.js 中切换该名称:

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

I think without mounting volumes in db service , container won't be able to continue its process.我认为如果没有在db service 中安装卷,容器将无法继续其进程。 it will start for just a second and then it will be terminated.它将启动一秒钟,然后将终止。 so that's why you are getting an error.所以这就是你收到错误的原因。

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/您必须在检查器中查看容器的端口部分,我的意见是您必须输入: mongodb://0.0.0.0:27017/

enjoy !请享用 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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