docker-compose只运行我的mongodb服务器但没有运行我的js文件

时间:2017-11-23 16:15:48

标签: javascript node.js mongodb docker docker-compose

我是使用docker的新手。我正在开发一个简单的表单,将用户输入的数据提交到mongodb数据库,并将他/她重定向到感谢html页面。 它在我的本地主机上工作得很好但是当我对其进行停靠时,它不起作用。 事实上,我的代码在Mac上完美运行,但在Windows操作系统上运行不正常。 任何帮助将不胜感激。

这是我的js代码:

var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var MongoClient = require('mongodb').MongoClient;

app.use(express.static(__dirname + '/../public'));
app.get('/', (req,res)=> file = fs.createReadStream(__dirname + '/clientlogin.html').pipe(res));
app.get('/thanks', (req,res)=> file = fs.createReadStream(__dirname + '/formthanks.html').pipe(res));
app.post('/', urlencodedParser, function(req,res){
    var firstname = req.body.firstname;
    var lastname = req.body.lastname;
    var email = req.body.email;
    var phonenumber = req.body.phonenumber;
    var pass = req.body.password;

// Use connect method to connect to the server
var url = "mongodb://mongo:27017/clientdb";
MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var obj = {
        'FirstName': firstname,
        'LastName': lastname,
        'Email': email,
        'PhoneNumber': phonenumber,
        'Pass': pass
    };
    db.collection("myclients").insertOne(obj, function(err, res) {
      if (err) throw err;
      console.log("1 client registered!");
      db.close();
    });
    res.redirect('/thanks');
});

});
app.listen(8081, function(){
    console.log("Listening on port 8081");
});

我的package.json代码

{
  "name": "loginpage",
  "version": "1.0.0",
  "description": "login page",
  "main": "signupmongo.js",
  "scripts": {
    "start": "node signupmongo.js"
  },
  "author": "David",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "fs": "0.0.1-security",
    "mongodb": "^2.2.33",
    "mongoose": "^4.13.4"
  }
}

我的dockerfile

FROM node:argon
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8081
CMD ["npm", "start"]

我的docker-compose.yml文件

version: "3"
services:
  web:
    build: .
    volumes:
      - ./:/app
    ports:
      - "8081:8081"
    depends_on:
      - mongo
  mongo:
    image: mongo
    ports:
      - "27017:27017"

这是命令行界面,代码似乎停止运行。 enter image description here

1 个答案:

答案 0 :(得分:0)

您必须在应用容器中链接mongo容器。使用链接功能 例如:

version: "3"
services:
  web:
    build: .
    volumes:
      - ./:/app
    ports:
      - "8081:8081"
    links:
      - mongo
    depends_on:
      - mongo
  mongo:
    image: mongo
    ports:
      - "27017:27017"