Skip to content

Instantly share code, notes, and snippets.

@kevingo
Last active January 26, 2016 13:41
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kevingo/c43bef3dc08137ebede8 to your computer and use it in GitHub Desktop.
Save kevingo/c43bef3dc08137ebede8 to your computer and use it in GitHub Desktop.
Dockerizing a Node.js web app

Dockerizing a Node.js web app

如果想要在 Docker 在跑 NodeJS 的應用,可以參考 NodeJS 官網上有一篇 「Dockerizing a Node.js web app」介紹,還蠻簡單易懂的,這邊稍微紀錄一下相關步驟。

安裝 Docker

可以參考 Docker 官網 Installation Guide

建立 package.json

{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "First Last ",
  "main": "server.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.13.3"
  }
}

p.s. 這個部分之前官網上的文章漏掉了 scripts 的區塊,這裏我上了一個 patch,有用到的可以注意一下。

使用 Express 建立 web server,建立一個如下的檔案,並且存成 index.js

'use strict';

const express = require('express');

// Constants
const PORT = 8080;

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

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

建立一個 Dockerfile,並寫入以下內容

FROM node:argon

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]

Dockerfile 是 docker 用來 build image 的參考檔案。裡面會包含多個 commands,Docker 在 build image 的時候,會照著裡面所列的步驟一步一步執行。詳細的指令可以參考 Docker 官方網站的 Dockerfile reference

在這邊的意思是,從 node 這個 base image 中,選擇 argon 這個 tag 所標示的版本來建立這個 image。在建立的過程中,先建立一個 /usr/src/app 資料夾,並且使用這個資料夾當作以下指令的工作目錄。指定完工作目錄後,copy package.json 這個檔案到工作目錄下,接著執行 npm install。接著繼續 copy 所有的檔案到工作目錄下,然後開放 8080 port。最後則是執行 command npm start

執行 docker build 建立 image

docker build -t <tag> .

執行 docker build 來建立 image,-t 是用來給你的 image 一個 tag,在這裡你可以用自定義的名稱。別忘了最後有一個 .,意味著你要切換到該目錄下作業。

查看建立好的 image

透過 docker iamges 指令,可以確認目前系統中建立好的 images。

Alt text

執行 image

你可以用 docker run 指令把剛剛建立好的 image 跑起來。-p 的參數代表你要把 public 的 port 綁到 container 的某個 port 上。-d 代表把這個 image 跑在背景。

docker run -p <public expose port>:<container expose port> -d <iamge tag>

MICS

剩下就是一些附加的指令,你可以用 docker ps 來看目前有哪些 container 正在跑,或是用 docker log <container id> 來看 log,也可以用 docker exec -it <container id> /bin/bash 進入到每個 container 的 bash 去操作。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment