使用docker-compose与mongodb,node和postman的正确方法是什么?

时间:2017-11-01 19:28:35

标签: node.js mongodb docker docker-compose

我知道之前已经被问过并回答了,但我已经阅读了很多答案,做了很多谷歌搜索,似乎仍然无法弄清楚发生了什么。

我想使用docker和mongodb使用docker创建一个待办事项列表应用程序。我有像这样的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连接到此mongoose.createConnection('mongodb://mongo:27017');而不是localhost。但是,当我尝试在Postman中POST到我的/ 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');
  });
});

1 个答案:

答案 0 :(得分:1)

在服务器运行之前,您必须确保mongo已启动并正在运行。目前,当您从服务器连接时,mongo可能正在启动。有几种方法可以解决这个问题。也许是在开始你的npm进程之前等待端口27017的shell脚本。请查看此问题以供参考How to wait for an open port with netcat?。这个:https://docs.docker.com/compose/startup-order/

此外,我没有在您的服务器代码上看到POST路由