LoginSignup
1
1

More than 3 years have passed since last update.

Docker でRails6とPostgreSQLの環境構築

Last updated at Posted at 2020-10-18

Dockerで Rails6 + PostgreSQLで環境構築

自分の備忘録も兼ねてDockerでRails6 + PostgreSQLで環境構築のやり方を記事にして残しておきます。
今回はアプリ名をshopping_appとして作成していきます。

作成する環境の各バージョン

  • Ruby 2.7.2
  • Rails 6.0.3
  • PostgreSQL 13.0

ディレクトリ構造

 .
 ├── Dockerfile
 ├── docker-compose.yml
 └── shopping_app
     ├── Gemfile
     └── Gemfile.lock

Dockerfileの作成

まずはDockerfileの作成をします。

FROM ruby:2.7.2
ENV LANG C.UTF-8


RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
    && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list

RUN apt-get update -qq && \
    apt-get install -y build-essential \
            libpq-dev \
            nodejs \
            postgresql-client yarn

RUN mkdir /app
RUN mkdir /app/shopping_app

ENV APP_ROOT /app/shopping_app
WORKDIR $APP_ROOT

ADD ./shopping_app/Gemfile $APP_ROOT/Gemfile
ADD ./shopping_app/Gemfile.lock $APP_ROOT/Gemfile.lock

RUN bundle install

ADD . $APP_ROOT

docker-compose.ymlの作成

docker-compose.ymlを作成します。今回はportを1501に設定しています。

version: '3'
services:
  postgres:
    image: postgres
    ports:
      - "3306:3306"
    volumes:
      - ./tmp/db:/var/lib/postgresql/data #MacOSの場合
    environment:
      POSTGRES_USER: 'admin'
      POSTGRES_PASSWORD: 'admin-pass'
    restart: always
  app:
    build: .
    image: rails
    container_name: 'app'
    command: bundle exec rails s -p 1501 -b '0.0.0.0'
    ports:
      - "1501:1501"
    environment:
      VIRTUAL_PORT: 80
    volumes:
      - ./shopping_app:/app/shopping_app
    depends_on:
      - postgres
    restart: always

volumes:
  app_postgre:
    external: true

Gemfileの作成

source 'https://rubygems.org'
gem 'rails', '6.0.3'

Gemfile.lockは空のままでいいです。

コンテナをBuildしてappを作成

$ docker-compose run app rails new . --force --database=postgresql --skip-bundle

webpackerのinstall

docker-compose run app rails webpacker:install

Databaseの作成と設定

作成されたappのdatabase.ymlを設定します。

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  # 以下を記述
  user: admin
  password: admin-pass
  host: postgres

imageをbuild

docker-compose build

Databaseの作成

docker-compose run app rails db:create

以上で構築完了です。
以下のコマンドでアプリを起動して

docker-compose up

http://localhost:1501/
にアクセスすれば以下の画面に表示されます。

スクリーンショット 2020-10-18 20.16.20.png

以上です。

1
1
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
1
1