創(chuàng)建文件夾:
mkdir ~/docker-node-hello && cd $_
創(chuàng)建 index.js
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3001, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
創(chuàng)建 package.json
{
"name": "docker-node-hello",
"private": true,
"version": "0.0.1",
"description": "Node.js Hello world app on Ubuntu using docker",
"dependencies": {
"express": "4.x.x"
}
}
創(chuàng)建 Dockerfile 配置文件
# 設(shè)置基礎(chǔ)鏡像
FROM ubuntu:14.10
# 如果上個步驟已經(jīng)更新軟件源偎行,這步可以忽略
RUN apt-get update
# 安裝 NodeJS 和 npm
RUN apt-get install -y nodejs npm
# 將目錄中的文件添加至鏡像的 /srv/hello 目錄中
ADD . /srv/hello
# 設(shè)置工作目錄
WORKDIR /srv/hello
# 安裝 Node 依賴庫
RUN npm install
# 暴露 3001 端口劈猪,便于訪問
EXPOSE 3001
# 設(shè)置啟動時默認(rèn)運行命令
CMD ["nodejs”, “/srv/hello/index"]
構(gòu)建鏡像
# 通過該命令,按照 Dockerfile 所配置的信息構(gòu)建出鏡像
# -t 鏡像的名稱
# --rm 構(gòu)建成功后,刪除臨時鏡像(每執(zhí)行一行 Dockerfile 中的命令稼跳,就會創(chuàng)建一個臨時鏡像)
docker build --rm -t node-hello .
# 檢查鏡像是否創(chuàng)建成功
docker images
運行鏡像
docker run -p 3001:3001 --name nodejs1 node-hello