15
16

More than 3 years have passed since last update.

Rails6 + PostgresのDocker開発環境を構築

Last updated at Posted at 2020-05-07

いろんな記事をみてコピペしてみたのですが、どれもうまくいきませんでした。
私がうまくいった方法を記録しておきます。

ファイルの準備

$ touch Dockerfile docker-compose.yml Gemfile Gemfile.lock
FROM ruby:2.7

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 nodejs postgresql-client yarn

RUN mkdir /app_name
ENV APP_ROOT /app_name
WORKDIR $APP_ROOT

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

RUN bundle install
ADD . $APP_ROOT
docker-compose.yml
version: "3"
services:
  db:
    image: postgres
    volumes:
      - psgl_data:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
    ports:
      - 5433:5432
  web:
    build:
      context: .
      dockerfile: Dockerfile
    command: /bin/sh -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    tty: true
    stdin_open: true
    depends_on:
      - db
    ports:
      - "3000:3000"
    volumes:
      - .:/app_name
volumes:
  psgl_data:
Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 6'

Gemfile.lockは空のままでOK

構築

$ docker-compose run web rails new . --force --no-deps --database=postgresql
$ docker-compose build

ビルドの間に、config/database.ymlを編集

config/database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: db
  username: root
  password: password

development:
  <<: *default
  database: app_name_development

test:
  <<: *default
  database: app_name_test

ビルドが終わったら以下のコマンドを叩く

$ docker-compose up
$ docker-compose exec web rails db:create

http://localhost:3000 にアクセスして、Yay! You’re on Rails!を確認

【おまけ】VSCode Remote Containerで開発

私は普段以下のような環境で作業をしています。ローカルにRubyやRailsを入れる必要無し!
VSCode Remote Containerが良い

15
16
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
15
16