LoginSignup
2
2

More than 1 year has passed since last update.

[軽量化] マルチステージビルドによるrails環境のdocker化

Last updated at Posted at 2023-02-10

rails環境のdocker化

rails環境のdocker化についてまとめます。
dockerの軽量化のためにマルチステージビルドで環境を構築します。

各種バージョン

  • rails 6.0.6.1
  • ruby 3.0.2
  • node 15.0.1
  • postgresql 14.6-alpine

Dockerfileの作成

リポジトリに dockerfile を作成。apt-get install を使用せずに下記のようにマルチステージビルドでnodeをインストールすることで、dockerの軽量化およびbuildの時間短縮が期待できます。

FROM node:15.0.1
FROM ruby:3.0.2

COPY --from=node /opt/yarn-* /opt/yarn
COPY --from=node /usr/local/bin/node /usr/local/bin/
COPY --from=node /usr/local/lib/node_modules/ /usr/local/lib/node_modules/
RUN ln -fs /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
  && ln -fs /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npx \
  && ln -fs /opt/yarn/bin/yarn /usr/local/bin/yarn \
  && ln -fs /opt/yarn/bin/yarnpkg /usr/local/bin/yarnpkg
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev

RUN mkdir /repogitory_name
WORKDIR /repogitory_name
ADD Gemfile /repogitory_name/Gemfile
ADD Gemfile.lock /repogitory_name/Gemfile.lock
RUN bundle install
ADD package.json yarn.lock /repogitory_name/
RUN yarn install
ADD . /repogitory_name

docker-compose.ymlの作成

version: '3'
services:
  db:
    image: postgres:14.6-alpine
    environment:
      - POSTGRES_PASSWORD=password
  web:
    image: repogitory_name:latest
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/repogitory_name
    ports:
      - "3000:3000"
    depends_on:
      - db

database.ymlの編集

default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password: password
  pool: 5

development:
  <<: *default
  database: myproject_development

test:
  <<: *default
  database: myproject_test

起動方法

$ docker-compose build
$ docker-compose run web rake db:create db:migrate
$ docker-compose up

上記コマンドを実行後、localhost:3000 にアクセスできれば成功です🎉

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