LoginSignup
6

More than 5 years have passed since last update.

Dockerでnode-stacicの静的コンテンツ用Webサーバーを起動する

Posted at

テスト用に手軽な静的Webサーバーを使いたかったのでnode-staticをDockerコンテナで起動しました。ちょっとしたJavaScriptのアプリを簡単にデプロイして確認することができます。

node-staticコンテナ

最初にプロジェクトに作成したファイル一覧です。

$ cd ~/node_apps/node-static
$ tree
.
├── Dockerfile
├── app.js
├── package.json
└── public
    └── index.html

Dockerfileはgoogle/nodejs-runtimeをベースイメージに使います。

~/node_apps/node-static/Dockerfile
FROM google/nodejs-runtime
VOLUME /app/public
EXPOSE 80

app.jsのメインプログラムでは静的ファイルをデプロイするディレクトリとしてpublicを指定します。

~/node_apps/node-static/app.js
var static = require('node-static');
var file = new static.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        file.serve(request, response);
    }).resume();
}).listen(80);

console.log("Server running at http://localhost");

package.jsonではnode-staticパッケージをインストールします。

~/node_apps/node-static/package.json
{
  "name": "node-static-app",
  "description": "node static app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "node-static": "0.7.6"
  },
  "scripts": {"start": "node app.js"}
}

A Minimal HTML Document (HTML5 Edition)を参考にしてミニマルなindex.htmlを用意します。

~/node_apps/node-static/public/index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>title</title>
  </head>
  <body>
    <p>hello world</p>
  </body>
</html>

コンテナの起動と確認

Dockerイメージをビルドします。

$ docker build -t node-static . 

Dockerコンテナを起動します。

$ docker run -d \
  --name node-static \
  -p 80:80 \
  -v $PWD/public:/app/public \
  node-static

localhostから簡単に確認してみます。

$ curl localhost
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>title</title>
  </head>
  <body>
    <p>hello world</p>
  </body>
</html>

publicディレクトリはVOLUMEにマウントしているのでDockerコンテナが起動中にファイルを編集することができます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6