docker & nodejs & mongodb

來源:互聯網
上載者:User

標籤:

Nodejs 應用簡單的訪問Mongodb 部署至Docker

 

1.

本地簡單的寫能運行起來的一個nodejs (demo可寫的更簡單 一個post一個get即可)

schemas  user.js

var mongoose = require(‘mongoose‘)var UserSchema = new mongoose.Schema({name:{unique:true,type:String},password:{type:String},//0  1  2  3  4role:{type:Number,default:5}})UserSchema.statics = {fetch:function(cb){return this.find({}).exec(cb)},findById:function(id,cb){return this.findOne({_id:id}).exec(cb)}}module.exports = UserSchema

model user.js  

var mongoose = require(‘mongoose‘)var UserSchema = require(‘../schemas/user‘)var User = mongoose.model(‘User‘,UserSchema);module.exports = User;

controller user.js

var User = require(‘../model/user‘)exports.list = function(req,res){User.fetch(function(err,users){if(err) {console.log(err)}res.send(users);})}exports.save = function(req,res){console.log(req.query.name);var name = req.query.name || ‘noname‘;var password = ‘abcdefg‘;var user = new User({"name":name,"password":"123456"})user.save(function(err){if(err){console.log(‘false‘);res.send("fails");return;}res.redirect(‘/‘);})}

 

app.js

var express = require(‘express‘);var router = express.Router();var mongoose = require(‘mongoose‘)//var dbURL = ‘mongodb://localhost:27017/imooc‘;var dbURL = ‘mongodb://mongodb/imooc‘;//mongodb這個名字是 在--link=aaa:bbb時的名字 即bbbmongoose.connect(dbURL);var app = express();app.listen(3000,function(){console.log("server start. Listen port:3000");});require(‘./router/router‘)(app)

  router.js

var User = require(‘../app/controller/user‘)var _ = require(‘underscore‘)module.exports = function(app){app.get(‘/‘,User.list)app.get(‘/user‘,User.save);}

  確保本地能夠正常運行。

2.在app.js檔案目錄編寫dockerfile

FROM nodeCOPY . /home/srcRUN cd /home/src; npm installEXPOSE 3000CMD ["node","/home/src/app.js"]

 

4.docker pull mongo 

5.docker run -it --name mongodb mongo /bin/bash  進入終端

cd /homemkdir dbmongod --dbpath=‘/home/db‘啟動mongodb服務

 

6.docker build -t nodejsdemo ./ 

docker run -it -p 3000:3000 --name nodejsdemo --link=mongodb:mongodb modejsdemo

此時控制台可以看到 server start Listen port:3000

 

瀏覽器訪問 192.168.99.100:3000

 

docker & nodejs & mongodb

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.