LoginSignup
2
2

docker-compose build はやりたくない rails

Last updated at Posted at 2023-12-31

はじめに

今回、ruby on rails を勉強のためdocker上で環境構築して学習しているのですが、

章が変わるごとにgemを追加して、docker-compose buildで2時間近くかかって、全然学習にならなかったので改善できないか調べて取り組んでみました

結論

docker-compose のvolumesを使えばできた。

 version: '3'
 services:
   web:
    volumes:
      - .:/app
+     - bundle:/usr/local/bundle
 volumes:
+  bundle:

概要

  • PC : M1 Macbook
    m1 Macbookは通常と違う点が多いのでご注意を。

ファイル構造

現在のディレクトリ

rails
 ├─ Dockerfile
 ├─ Gemfile
 └─ docker-compose.yml

  • Dockerfile
  • Gemfile
  • docker-compose.yml
Dockerfile
FROM ruby:3.2.2-alpine
RUN apk update
RUN apk add git g++ make mysql-dev tzdata build-base python3
WORKDIR /app
COPY Gemfile .
RUN bundle config set force_ruby_platform true
RUN bundle install
Gemfile
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.2.2"

gem "rails", "~> 7.0.8"
docker-compose.yml
version: '3'
services:
  web:
    build: .
    command: sh -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/app
    ports:
      - 3000:3000
    depends_on:
      - db
    environment:
      MYSQL_ROOT_PASSWORD: 12345
    links:
      - db
    tty: true
    stdin_open: true
  db:
    image: mysql:8.0
    volumes:
      - db-volume:/var/lib/mysql
volumes:
  db-volume:

rails app構築

qiitaで "docker rails 構築" と調べたらわかりやすい方がたくさんいるので簡略化します

  1. rails new . --force --database=mysql --skip-bundle
  2. docker-compose build
  3. docker-compose up -d
  4. docker-compose run web rails db:create
  5. http://localhost:3000/ 

本題

imageをもとにコンテナを作っているため、run web bundle installだとコンテナをdownしたらgemは使えなくなります。

docker compose のvolumesを使ってbundlerのデータをマウントして永続化することによって解決できます。

 version: '3'
 services:
   web:
     build: .
     command: sh -c "rm -f tmp/pids/server.pid && bundle exec 
rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/app
+     - bundle:/usr/local/bundle
     ports:
       - 3000:3000
     depends_on:
       - db
     environment:
       MYSQL_ROOT_PASSWORD: 12345
     links:
       - db
     tty: true
     stdin_open: true
   db:
     image: mysql:8.0
     volumes:
       - db-volume:/var/lib/mysql
 volumes:
+  bundle:
   db-volume:

その後

$ docker-compose run --rm web bundle install
$ docker-compose up

それでもエラーが出たり反映されなかったら、

$ docker-compose run web ash
/app# bundle install  
/app# exit
$ docker-compose up

私は前者ではエラーが出ました。なぜか後者のshellに入って実行すると上手くいきました。(なぜ)

ここで気をつけたいことが,linux-alpineを使っていますので、bashではなくashを使っています。
使っている環境によって使い分けてください。

alpineのshellはash

終わりに

まだまだ勉強しなくてはならないことがたくさんありますねぇ

参考文献

docker-composeでRailsのGemを更新する時、docker buildするのを回避したい
Docker Composeのvolumesについてわかったことをまとめる
Docker Composeのvolumesを使ってもっと効率的に

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