[英]Connect mongo docker container with node.js
docker-compose.yml: docker-compose.yml:
version: '3.1'
services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
index.js:索引.js:
const mongoose = require('mongoose')
mongoose
.set('strictQuery', false)
.connect('mongodb://root:example@mongo:27017/')
.then(() => console.log('Connected!'))
.catch((e) => console.log('Mongo Error:', e.message))
const Book = mongoose.model('Book', new mongoose.Schema({
title: {
type: String,
required: true,
unique: true,
minlength: 2
},
published: {
type: Number,
required: true,
},
author: {
type: String,
required: true,
},
}));
const book = new Book({ title: 'Harri Potter', published: 1997, author: "J. K. Rowling" })
//book.save()
package.json package.json
{
"name": "sb",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"mongoose": "^6.8.3",
"nodemon": "^2.0.20"
}
}
And then how to connect.然后是如何连接。
$ docker-compose up -d
....
$ npm run dev
ivo@LAPTOP-0KNMEE5S MINGW64 /c/myproj/sb (master)
$ npm run dev
> sb@1.0.0 dev
> nodemon index.js
[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Mongo Error: getaddrinfo ENOTFOUND mongo
[nodemon] clean exit - waiting for changes before restart
I puzzle a long time it.我困惑了很久呢。 Can somebody help me????
有人可以帮帮我吗???? Please working example.
请工作示例。 Than you forward
比你前进
You need to map your PC port to the docker one:你需要把你PC的map端口到docker之一:
version: '3.1'
services:
mongo:
image: mongo
restart: always
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
Then in your node.js script然后在你的 node.js 脚本中
...
.connect('mongodb://root:example@127.0.0.1:27017/')
...
The mongo:27017
would work only if you run your node.js application inside a docker container in the same mongo container's.network.只有在同一个 mongo 容器的 .network 中的 docker 容器内运行 node.js 应用程序时,
mongo:27017
才会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.