初心者インフラエンジニアが困ったときに試行錯誤するブログ

インフラエンジニアが,開発の勉強をするときのログを残します

DockerでRailsを動かす その1

実現したいこと

Dockerの導入に伴い,RailsプロジェクトをDocker上で動かします. すでに,Dockerのインストールは行っており,環境はMacで行います.

やったこと

以下の構成でやってみます

Gemfile

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.3.3'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.0'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# 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 r
untimes
# 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'

docker-compose.yml

version: '3'

services:
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - ./app:/app
    ports:
      - 3000:3000
    # environment:
    # DATABASE_HOST: host.docker.internal

Dockerfile

FROM ruby:2.3.3
ENV LANG C.UTF-8

# apt-utils is not installed対策
ENV DEBIAN_FRONTEND noninteractive
ENV DEBCONF_NOWARNINGS yes

RUN apt-get update && apt-get install -y build-essential libpq-dev postgresql-client qt5-default qt5-qmake libqt5webkit5-dev
RUN gem install capybara-webkit --no-ri --no-rdoc
RUN gem install rails

RUN mkdir /app
WORKDIR /app
COPY ./app /app

# Gitの認証情報
COPY ./git-credential-git-token /usr/local/bin
RUN git config --global credential.helper git-token

ADD /app/Gemfile /app/Gemfile
ADD /app/Gemfile.lock /app/Gemfile.lock

RUN gem install bundler
RUN bundle install

EXPOSE 3000
CMD bundle exec rails s

$docker-compose up -dしてみる.

WARNING: Image for service web was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build.
Creating rails-gem-env-test_web_1 ... done

あれ?コンテナが立ち上がらない... なんでだろう.Rails sしているのに

もっと簡単な構成でやってみる

Dockerfile

FROM ruby:2.3.7
ENV LANG C.UTF-8

RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

ENV APP_ROOT /usr/src/app
WORKDIR $APP_ROOT

ADD app/Gemfile $APP_ROOT
ADD app/Gemfile.lock $APP_ROOT

RUN bundle install

ADD app $APP_ROOT
                       

docker-compose.yml

version: '3'
services:
  web:
    container_name: rails-sample-app
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - pg-db:/usr/src/app
    ports:
      - "3000:3000"
    #depends on では,pg-dbを起動させてからwebを起動する.という順番を設定できる
    depends_on:
      - sample-db
    env_file: .env.dev
volumes:
  sample-db:
    driver: local
~                 

$ bundle installしてから,$ docker-compose up -d する $ rails newしておく

database.yml

default:
  adapter: postgresql
  encoding: unicode
  pool: 5
  # 以下の3つを追加
  username: <user-name>
  password: <password>
  # RailsサーバとPostgreSQLサーバが同じ場合
  host: localhost
development:
  <<: *default
  database: sample-db
test:
  <<: *default
  database: sample-db

bundle installがうまくいかないので,さらにGemfileを書き換え

Gemfile

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.3.7'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.0'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# 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]

$ rake db:migrateしたら怒られた.

rake aborted!
Psych::BadAlias: Cannot load `Rails.application.database_configuration`:
Unknown alias: default

&defaultがなかったみたい.修正

database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5
  # 以下の3つを追加
  username: pg-taka
  password: pg-taka
  # RailsサーバとPostgreSQLサーバが同じ場合
  host: localhost
development:
  <<: *default
  database: sample-db
test:
  <<: *default
  database: sample-db

$ rake db migrate 成功した.

$ rake db:setup実行

いけるかなとおもいきや...

Caused by:
PG::InsufficientPrivilege: ERROR:  permission denied to create database

これはなんだ.権限ないのか.

権限を確認する

$ psql -U <権限のあるユーザー名> -d <database>
# \du

 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 <今回のUSER>   | Superuser                                                  | {}
 <superuser>  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
# ALTER ROLE "今回のUSER" WITH SUPERUSER;

権限がついた. 一通りの権限を渡して,再チャレンジ

$ rake db:setup
Database 'sample-db' already exists
Database 'sample-db' already exists
-- enable_extension("plpgsql")
   -> 0.0356s
-- enable_extension("plpgsql")
   -> 0.0224s

通った...!!!

最後に,$docker-compose up -dしようと思ったが失敗したので,再度'docker-compose.yml'を書き換え

docker-compose.yml

version: '3'
services:
  web:
    container_name: rails-sample-app
    build: .
    command: bundle exec railss -p 3000 -b '0.0.0.0'
    volumes:
      - ./app:/app
    ports:
      - "3000:3000"
    environment:
      DATABASE_HOST: host.docker.internal

コンテナは一応立ち上がったが,localhost:3000につなぐと

return PG::Connection.new( *args )エラーが...

Docker導入までの道のりは遠い.

続く...

ktaka.hatenablog.com

参考

以下の記事を参考にさせていただきました.

インストールからRails-PostgreSQL環境を整える - Qiita

MacOSX YosemiteでRails4.xを動かして、Postgresと繋げるときのメモ - Qiita

本記事について

本記事は,学習を目的に書かれています. 間違い,改良案などございましたら,コメントしていただけると幸いです. 基本的に編集途中ですので,何を書いてほしいかもコメントいただけると, その情報を中心に追記します.