我有一个在本地运行的mongoDB docker,称为“ some-mongo”。在同一台计算机上,我还运行了后端服务器(由nodeJS制成)。问题是使用“ mongoose”模块将我的nodeJS服务器连接到本地mongo docker。
我通过运行以下命令启动了mongoDB docker:
docker run --name some-mongo -d mongo
我的nodeJS服务器尝试按以下方式连接到mongo docker:
const mongoose = require('mongoose');
const app = express();
//Connect to db
mongoose.connect('mongodb://local-host:27017/some-mongo')
.then(db => console.log('DB Mongo: connected'))
.catch(err => console.log(err));
问题是出现以下错误:
Server on port 3000
{ MongoNetworkError: failed to connect to server [local-host:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND local-host local-host:27017]
at Pool.<anonymous> (/Users/bisite/Documents/Git/Trusted-Industry/TrustedIndustryFront/node_modules/mongodb/lib/core/topologies/server.js:431:11)
at Pool.emit (events.js:198:13)
at connect (/Users/bisite/Documents/Git/Trusted-Industry/TrustedIndustryFront/node_modules/mongodb/lib/core/connection/pool.js:580:14)
at makeConnection (/Users/bisite/Documents/Git/Trusted-Industry/TrustedIndustryFront/node_modules/mongodb/lib/core/connection/connect.js:39:11)
at callback (/Users/bisite/Documents/Git/Trusted-Industry/TrustedIndustryFront/node_modules/mongodb/lib/core/connection/connect.js:261:5)
at Socket.err (/Users/bisite/Documents/Git/Trusted-Industry/TrustedIndustryFront/node_modules/mongodb/lib/core/connection/connect.js:286:7)
at Object.onceWrapper (events.js:286:20)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
答案 0 :(得分:1)
如果在单个Docker容器中运行它,则必须像这样公开端口buckets
:
27017
但是将docker run --name some-mongo -d mongo -p 27017:27107
与mongoDB和app一起用作容器化应用程序将是一种更为安全的方法。
这样,您就不必在docker基础架构外部暴露mongo端口。