2015年6月12日 星期五

[Docker]Dockerizing a Node.js Web App Using Boot2Docker on Windows

[Docker]Dockerizing a Node.js Web App Using Boot2Docker on Windows

此篇內容參考https://docs.docker.com/examples/nodejs_web_app/,並做適當修改。

安裝 Boot2Docker

詳細步驟參考 https://docs.docker.com/installation/windows/

打開Boot2Docker

打開之後會如圖片:
enter image description here
這邊的虛擬IP需要記錄一下,如圖中的192.168.59.103

建立資料夾src

mkdir src
cd src

建立package.json

package.json內容為:

{
  "name": "docker-centos-hello",
  "private": true,
  "version": "0.0.1",
  "description": "Node.js Hello world app on CentOS using docker",
  "author": "Daniel Gasienica <daniel@gasienica.ch>",
  "dependencies": {
    "express": "3.2.4"
  }
}

建立index.js

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);

建立Dockerfile

使用指令

vi Dockerfile

Dockerfile內容為

FROM    centos:centos6

# Enable EPEL for Node.js
RUN     rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
# Install Node.js and npm
RUN     yum install -y npm

# Bundle app source
COPY . /src
# Install app dependencies
RUN cd /src; npm install

EXPOSE  8080
CMD ["node", "/src/index.js"]

建立你的映像檔

docker build -t <your username>/centos-node-hello .

注意後面的 “.” 是必需的,所以指令會是像底下這樣:

docker build -t moonjuice/centos-node-hello .

如果建立成功,可以使用指令:

docker images

應該就會看到妳剛剛建立的映像檔。

執行映像檔

使用指令:

docker run -p 49160:8080 -d <your username>/centos-node-hello

以我的例子來說:

docker run -p 49160:8080 -d moonjuice/centos-node-hello

如果執行成功,可以使用指令:

docker ps

看到目前正在執行的 Container.

這時候開啟瀏覽器輸入網址:http://<剛剛紀錄的虛擬IP>:49160/,就可以看到 顯示 Hello World 的網頁。以我的 ip 為例:

http://192.168.59.103:49160/

enter image description here

或是使用指令:

curl -i <剛剛紀錄的虛擬IP>:49160

以我的 ip 為例:

curl -i 192.168.59.103:49160

可以得到:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 12
Date: Fri, 12 Jun 2015 13:59:39 GMT
Connection: keep-alive

Hello world

這樣就代表執行成功啦!

注意:我這邊使用 curl -i localhost:49160 ,會得到

curl: (7) Failed to connect to localhost port 49160: Connection refused

的錯誤。
不確定是不是有什麼可以修正的指令或是 Boot2Docker 本身的問題。

沒有留言: