Docker & Nodejs & MongoDB
Nodejs Application Simple Access MongoDB deployment to Docker
The original address https://www.cnblogs.com/zhangyanbo/p/5851644.html (I encountered the operation of the situation can not continue, so slightly modified to improve)
Directory structure
.├── app.js├── controller├── Dockerfile├── model├── node_modules├── package.json├── router└── schemas
1. Local simple write can be run up a Nodejs (demo can be written more simple a post a Get can)
schemas/User.JSvarMongoose= require(' Mongoose ')varUserschema= New Mongoose.Schema({ name:{ Unique:true, type:String}, Password:{ type:String}, role:{ 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 . Span class= "at" >js var Mongoose = require ( ' Mongoose ' ) var userschema = require () var user = mongoose . model ( ' User ' Userschema) module . exports = User
controller/user.jsvar 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.JSvarExpress= require(' Express ');varRouter= Express.Router();varMongoose= require(' Mongoose ')//var dburl = ' Mongodb://localhost:27017/imooc ';varDburl= ' Mongodb://mongodb/imooc ';//mongodb The name is--LINK=AAA:BBB when the name is BBBMongoose.Connect(Dburl); varApp= Express(); app.Listen( the,function(){ Console.Log("Server start. Listen port:3000 ");}); require('./router/router ') (APP)
router/router.jsvar=require(‘../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.NPM Installation Express Mongoose underscore
npm install express mongoose underscore
3. Write dockerfile in the app.js file directory
FROM nodeRUN mkdir -p /home/srcCOPY . /home/srcRUN cd /home/src; npm install --registry=https://registry.npm.taobao.orgEXPOSE 3000CMD ["node""/home/src/app.js"]
4.docker Pull Mongo5.docker run-it--name MongoDB MONGO
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 Nodejs Application simple Access MongoDB deployment to Docker