Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Dockerを利用してSinatraアプリケーションを作成します

f:id:tbpg:20150917214910p:plain

Dockerを利用してSinatraアプリケーションを作成します

仕様

利用フォントをランダムに決定し、現在時刻を表示するWebアプリケーションを Dockerコンテナ上に作成します。

構成

└── docker_sinatra_timer
    ├── config.ru
    ├── Dockerfile
    ├── Gemfile
    ├── Procfile
    ├── start.sh
    └── timer.rb

プログラム

Gemfile

source 'https://rubygems.org'

gem 'sinatra', '~> 1.4.6'
gem 'thin'

timer.rb

require 'sinatra'

module Template
  HTML =<<-EOS
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Timer</title>
  <link href='https://fonts.googleapis.com/css?family=$font-family$' rel='stylesheet' type='text/css'>
</head>
<body>
  <div style="font-size:64px;font-family: '$font-family$', sans-serif;">$font-family$</div>
  <div style="font-size:64px;font-family: '$font-family$', sans-serif;">$time$</div>
</body>
</html>
  EOS

  WEB_FONTS = %w(Roboto Lato Oswald Slabo Lora Montserrat Raleway Merriweather Arimo Bitter)
end

get '/' do
  html = Template::HTML.gsub('$time$', Time.now.strftime("%Y/%m/%d %H:%M:%S"))
  html.gsub('$font-family$', Template::WEB_FONTS.sample)
end

config.ru

require './timer'
run Sinatra::Application

Procfile

web: bundle exec rackup config.ru -p 4567 -s thin -o 0.0.0.0

start.sh

#!/bin/bash
foreman start -p 4567

Dockerfile

FROM ruby:2.2.3
RUN gem install bundler
RUN gem install foreman
COPY . /app
WORKDIR /app
COPY Gemfile /app/Gemfile
COPY timer.rb /app/timer.rb
COPY config.ru /app/config.ru
COPY Procfile /app/Procfile
COPY start.sh /app/start.sh
EXPOSE 4567
RUN bundler
CMD ["foreman", "start", "-d", "/app", "-f", "/app/Procfile", "-p", "4567"]

実行

docker build

$ docker build -t tbpgr/timer .

docker run

$ ID=$(docker run -p 4567:4567 -d tbpgr/timer)

確認

実行1回目

f:id:tbpg:20150917214910p:plain

実行2回目

f:id:tbpg:20150917214914p:plain

GitHub

作成したアプリケ-ションおよびDockerfile等は以下のリポジトリに公開しました。
cloneして同じ手順を踏めば動作確認可能です。

tbpgr/docker_sinatra_timer - GitHub

関連資料