[英]Connecting to MongoDB with Mongoose in docker-compose containers fail with useUnifiedTopology
I have a NodeJS Application that connects to a MongoDB server.我有一个连接到 MongoDB 服务器的 NodeJS 应用程序。
Both the node application and MongoDB server are served in a docker container (with docker-compose
)节点应用程序和 MongoDB 服务器都在 docker 容器中提供服务(使用
docker-compose
)
docker-compose.yml
: docker-compose.yml
:
version: '3'
services:
redis:
image: "redis:alpine"
ports:
- "6379:6379"
expose:
- 6379
restart:
always
container_name: redis-server
mongo:
image: "mongo"
command: mongod --bind_ip_all --replSet rs8
volumes:
- c:\mongo\data:/data/db
ports:
- "27017:27017"
expose:
- 27017
restart:
always
container_name: mongo-server
accounts-service:
depends_on:
- redis
- mongo
build:
context: .
dockerfile: GenericNodeJSDockerfile
container_name: accounts-service
ports:
- "8001:8001"
In the node app, the connection in mongo looks like this:在 node 应用程序中,mongo 中的连接如下所示:
const m = require('mongoose') const connectionConfig = { useUnifiedTopology: true, useNewUrlParser: true, }; let connectionString = 'mongodb://mongo:27017/mydb/replicaSet=rs8'; m.connect(connectionString, connectionConfig).then(_ => { console.log("Connected to MongoDB") }).catch(err => { console.log("Failed connecting to MongoDB: " + err); });
And the error that is thrown is:抛出的错误是:
Failed connecting to MongoDB: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
But when I'm commenting the row contains useUnifiedTopology
option, the connection succeeds.但是当我评论该行包含
useUnifiedTopology
选项时,连接成功。
Does anyone have an idea how to fix it?有谁知道如何解决它?
It turns out that I had a wrong hosts
file configuration that made this issue.事实证明,我有一个错误的
hosts
文件配置导致了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.