LoginSignup
11
9

More than 3 years have passed since last update.

DockerでrailsでpostgreSQL

Posted at

手順(2020/6/5時点) ※10分レシピ

Docker公式のやり方でやってもエラーが出ちゃう・・・
そのために作成しました。
自分の備忘録目的ですが、どうぞお役立て下さい。

1:必要ファイル準備

Dockerfile
FROM ruby:2.6.5   #希望のバージョンでOK
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000   #localhost:3000で接続する設定

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]
Gemfile
source 'https://rubygems.org'
gem 'rails', '~>5.2.4'   #希望のバージョンでOK。
# 上記以外の主要gemは、この後自動で書き込まれる。
Gemfile.lock
# 空ファイル
entrypoint.sh
#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"
Gemfile.lock
version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:  #この行がDocker公式に載ってない。
      - POSTGRES_PASSWORD=password    #この行がDocker公式に載ってない。
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

2:プロジェクトをビルドする

ターミナル
$ docker-compose run web rails new . --force --no-deps --database=postgresql

※4分程度かかります。

2:プロジェクトをビルドする

ターミナル
$ docker-compose run web rails new . --force --no-deps --database=postgresql

※4分程度かかります。

3:権限変更

ターミナル
$ sudo chown -R $USER:$USER .

※LinuxでDockerを実行している場合、作成rails newされたファイルはrootが所有します。これは、コンテナーがrootユーザーとして実行されるために発生します。この場合は、新しいファイルの所有権を変更してください。

4:Gemfile更新のための再ビルド

ターミナル
$ docker-compose build

※1分程度かかります。コンテナのGemfile更新のため。

5:データベースの設定

config/database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password: password  #この行がDocker公式に載ってない。
  pool: 5

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

6:コンテナの更新のための再ビルド

ターミナル
$ docker-compose build

※1分程度かかります。コンテナのdatabase.ymlの更新のため。

7:コンテナの起動

ターミナル
$ docker-compose up

※データベース未作成の為、localhost接続でエラーが出る。

8:コンテナのデータベースの作成

ターミナル
$ docker-compose run web rails db:create

※ローカルから設定可能。

9:設定完了

images.jpeg
※localhost:3000で接続
※ここからアプリ開発開始〜!!

備考:参考動画・サイト

Masara Oshimaさん
※youtubeで15分程度の簡潔な動画です。助かりました!

Farstepさん
※Dockerfileやdocker-compose.ymlの記述説明もあり。わかりやすい!

Docker公式サイト
※一部修正が必要だった為、上記1〜8まで実行すれば開発環境構築まで可能です。

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9