我的node.js express app无法连接到Docker中的MongoDB。我对Docker并不熟悉。
node.js连接:
import mongodb from 'mongodb';
...
mongodb.MongoClient.connect('mongodb://localhost:27017', ... );
Dockerfile:
FROM node:argon
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "start"]
泊坞窗,compose.yml
version: “2”
services:
web:
build: .
volumes:
— ./:/app
ports:
— “3000:3000”
links:
— mongo
mongo:
image: mongo
ports:
— “27017:27017”
建立命令:docker build -t NAME .
运行命令:docker run -ti -p 3000:3000 NAME
连接错误:
[MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]]
name: 'MongoError',
message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]'
尝试:
mongodb.MongoClient.connect('mongodb://mongo:27017', ... );
改变你的docker-compose.yml
:
version: "2"
services:
web:
build: .
volumes:
- ./:/app
ports:
- "3000:3000"
links:
- mongo
mongo:
image: mongo
ports:
- "27017:27017"
并使用一些docker compose命令:
docker-compose down
docker-compose build
docker-compose up -d mongo
docker-compose up web
试试这个。
mongodb.MongoClient.connect('mongodb://mongo:27017', ... );
而不是mongodb.MongoClient.connect('mongodb://localhost:27017', ... );
。将其更改为mongo的原因是因为您在docker-compose.yml
中使用了links属性mongo。这将导致您的web docker容器的/etc/hosts
中的mongo主机名。参考linking-containers。version: '2'
services:
web:
build: .
volumes: ['./:/app']
ports: [ '3000:3000' ]
links: [ mongo ]
mongo:
image: mongo
ports: [ '27017:27017' ]
docker-compose.yml
然后我docker-compose build
然后docker-compose up
。 Logs of my local run我不确定你是否还有这个问题,但datasources.json
应该是:
"host": "mongo"
而不是“localhost”。
在我的日志中,我看到:
mongo | NETWORK [listener] connection accepted from 172.22.0.3:47880 #1 (1 connection now open)
正如您所看到的,docker compose将NAT mongo转移到另一个V-LAN。 IP地址172.22.0.0
是守护程序用于路由docker-compose
映像的内部IP地址。所以localhost
现在不在游戏中。
至少,它对我有用。
datasources.json
"mongoDS": {
"host": "mongo",
"port": 27017,
...