docker コンテナ上で Hubot スクリプトを開発しはじめるときの自分のやり方


久しぶりに docker コンテナ上で Hubot スクリプトを開発してるんだけど、docker の使い方に慣れてきたのか、前よりもいい感じに環境構築できたのでメモしておく。

準備

まず、Dockerfile.devdocker-dev.sh という 2 つのファイルを用意する。

Dockerfile.dev

FROM node
RUN apt-get update && apt-get install -y vim
RUN npm install -g hubot coffee-script
WORKDIR /usr/local/hubot

docker-dev.sh

docker build -f Dockerfile.dev -t tily/hubot-example:dev .
docker run -ti --rm -v $(pwd):/usr/local/hubot tily/hubot-example:dev bash

開発しはじめる

docker-dev.sh を実行すると Dockerfile.dev を元にイメージがビルドされたあと、bash でログインした状態になる。(初回のみ時間がかかり、次回以降は一瞬でログインできる。)

$ ./docker-dev.sh 
Sending build context to Docker daemon 3.072 kB
Step 1 : FROM node
 ---> b554dc4860d7
Step 2 : RUN apt-get update && apt-get install -y vim
 ---> Using cache
 ---> e05afe17e1a0
Step 3 : RUN npm install -g hubot coffee-script
 ---> Using cache
 ---> 30f07011bb7c
Step 4 : WORKDIR /usr/local/hubot
 ---> Using cache
 ---> 5938ef13430e
Successfully built 5938ef13430e
root@cc998ad261a9:/usr/local/hubot#

npm init して package.json を生成する。

root@cc998ad261a9:/usr/local/hubot# npm init
(略)
root@cc998ad261a9:/usr/local/hubot# cat package.json 
{
  "name": "hubot-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

index.js ファイルで Hubot スクリプトを開発していく。

root@cc998ad261a9:/usr/local/hubot# vim index.js
root@cc998ad261a9:/usr/local/hubot# cat index.js 
module.exports = (robot)=> {
  robot.respond(/hello/, (message)=> { message.reply("world"); });
};

hubot -r . で動作確認する。(-r はスクリプトを読み込むディレクトリのパスを指定するオプション。)

root@cc998ad261a9:/usr/local/hubot# hubot -r .
Hubot> Hubot hello
Hubot> Shell: world

開発終了

開発が終わったら、exit してコンテナを破棄する。docker run 時にカレントディレクトリを /usr/local/hubot へマウントしていたので、ファイルの変更はホスト側にも反映されている。

root@cc998ad261a9:/usr/local/hubot# exit
exit
$ cat index.js 
module.exports = (robot)=> {
  robot.respond(/hello/, (message)=> { message.reply("world"); });
};

まとめ

docker が使える環境なら、2 ファイル用意すれば素早くいい感じに Hubot スクリプトの開発をはじめられるようになった。

hubot-brain 用に redis を立ち上げたいこととかありそうなので、docker-compose.yml にしたほうがいいのかもしれないけど、とりあえず最小限はこんな感じかな。