无法使用 mongoose 连接到 mongo docker 映像 [英] Can't connect to mongo docker image with mongoose
问题描述
我正在尝试使用 node 和 mongo 运行一个简单的 docker 设置:
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
现在在我的 app.js 中,我像这样连接到 mongo:
Now in my app.js I'm connecting to mongo like that:
mongoose.connect('mongodb://localhost:27017')
.catch(err => {
console.log(err)
})
但是我得到一个 在第一次连接时无法连接到服务器 [localhost:27017] [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
mongo 容器似乎启动并运行良好,让我等待端口 27017 上的连接
.
The mongo container seems to boot up and run fine giving me waiting for connections on port 27017
.
我的设置有什么问题?我还尝试在连接时将 localhost
换成 mongo
,但也没有效果.
What's wrong with my setup? I also tried swapping out localhost
for mongo
when connecting, but it had no effect either.
推荐答案
我没有意识到我将我的数据库容器命名为 db 而不是 mongo,所以我所要做的就是在我的 app.js 中切换该名称:
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)
})
这篇关于无法使用 mongoose 连接到 mongo docker 映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!