Docker node 生产环境配置

12 min read

index.js

var express = require('express');

// Constants
var PORT = 8080;

// App
var app = express();
app.get('/', function (req, res) {
res.send('Hello World\n');
});

app.listen(PORT)
console.log('Running on http://localhost:' + PORT);

package.json文件的内容为:

{
    "name": "docker-centos-hello",
    "private": true,
    "version": "0.0.1",
    "description": "Node.js Hello World app",
    "author": "linyiting",
    "dependencies": {
        "express": "^4.13.4"
    }
}

定义运行应用的命令

由于我们web应用使用了8080端口,我们需要把这个端口公开:

EXPOSE  8080

使用CMD定义启动应用的命令行

CMD ["node", "/usr/code/index.js"]

完整的Dockerfile:


FROM ubuntu:zesty


ADD sources.list /etc/apt/sources.list

# Install Node.js 安装Node.js运行环境
RUN apt-get update && apt-get install -y curl && \
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - && \
apt-get install -y nodejs

# 将项目文件复制到镜像中
RUN mkdir -p /usr/code
COPY index.js /usr/code/
COPY package.json /usr/code/

# npm install
RUN cd /usr/code && npm install

# 公开镜像的8080端口
EXPOSE 8080

# 定义应用的启动命令行
CMD ["node", "/usr/code/index.js"]

构建镜像

构建镜像的命令

sudo docker build -t <your username>/ubuntu-nodejs-hello .

# example
sudo docker build -t test/ubuntu-nodejs-hello .

构建的过程中,如果你docker上已经安装了ubuntu:trusty的镜像,docker会在该镜像的基础上构建新镜像;否则,docker会安装ubuntu:trusty镜像,然后在构建ubuntu-nodejs-hello

运行镜像

-d使镜像在运行在后台模式下,-p参数会将容器的私有端口转发到主机的上共有端口:

sudo docker run -p 49160:8080 -d test/ubuntu-nodejs-hello

使用curl查看应用是否运行:

curl -i localhost:49160

输出:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 12
ETag: W/"c-5Z/5eUEET4XfUpfhwwLSYA"
Date: Mon, 09 May 2016 09:13:01 GMT
Connection: keep-alive

Hello World

可以看到,我们的应用已经成功运行。