LoginSignup
4
1

More than 1 year has passed since last update.

Docker上のRailsでbin/rails tailwindcss:watchが効かない場合の対処方法

Posted at

Docker上のRails6アプリにGemのtailwindcss-railsでTailwind CSSを導入し、bin/devで動かしたところ、コンテナ起動時にしかapp/assets/builds/tailwind.cssが更新されませんでした。
コードを変更したときはbin/rails tailwindcss:buildを実行しなければなりませんでした。

実行環境

  • Windows 10 Home
  • WSL 2
  • Ubuntu 20.04 LTS
  • Docker 20.10.11
  • docker-compose 1.29.2
  • Rails 6.1.4.1
  • Ruby 2.7.4

RubyのDockerイメージにはruby:2.7.4-alpineを使用
ソースコードはWindowsのCドライブ下
Gemのtailwindcss-railsでTailwind CSSを導入

bin/rails tailwindcss:installbin/devProcfile.devapp/assets/stylesheets/application.tailwind.cssなどを作成
Railsのコンテナはbin/devを実行

docker-compose.yml
services:
  app:
    command: bash -c "rm -f tmp/pids/server.pid && ./bin/dev"
    .
    .
    .
Procfile.dev
web: bin/rails server -p 3000 -b 0.0.0.0
css: bin/rails tailwindcss:watch
bin/dev
#!/usr/bin/env bash

if ! command -v foreman &> /dev/null
then
  echo "Installing foreman..."
  gem install foreman
fi

foreman start -f Procfile.dev

原因

WSL2の問題かも

対処方法

Railsコンテナのコマンドにはbin/devではなくbin/rails sを使用し、別のコンテナでGuardがbin/rails tailwindcss:buildを実行するようにする。

docker-compose.yml
services:
  app:
    command: bash -c "rm -f tmp/pids/server.pid && ./bin/rails s -p 3000 -b '0.0.0.0'"
    .
    .
    .

  tailwindcss:
    command: bundle exec guard --force-polling
    tty: true
    .
    .
    .

Guardを動かすコンテナのオプションにはtty: true、コマンドには--force-pollingが必要

Gemfile
.
.
.
group :development do
  .
  .
  .
  gem 'guard'
  gem 'guard-process'
end
.
.
.
Guardfile
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

## Uncomment and set this to only include directories you want to watch
directories(%w[app config].select { |d| Dir.exist?(d) ? d : UI.warning("Directory #{d} does not exist") })

## Note: if you are using the `directories` clause above and you are not
## watching the project directory ('.'), then you will want to move
## the Guardfile to a watched dir and symlink it back, e.g.
#
#  $ mkdir config
#  $ mv Guardfile config/
#  $ ln -s config/Guardfile .
#
# and, you'll have to watch "config/Guardfile" instead of "Guardfile"

guard 'process', name: 'BuildingTailwindCSS', command: 'bin/rails tailwindcss:build', stop_signal: 'KILL' do
  watch(%r{app/helpers/.+\.rb})
  watch(%r{app/javascript/.+\.js})
  watch(%r{app/views/.+\.(erb|haml|html|slim)})
  watch('app/assets/stylesheets/application.tailwind.css')
  watch('config/tailwind.config.js')
end

watchの引数はGuardで監視したいファイルのパス
stop_signal:はGuardがコマンドを実行している最中にコードを変更すると例外が発生しログが大変なことになるので必要

ターミナル
.
.
.
tailwindcss_1  | rails aborted!
tailwindcss_1  | SignalException: SIGTERM
.
.
.
4
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
4
1