14.4 JavaScript

JavaScript是目前所有主流浏览器上唯一支持的脚本语言,这也是早期JavaScript的唯一用途。Node.js的出现,让服务端应用也可以基于JavaScript进行编写。

Node.js自2009年发布,使用Google Chrome浏览器的V8引擎,采用事件驱动,性能优异。同时还提供了很多系统级API,如文件操作、网络编程等。

下面,笔者将简述如何使用Docker搭建和使用Node.js环境。

使用Node.js环境

Node.js拥有3种官方镜像:node:<version>、node:onbuild、node:slim。

14.4 JavaScript - 图1

其中常用的是带有版本标签的,以及带有onbuild标签的node镜像。

首先,在Node.js项目中新建一个Dockerfile:


  1. FROM node:4-onbuild
  2. EXPOSE 8888

然后,新建server.js文件,内容如下:


  1. 'use strict';
  2. var connect = require('connect');
  3. var serveStatic = require('serve-static');
  4. var app = connect();
  5. app.use('/', serveStatic('.', {'index': ['index.html']}));
  6. app.listen(8080);
  7. console.log('MyApp is ready at http://localhost:8080');

之后,通过npm init命令来新建node项目所必须的package.json文件:


  1. $ npm init
  2. This utility will walk you through creating a package.json file.
  3. It only covers the most common items, and tries to guess sensible defaults.
  4. See `npm help json` for definitive documentation on these fields
  5. and exactly what they do.
  6. Use `npm install <pkg> --save` afterwards to install a package and
  7. save it as a dependency in the package.json file.
  8. Press ^C at any time to quit.
  9. name: (node) node
  10. version: (1.0.0)
  11. description: node-sample
  12. entry point: (index.js)
  13. test command:
  14. git repository:
  15. keywords:
  16. author:
  17. license: (ISC)
  18. About to write to /Users/faxi/Docker/js/node/package.json:
  19. {
  20. "name": "node",
  21. "version": "1.0.0",
  22. "description": "node-sample",
  23. "main": "index.js",
  24. "scripts": {
  25. "test": "echo \"Error: no test specified\" && exit 1"
  26. },
  27. "author": "",
  28. "license": "ISC"
  29. }
  30. Is this ok? (yes) yes

下面使用docker build指令构建node镜像:


  1. $ docker build -t node-image .

最后,创建并运行node容器:


  1. $ docker run -it -P node-image
  2. npm info it worked if it ends with ok
  3. npm info using npm@2.15.1
  4. npm info using node@v4.4.3
  5. npm info prestart node@1.0.0
  6. npm info start node@1.0.0
  7. > node@1.0.0 start /usr/src/app
  8. > node server.js
  9. MyApp is ready at http://localhost:8080

此时可以使用浏览器查看到MyApp应用的服务页面。

首先,使用docker ps指令查看端口绑定情况:


  1. $ docker ps
  2. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
  3. NAMES
  4. 7b6f666d4808 node-image "npm start" xxxago Up xx 0.0.0.0:32771->8888/tcp
  5. node-container

如果只需要运行单个node脚本的容器,则无需通过Dockerfile构建镜像,可以使用以下指令:


  1. $ docker run -it --rm --name my-running-script -v "$(pwd)":/usr/src/myapp -w
  2. /usr/src/myapp node:0.10 node your-daemon-or-script.js

读者也可以参考node官方提供的最佳实践:https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md