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。

其中常用的是带有版本标签的,以及带有onbuild标签的node镜像。
首先,在Node.js项目中新建一个Dockerfile:
- FROM node:4-onbuild
- EXPOSE 8888
然后,新建server.js文件,内容如下:
- 'use strict';
- var connect = require('connect');
- var serveStatic = require('serve-static');
- var app = connect();
- app.use('/', serveStatic('.', {'index': ['index.html']}));
- app.listen(8080);
- console.log('MyApp is ready at http://localhost:8080');
之后,通过npm init命令来新建node项目所必须的package.json文件:
- $ npm init
- This utility will walk you through creating a package.json file.
- It only covers the most common items, and tries to guess sensible defaults.
- See `npm help json` for definitive documentation on these fields
- and exactly what they do.
- Use `npm install <pkg> --save` afterwards to install a package and
- save it as a dependency in the package.json file.
- Press ^C at any time to quit.
- name: (node) node
- version: (1.0.0)
- description: node-sample
- entry point: (index.js)
- test command:
- git repository:
- keywords:
- author:
- license: (ISC)
- About to write to /Users/faxi/Docker/js/node/package.json:
- {
- "name": "node",
- "version": "1.0.0",
- "description": "node-sample",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "author": "",
- "license": "ISC"
- }
- Is this ok? (yes) yes
下面使用docker build指令构建node镜像:
- $ docker build -t node-image .
最后,创建并运行node容器:
- $ docker run -it -P node-image
- npm info it worked if it ends with ok
- npm info using npm@2.15.1
- npm info using node@v4.4.3
- npm info prestart node@1.0.0
- npm info start node@1.0.0
- > node@1.0.0 start /usr/src/app
- > node server.js
- MyApp is ready at http://localhost:8080
此时可以使用浏览器查看到MyApp应用的服务页面。
首先,使用docker ps指令查看端口绑定情况:
- $ docker ps
- CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
- NAMES
- 7b6f666d4808 node-image "npm start" xxxago Up xx 0.0.0.0:32771->8888/tcp
- node-container
如果只需要运行单个node脚本的容器,则无需通过Dockerfile构建镜像,可以使用以下指令:
- $ docker run -it --rm --name my-running-script -v "$(pwd)":/usr/src/myapp -w
- /usr/src/myapp node:0.10 node your-daemon-or-script.js
读者也可以参考node官方提供的最佳实践:https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md。
