標籤:
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