1. 建立一个文件夹
  2. 用管理员身份打开powershell.
  3. 在文件夹下面运行npm init, 根据提示填入信息,以便产生一个package.json文件。
  4. 在文件中加入需要的dependencies,例如:
  5. {
  6. "name": "docker_web_app",
  7. "version": "1.0.0",
  8. "description": "Node.js on Docker",
  9. "author": "First Last <first.last@example.com>",
  10. "main": "server.js",
  11. "scripts": {
  12. "start": "node server.js"
  13. },
  14. "dependencies": {
  15. "express": "^4.13.3"
  16. }
  17. }
  18.  

    4. 创建一个app.js文件,例如:

    const express = require('express')

    const app = express()

     

    app.get('/', function (req, res) {

    res.send('Hello World!')

    })

     

    app.listen(3000, function () {

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

    })

     

    5. 创建一个空文件名字为Dockerfile,填入如下内容:

    FROM node:boron

     

    # Create app directory

    WORKDIR /app

     

    # Install app dependencies

    COPY package.json .

    # For npm@5 or later, copy package-lock.json as well

    # COPY package.json package-lock.json ./

     

    RUN npm install

     

    # Bundle app source

    COPY . .

     

    EXPOSE 3000

    CMD [ "node", "app.js" ]

     

    6. 创建名为.dockerignore的文件,并输入如下的内容:

node_modules

npm-debug.log

 

这是为了防止本地的module和debug log被拷贝进docker image.

(我这一步无法做,因为没有办法创建这样的文件,总是要求必须有文件名。需要进一步调查)

7. Build image

docker build -t nodehello .

 

8. 运行image.

docker run -p 3000:3000 -d nodehello

 

如果运行成功,会出现Example app listening on port 3000的字样。

 

这时访问http://localhhost:3000 就可以访问app.js中定义的内容了。

 

参考文章:

https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

https://www.distelli.com/docs/tutorials/build-and-deploy-nodejs-with-docker/

https://expressjs.com/en/starter/hello-world.html

https://docs.docker.com/get-started/part2/#build-the-app

 

 

 

posted on 2017-10-20 17:32  今夜太冷  阅读(534)  评论(0编辑  收藏  举报