[英]What is the correct way to use docker-compose with mongodb, node, and postman?
我知道以前已經有人問過這個問題,但我已經讀了很多答案,做了很多谷歌搜索,但似乎仍無法弄清到底是怎么回事。
我想使用docker創建一個待辦事項列表應用程序,使用node和mongodb。 我有一個像這樣的docker-compose文件
local:
image: local
ports:
- "3000:3000"
volumes:
- ./:/project
links:
- mongo
# runs nodemon server.js
entrypoint: ["npm", "run", "start"]
mongo:
image: mongo:latest
ports:
- "27017:27017"
volumes:
- ./data/db:/data/db
entrypoint: ["mongod", "--port", "27017"]
我非常小心,以確保要連接到像mongoose.createConnection('mongodb://mongo:27017');
這樣的mongoose.createConnection('mongodb://mongo:27017');
而不是本地主機。 但是,當我嘗試在Postman中發布到/ tasks路由時,什么也沒有發生。 整個server.js文件是
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const mongoose = require('mongoose');
const Task = require('./api/models/todoListModel');
const bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.createConnection('mongodb://mongo:27017');
// I've also tried mongodb://mongo/local:27017 and /project just in case...
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const routes = require('./api/routes/todoListRoutes');
routes(app);
app.get('/', (req, res) => {
res.json({ message: 'At least this works...' });
});
app.listen(port);
console.log(`listening on port ${port}`);
謝謝你的盡心幫助!
更新 -以下答案基本上是正確的。 在使用服務器之前,我確實需要等待mongo啟動。 但是我不明白在這種情況下,我只能延遲在服務器上監聽以使其正常工作。 以下似乎正常工作。
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const mongo = 'mongodb://mongo:27017'
mongoose.connect(mongo);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', (err) => {
console.log(`DB Error -> ${err}`);
})
app.get('/', (req, res) => {
res.send('Hello world');
});
/*
Note that the server can be constructed in advance.
It only begins actively listening once the mongo/mongoose connection is fully open.
This way you don't have to use an external script to wait for the ports to open.
*/
db.once('open', () => {
app.listen(3000, () => {
console.log('App is listening on 3000');
});
});
您必須確保mongo正常運行,然后服務器才能運行。 從服務器連接時,當前mongo可能正在啟動。 有幾種解決方法。 也許一個shell腳本在啟動npm進程之前會等待端口27017
。 查看此問題以供參考如何使用netcat等待開放端口? 。 這是: https : //docs.docker.com/compose/startup-order/
另外我在您的服務器代碼上沒有看到POST路由
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.