ソフトウェア/docker/Railsを動かす のバックアップ差分(No.7)

更新


  • 追加された行はこの色です。
  • 削除された行はこの色です。
[[公開メモ]]

* 参考にしたページ [#k6629f77]

https://qiita.com/okamos/items/8e9b258e3d610bdc2ed9

Qiita - Ruby on Rails 5.2の新機能(Active Storage, Content Security Policyなど)~
https://qiita.com/ryohashimoto/items/75f48fa5a3846c58f735

* 構成案 [#l84246f8]

まだ考え中。

vagrant box に ubuntu/trusty64 を入れて、その中に以下の docker コンテナを用意する?

- データボリューム
- nginx サーバー
- rails サーバー
- postgresql サーバー

永続化が必要なデータは vagrant box 外のホストファイルシステムに置く?(とりあえず)

デプロイ方法はまた考える。

* vagrant で ubuntu/trusty64 に docker を入れる [#hc08e5d0]
* vagrant で ubuntu/xenial64 に docker を入れる [#hc08e5d0]

とりあえず開発用に、Windows 版の vagrant + VirtualBox で以下のように。

deploy 環境の構築についてはまた後で考える。

 LANG:console
 $ mkdir trusty64docker
 $ cd trusty64docker
 $ vagrant init
 $ ls
  Vagrantfile
 $ vi Vagrantfile # 変更点のみ
  # encoding: UTF-8
    config.vm.box = "ubuntu/trusty64"
    config.vm.box = "ubuntu/xenial64"
    config.vm.network "private_network", ip: "192.168.33.10"
    config.vm.provider "virtualbox" do |vb|
      vb.memory = "1024"
      # VM name
      vb.name = "xenial64docker"
      # Customize the amount of memory on the VM:
      vb.memory = "8192" # 開発用なので大きく取っておいても実害はない
    end
    config.vm.provision "shell", inline: <<-SHELL
      # すでに初期化が済んでいれば抜ける
      test -f /etc/bootstrapped && exitv
  
      # dockerproject.org を apt/sources/list.d へ入れる
      apt-get update
      apt-get install -y apt-transport-https ca-certificates
      apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
      echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" > /etc/apt/sources.list.d/docker.list
      echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" > /etc/apt/sources.list.d/docker.list
  
      # docker-engine を入れる
      apt-get update
      apt-get purge lxc-docker
      apt-cache policy docker-engine
      apt-get install -y docker-engine
  
      # vagrant ユーザーを docker グループに入れて docker サーバーを起動
      gpasswd -a vagrant docker
      service docker restart
  
      # docker-compose を入れる
      curl -s -S -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
      chmod +x /usr/local/bin/docker-compose
  
      # 初期化済みフラグを立てる
      date > /etc/bootstrapped
  
    SHELL
 $ vagrant up

実働時よりもプロビジョニングでメモリを馬鹿食いする docker 
イメージもあるようなので、Vagrant のメモリ設定は大きめにしておく。
この設定は最大値を決める物なので、大きな値を設定してあっても実際に使わなければ他を圧迫したりはしない。

box はパスフレーズでの認証が不可に設定されるので、
自身の ssh クライアントで接続するには設定で
キーファイルを指定してやる必要がある。

** box へ Windows 用ターミナルソフト PuTTY で繋ぎに行くには [#r06510da]

 LANG:console
 $ vagrant ssh-config

と打つと、IdentityFile として private_key のありかが分かるので、
原理的にはこれを PuTTY の [接続]-[SSH]-[認証] の 
[認証のためのプライベートキーファイル] に指定してから繋ぎ、
ユーザー名に vagrant を入れれば良いのだけれど、

putty は OpenSSH のキーファイルを直接扱えないため、
同梱の PuTTYgen でキーファイルを .ppk ファイルに変換してやる必要がある。

[load an existing private key file] から load して、
[Save the generated key] から Save private key で
.ppk ファイルとして保存する。load 時にファイルタイプを
PuTTY Private Keyfiles (*.ppk) から、All Files (*.*) 
に変更しないと正しく読み込めない?

保存した .ppk ファイルを PuTTY の接続情報に指定する。

** コマンドラインの ssh クライアントで繋ぐには [#s9a61f38]

 LANG:console
 $ vagrant ssh-config --host 192.168.33.10 >> ~/.ssh/config

とすると、box 用の接続設定が ~/.ssh/config に追加される。

192.168.33.10 のところは box のアドレスを指定する。
mybox.example.com のようなドメイン名でも構わない。

box を作り直した場合などで ~/.ssh/config 
に古い設定が残っている場合には手動で取り除く。


* メモ:docker をデフォルトで使うと CPU を食い潰す? [#a51c3865]

https://www.wantedly.com/companies/kurashicom/post_articles/102572 より
>
デフォルトの設定だとCPU使用率が急激に上がった
>
これは僕達のチーム固有の問題だと思いますが、Docker Composeで複数コンテナを立ち上げたときに、DockerのプロセスだけでCPU使用率が100%を超えて、Macが熱を持ってシュンシュン鳴り始めました。
>
キューをウォッチしているコンテナが最もCPUを使っていたのですが、docker-compose.yml の volumes ブロックに cached オプションを付けることで解消されました。
>
このオプションをつけると、ホストでのファイル変更がコンテナに反映されるまでに若干ディレイが発生するみたいですが、今のところ特に問題は起きていません。
>
  参照:[[Performance tuning for volume mounts>https://docs.docker.com/docker-for-mac/osxfs-caching/#cached]]


* library/ruby イメージ の雰囲気を確かめる [#n6f054ca]

サイズは 55.5MB だった。

 LANG:console
 $ docker run --rm -it ruby:alpine         # 何も指定しないと irb が立ち上がる
  irb(main):001:0>^D
 $ docker run --rm -it ruby:alpine bash    # bash は入っていない
  docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"bash\": executable file not found in $PATH": unknown.
 $ docker run --rm -it ruby:alpine sh      # sh は入ってる
 /# ls -l bin/sh                           # 正体は busybox
  lrwxrwxrwx    1 root     root            12 Jan  9 19:37 bin/sh -> /bin/busybox
 /# ruby --version
  ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-musl]
 /# gem --version
  2.7.6
 /# bundle --version
  Bundler version 1.16.1
 /# gem install rails                      # 始めは gcc 等が入っていないのでコケる
  ...
  Fetching: nokogiri-1.8.2.gem (100%)
  Building native extensions. This could take a while...
  ERROR:  Error installing rails:
          ERROR: Failed to build gem native extension.
  ...
 /# apk add -U --no-cache bash git alpine-sdk nodejs tzdata  # いろいろ入れる
 /# gem install rails                      # これで入った
  ...
  Successfully installed rails-5.2.0
  30 gems installed
 /# rails new myapp
  ...
  Installing sqlite3 1.3.13 with native extensions
  Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
  ...
 /# apk add sqlite-dev
 /# rails new myapp                        # うまく行った
 /# cd myapp
 /myapp# rails s &                         # サーバーを起動
  => Booting Puma
  => Rails 5.2.0 application starting in development
  => Run `rails server -h` for more startup options
  Puma starting in single mode...
  * Version 3.11.4 (ruby 2.5.1-p57), codename: Love Song
  * Min threads: 5, max threads: 5
  * Environment: development
  * Listening on tcp://0.0.0.0:3000
  Use Ctrl-C to stop
 /myapp# wget -O- localhost:3000 | head -4 # 正しく読める
  Connecting to localhost:3000 (127.0.0.1:3000)
  Started GET "/" for 127.0.0.1 at 2018-05-09 20:02:41 +0000
  Processing by Rails::WelcomeController#index as HTML
    Rendering /usr/local/bundle/gems/railties-5.2.0/lib/rails/templates/rails/welcome/index.html.erb
    Rendered /usr/local/bundle/gems/railties-5.2.0/lib/rails/templates/rails/welcome/index.html.erb (3.0ms)
  Completed 200 OK in 6ms (Views: 4.5ms | ActiveRecord: 0.0ms)
  
  <!DOCTYPE html>
  <html>
  <head>
    <title>Ruby on Rails</title>
 /myapp# cat Gemfile                       # 標準の Gemfile
  source 'https://rubygems.org'
  git_source(:github) { |repo| "https://github.com/#{repo}.git" }
  
  ruby '2.5.1'
  
  # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
  gem 'rails', '~> 5.2.0'
  # Use sqlite3 as the database for Active Record
  gem 'sqlite3'
  # Use Puma as the app server
  gem 'puma', '~> 3.11'
  # Use SCSS for stylesheets
  gem 'sass-rails', '~> 5.0'
  # Use Uglifier as compressor for JavaScript assets
  gem 'uglifier', '>= 1.3.0'
  # See https://github.com/rails/execjs#readme for more supported runtimes
  # gem 'mini_racer', platforms: :ruby
  
  # Use CoffeeScript for .coffee assets and views
  gem 'coffee-rails', '~> 4.2'
  # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
  gem 'turbolinks', '~> 5'
  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
  gem 'jbuilder', '~> 2.5'
  # Use Redis adapter to run Action Cable in production
  # gem 'redis', '~> 4.0'
  # Use ActiveModel has_secure_password
  # gem 'bcrypt', '~> 3.1.7'
  
  # Use ActiveStorage variant
  # gem 'mini_magick', '~> 4.8'
  
  # Use Capistrano for deployment
  # gem 'capistrano-rails', group: :development
  
  # Reduces boot times through caching; required in config/boot.rb
  gem 'bootsnap', '>= 1.1.0', require: false
  
  group :development, :test do
    # Call 'byebug' anywhere in the code to stop execution and get a debugger console
    gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  end
  
  group :development do
    # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
    gem 'web-console', '>= 3.3.0'
    gem 'listen', '>= 3.0.5', '< 3.2'
    # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
    gem 'spring'
    gem 'spring-watcher-listen', '~> 2.0.0'
  end
  
  group :test do
    # Adds support for Capybara system testing and selenium driver
    gem 'capybara', '>= 2.15', '< 4.0'
    gem 'selenium-webdriver'
    # Easy installation and use of chromedriver to run system tests with Chrome
    gem 'chromedriver-helper'
  end
  
  # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

* 方針 [#me5e176b]

rails サーバー と postgresql サーバーとを別々に建てて接続する

postgres と mysql のイメージサイズは10倍くらい違う。~
どちらでもいいなら postgres を使いたくなる感じ。

 postgres                 alpine              24a77bfbb9ee        13 hours ago        39.5MB
 mysql                    latest              a8a59477268d        5 days ago          445MB

* postgres イメージの使い方 [#u42d179e]

以下まだ考え中、とりあえずメモとして保存。後で編集する。

postgres 側の起動:
 LANG:console
 $ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres:alpine

 LANG:console
This image includes EXPOSE 5432 (the postgres port), so standard container linking will make it automatically available to the linked containers. The default postgres user and database are created in the entrypoint with initdb.

    The postgres database is a default database meant for use by users, utilities and third party applications.

    postgresql.org/docs

connect to it from an application

 LANG:console
 $ docker run --name some-app --link some-postgres:postgres -d application-that-uses-postgres

* development [#ze449dce]

まだ考え中

 $ docker run -it -v /path_to_app_in_host:/rails_proj -p 13000:3000 myimage/ruby_with_docker /bin/sh
 /# cd /rails_proj
 /# bundle install
 /# rails db:create
 /# rails db:migrate
 /# rails s

* Dockerfile の作りかけ [#nf20b46f]

 FROM ruby:alpine
 
 RUN \
     # いろいろ入れる
     apk add -U --no-cache bash git alpine-sdk nodejs tzdata  && \
     # bundler 入れる
     gem install bundler && \
     #
     cd 

Gemfile
 LANG:ruby
 source 'https://rubygems.org'
 git_source(:github) { |repo| "https://github.com/#{repo}.git" }
 
 ruby '2.5.1'
 
 # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
 gem 'rails', '~> 5.2.0'
 # Use sqlite3 as the database for Active Record
 gem 'sqlite3'
 # Use Puma as the app server
 gem 'puma', '~> 3.11'
 # Use SCSS for stylesheets
 gem 'sass-rails', '~> 5.0'
 # Use Uglifier as compressor for JavaScript assets
 gem 'uglifier', '>= 1.3.0'
 # See https://github.com/rails/execjs#readme for more supported runtimes
 gem 'mini_racer', platforms: :ruby
 
 # Use CoffeeScript for .coffee assets and views
 gem 'coffee-rails', '~> 4.2'
 # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
 ## gem 'turbolinks', '~> 5'
 # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
 gem 'jbuilder', '~> 2.5'
 # Use Redis adapter to run Action Cable in production
 # gem 'redis', '~> 4.0'
 # Use ActiveModel has_secure_password
 gem 'bcrypt', '~> 3.1.7'
 
 # Use ActiveStorage variant
 # gem 'mini_magick', '~> 4.8'
 
 # Use Capistrano for deployment
 # gem 'capistrano-rails', group: :development
 
 # Reduces boot times through caching; required in config/boot.rb
 gem 'bootsnap', '>= 1.1.0', require: false
 
 group :development, :test do
   # Call 'byebug' anywhere in the code to stop execution and get a debugger console
   gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
 end
 
 group :development do
   # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
   gem 'web-console', '>= 3.3.0'
   gem 'listen', '>= 3.0.5', '< 3.2'
   # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
   gem 'spring'
   gem 'spring-watcher-listen', '~> 2.0.0'
 end
 
 group :test do
   # Adds support for Capybara system testing and selenium driver
   gem 'capybara', '>= 2.15', '< 4.0'
   gem 'selenium-webdriver'
   # Easy installation and use of chromedriver to run system tests with Chrome
   gem 'chromedriver-helper'
 
   gem 'rspec-rails'
   gem 'rails-controller-testing'
 end
 
 # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
 # gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
 
 # riot support
 gem 'riot_js-rails', github: 'bjarosze/riot_js-rails', ref: 'f6328dbabcdf69400e1cea70485973ae1c926b94'
 gem 'slim-rails'
 
 # frontend libraries
 gem 'jquery-rails'
 gem 'jquery-validation-rails'
 gem 'materialize-sass'
 
 # easy way to check emails sent by rails app
 group :development do
   gem "letter_opener"
   gem "letter_opener_web"
 end


Counter: 4726 (from 2010/06/03), today: 2, yesterday: 0