如何从主机连接MongoDb docker容器



我正在学习MongoDb,并试图用NodeJS创建一个简单的CRUD。我从这个码头构建容器组成:

version: '3.1'
services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 123mudar
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: 123mudar

我做了两种方式的连接实例:

mongoose.connect('mongodb://root:123mudar@localhost:27017/learning_mongo', { useUnifiedTopology: true, useNewUrlParser: true });

mongoose.connect('mongodb://localhost:27017/learning_mongo', { useUnifiedTopology: true, useNewUrlParser: true });

两者都不起作用。从Ubuntu托管这些容器,我尝试使用命令行进行连接。

$mongo

MongoDB shell version v3.6.8
connecting to: mongodb://127.0.0.1:27017
2020-12-11T02:17:48.844-0300 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2020-12-11T02:17:48.844-0300 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:257:13
@(connect):1:6
exception: connect failed

有人能帮我找出问题吗?

在我的例子中,docker-compose.yml看起来像这个

version: "3"
services:
app:
container_name: scan-app-backend
restart: always
build: ./api
ports:
- "3001:3001"
links:
- mongo
mongo:
container_name: mongo
image: mongo
ports:
- "27017:21017"
react-app:
container_name: scan-app-frontend
build: ./dashboard
ports:
- "3000:3000"
stdin_open: true

现在,您必须在传入Express服务器时更改数据库URL。

const mongoose = require("mongoose");
module.exports = mongoose
.connect('mongodb://mongo:27017/scans', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB server"))
.catch((error) => console.log(error));

我不确定什么是mongo express

在你的情况下会是

Docker compose-

图中的MongoDB服务器在标准MongoDB端口27017 上侦听

mongo:
container_name: mongo
restart: always
ports:
- "27017:27017"
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: 123mudar
const mongoose = require("mongoose");
module.exports = mongoose
.connect('mongodb://mongo:27017/learning_mongo', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB server"))
.catch((error) => console.log(error));