LoginSignup
0
1

More than 3 years have passed since last update.

RailsをDockerを使って始める

Last updated at Posted at 2020-03-26

これ以降,app_nameは任意のプロジェクトの名前に置き換えること.

最初の準備

app_name/の下に以下の5つのファイルを用意する
- Gemfile
- Gemfile.lock
- entrypoint.sh
- Dockerfile
- docker-compose.yml

Gemfile
source 'https://rubygems.org'

ruby '2.5.1'

gem 'rails', '~> 5.2.3'
Gemfile.lock
(空でいい)
entrypoint.sh
#!/bin/bash

set -e

rm -f ./tmp/pids/server.pid

exec "$@"
Dockerfile
FROM ruby:2.5.1
ENV LANG C.UTF-8

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

ENV APP_DIR /app_name
RUN mkdir -p APP_DIR
WORKDIR $APP_DIR

COPY Gemfile $APP_DIR
COPY Gemfile.lock $APP_DIR

RUN gem install bundler && bundle install
COPY . $APP_DIR

COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["bundle", "exec", "rails", "s", "-p", "3000", "-b", "0.0.0.0"]
docker-compose.yml
version: '3'
services:
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: password
    ports:
      - "3306:3306"
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    volumes:
      - sql-data:/var/lib/mysql
  web:
    build: .
    tty: true
    stdin_open: true
    ports:
      - "3000:3000"
    volumes:
      - .:/app_name
      - gem-data:/usr/local/bundle
    depends_on:
      - db
volumes:
  gem-data:
  sql-data:

プロジェクトを起動する

app_name/の下で以下の作業をする

1, プロジェクトを作成:

$ docker-compose run web rails new . --force --database=mysql --skip-bundle

2, passwordの設定:

$ grep -l 'password:' config/database.yml | xargs sed -i.bak -e 's/password:/password: password/g'

3, host名の置き換え:

$ grep -l 'host: localhost' config/database.yml | xargs sed -i.bak -e 's/host: localhost/host: db/g'

4, コンテナをビルド:

$ docker-compose build

5, コンテナ内のbundle install:

$ docker-compose run web bundle install  

6, DBを作成

docker-compose run web rails db:create

7, コンテナの起動:

$ docker-compose up

localhost:3000でアクセス

Screen Shot 2020-03-26 at 21.19.57.png

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