LoginSignup
1
1

More than 3 years have passed since last update.

rails+postgresqlのDocker構築を公式通りやったけどうまく行かなかったので一部修正した

Last updated at Posted at 2020-11-01

前提

macOS Catalina
Docker for Mac 2.3.0.5

公式

Quickstart: Compose and Rails

コード

Dockerfile

公式通りの記述でやっていったらいきなり諸々エラーになった為、ググって足りないもの追加しました。
他、公式のrubyはバージョン2.5ですが、2020/11/1最新の2.7.2にしました

公式

FROM ruby:2.5
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

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

FROM ruby:2.7.2
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
# 以下同じ

Gemfile

公式ではrailsのバージョンは5ですが、2020/11/1最新の6にしました

公式

source 'https://rubygems.org'
gem 'rails', '~>5'

source 'https://rubygems.org'
gem 'rails', '~> 6.0.3', '>= 6.0.3.4'

docker-compose.yml

公式や他の記事通りにしてもなぜかDBが永続化されずに心折れかけましたが、こちらの方法で解決しました。
https://github.com/docker/compose/issues/5012#issuecomment-316518185

(公式)docker-compose.yml
version: "3"
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
  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

docker-compose.yml
version: '3'
services: 
  db:
    image: postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
      PGDATA: /var/postgres_data # 追加
    volumes: 
      - ./tmp/db:/var/postgres_data # 修正
    ports:
      - "5432:5432"
  web: # 同じ

※フロントをReact等のportが3000のもので作成する場合は、競合を避ける為
ports: "3001:3000"
にしてrailsサーバーに接続する時は3001を指定します。
(or フロント側のportを変える)

手順

基本的な手順はこちらの動画がわかりやすかったので参考にしてください。
【rails環境構築】docker + rails + mysql で環境構築(初心者でも30分で完了!)
※こちらの動画はpostgresqlではなくmysqlでrails5、ruby2.5です

DB接続

※コンテナ起動していないとつながりません
スクリーンショット 2020-11-03 9.55.57.png

Name 自由
User docker-compose.ymlのPOSTGRES_USERに記述されているものを設定
Password docker-compose.ymlのPOSTGRES_PASSWORDに記述されているものを設定
Database myapp/config/database.yml のdevelopment:databaseに記述されているものを設定

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