Nodejs Application Simple Access MongoDB deployment to Docker
1.
Local simple write can be run up a Nodejs (demo can be written more simple a post a Get can)
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 the name is Bbbmongoose.connect (Dburl) at--link=aaa:bbb, 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);}
Ensure that the local is functioning properly.
2. Write dockerfile in the app.js file directory
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 Enter terminal
Cd/homemkdir dbmongod--dbpath= '/home/db ' Start MongoDB service
6.docker build-t Nodejsdemo./
Docker run-it-p 3000:3000--name Nodejsdemo--link=mongodb:mongodb Modejsdemo
At this point the console can see the server start Listen port:3000
Browser Access 192.168.99.100:3000
Docker & Nodejs & MongoDB