Write a simple Node project

The project address

The directory structure is as follows:

App.js is as follows:

// app.js

const express = require('express')
var mongoose = require('mongoose');

const app = express()
mongoose.connect('mongodb://mongodb/test');


var kittySchema = mongoose.Schema({
  name: String
});

kittySchema.methods.speak = function () {
  var greeting = this.name
    ? "Meow name is " + this.name
    : "I don't have a name";
  console.log(greeting);
}

var Kitten = mongoose.model('Kitten', kittySchema);

app.get('/create', (req, res) => {
  var fluffy = new Kitten({ name: 'fluffy' });

  fluffy.save(function (err, fluffy) {
    if (err) return console.error(err);
    fluffy.speak();
  });
  res.send(fluffy.speak())
})

app.get('/', (req, res) => {
  Kitten.find(function (err, kittens) {
    if (err) return console.error(err);
    res.send(kittens)
  })
  // res.send('hello aa')
})

app.listen(3000.console.log('Example app listening on port 3000! '))


Copy the code

Write Dockerfile

FROM node:latest

RUN mkdir -p /home/project
WORKDIR /home/project

RUN chmod -R 777 /home/project
COPY . /home/project

RUN npm install

EXPOSE 3000

ENTRYPOINT ["npm"."run"]
CMD ["start"]

Copy the code

Install the docker

Please refer to www.runoob.com/docker/maco…

Docker packages node projects as images

In the project root directory

docker build -t node .
Copy the code

Docker runs mongo containers

Docker pulls the Mongo image

docker pull mongo
Copy the code

Docker starts with mongo containers

docker run -p 27017:27017 -v $PWD/db:/data/db -d --name mongodb mongo:latest
Copy the code

Docker Running Node project

docker run -d --name nodeapp --link=mongodb:mongodb -p 3000:3000 node
Copy the code

Note:

  • Mongodb: the first mongodb is the name of the mongo container and the second mongodb is the address of the mongodb service in app.js