Docker + Nodejs + Mongo:MongoError:首次连接时无法连接到服务器[172.17.0.2:27017]

时间:2018-08-22 16:32:48

标签: node.js mongodb docker docker-compose

我正在尝试dockerize和与mongodb连接的Nodejs API稳定...

但是当我尝试运行(docker-compose up)时。该应用在终端上给了我这个错误:

“ MongoError:首次连接时无法连接到服务器[172.17.0.2:27017]”

Nodejs:

var express = require('express');
var mongo = require('mongoose');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

var mongoaddr = 'mongodb://' + process.env.MONGO_PORT_27017_TCP_ADDR + 
':27017/testeapi';
console.log(mongoaddr);
mongo.connect(mongoaddr);

var taskListSchema = mongo.Schema({
    descricao : { type: String },
    concluido : Boolean,
    updated_at: { type: Date, default: Date.now },
});

var Model = mongo.model('Tasks', taskListSchema);

app.post("/api/add", function (req, res) {
    var register = new Model({
        'descricao' : req.body.descricao,
        'concluido' : req.body.concluido
    });
    register.save(function (err) {
        if (err) {
            console.log(err);
            res.send(err);
            res.end();
        }
    });
    res.send(register);
    res.end();
});

app.get("/api/all", function (req, res) {
    Model.find(function(err, todos) {
        if (err) {
            res.json(err);
        } else {
            res.json(todos);
        }
    })
});

app.delete("/api/delete/:id", function (req, res) {
 Model.findByIdAndRemove(req.params.id, req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

app.listen(8080, function() {
    console.log('Working');
});

package.json:

{
  "name": "node-app",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app.js"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "express": "^4.14.0",
    "mongoose": "~4.6.1",
    "nodemon": "^1.10.2",
    "body-parser": "1.15.2"
  }
}

docker-compose.yml:

mongo:
  image: mongo:3.0.4
  ports:
   - "27017:27017"
  volumes:
   - './data:/data/db'
application:
  build: .
  command:  bash -c "npm install; nodemon app.js --color=always"
  ports:
   - "8080:8080"
   - "5858:5858"
  volumes:
   - ./app:/usr/src/app
  links:
   - mongo

Dockerfile:

 FROM node:7.1 

 RUN mkdir -p /usr/src/app  
 RUN npm install nodemon -g  

 WORKDIR /usr/src/app  
 COPY app/package.json /usr/src/app/package.json  
 RUN npm install -g  

 EXPOSE 8080  
 EXPOSE 5858  

 CMD ["npm", "start"]  

文件如下:

app   app.js   package.json Docker文件 docker-compose.yml

运行其以下命令:

docker-compose构建 docker-compose run

Thanos!

0 个答案:

没有答案