前提
- Alpine 3.4
- Ruby 2.3.3
- Rails 5.0.0.1
Railsアプリケーションと、GemfileとGemfile.lockは、事前に用意してあるものとします。
Dockerfile
FROM ruby:2.3.3-alpine
MAINTAINER Shigeru Nakajima <shigeru.nakajima@gmail.com>
ENV BUILD_PACKAGES="curl-dev ruby-dev build-base bash" \
DEV_PACKAGES="zlib-dev libxml2-dev libxslt-dev tzdata yaml-dev sqlite-dev postgresql-dev mysql-dev" \
RUBY_PACKAGES="ruby-json yaml nodejs"
# Update and install base packages and nokogiri gem that requires a
# native compilation
RUN apk update && \
apk upgrade && \
apk add --no-cache --update\
$BUILD_PACKAGES \
$DEV_PACKAGES \
$RUBY_PACKAGES && \
mkdir -p /usr/src/app
# Copy the app into the working directory. This assumes your Gemfile
# is in the root directory and includes your version of Rails that you
# want to run.
WORKDIR /usr/src/app
COPY . /usr/src/app
EXPOSE 3000
RUN bundle config build.nokogiri --use-system-libraries && \
bundle install && \
bundle clean
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
実行
docker build -t hogehoge .
docker run --rm hogehoge
で起動します(hogehogeは適当です)。
どのようにして作ったか?
alpine-rails/Dockerfile at master · alim/alpine-railsを元にしました。
変更点
ベースイメージ
Ruby 2.3.3にします。
FROM ruby:2.3.3-alpine
centurylink/alpine-railsをベースイメージにすることも考えましたがalpine:3.2
だったのでやめました。
apkパッケージのインストール方法
Alpine Linux で軽量な Docker イメージを作る - Qiita
Alpine Linux は 3.3 から apk で --no-cache というオプションが使えます。
apk add
に--no-cache
オプションを追加します。
rm -rf /var/cache/apk/*
を削除します。
onbuildをなくす
直接docker buildするために22行目以降のONBUILD
指定を消します。
消さないとGemfileがコピーされていないので、docker run
時に次のエラーが出ます。
Could not locate Gemfile or .bundle/ directory
実行コマンドを修正
bundler経由で起動したいので
CMD ["rails", "server", "-b", "0.0.0.0"]
を
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
に修正します。
修正前は、docker run
時に次のエラーが出ます。
docker: Error response from daemon: invalid header field value "oci runtime error: container_linux.go:247: starting container process caused \"exec: \\\"rails\\\": executable file not found in $PATH\"\n".