LoginSignup
32
29

More than 3 years have passed since last update.

VSCodeでRailsプロジェクトをデバッグして、Dockerコンテナでもできるようにするまで。

Last updated at Posted at 2019-05-10

これからRailsを本格的に始めるなら、高性能なIDEを使いたいですよね?私もです。

RubyMineはいいらしいけど、高いし、重いし、自分お小遣いとMacBookAirでは不安ですよね?私もです。

VisualStudioCodeなら、無料だし、軽いし、Rubyのステップ実行とかもできるらしいですよ!

というわけでやってみました。

第一部 MacローカルでRails動かしてデバッグするまで

新規Railsプロジェクトを作る

プロジェクト用ディレクトリを作成し、VSCodeでこのディレクトリを新規ウィンドウで開き、NewTerminalを開く

$ pwd
/Users/[myHome]/Dev
$ mkdir debug_sample
$ cd debug_sample/

rbenvでRubyバージョンを指定しておく。(なぜかコマンドでやらなかった)

$ rbenv versions
* system (set by /Users/[myHome]/.rbenv/version)
  2.5.1
  2.6.1
$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin17]
$ touch .ruby-version
$ vim .ruby-version 
$ rbenv versions
  system
* 2.5.1 (set by /Users/[myHome]/Dev/debug_sample/.ruby-version)
  2.6.1
$ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
$ rails -v
Rails 5.2.3
$ bundler -v
Bundler version 2.0.1
$ gem -v
2.7.6

gemは何が入っているんだろう

$ gem list
... 

この環境にはruby-debug-ideは入っていない。

システムはきれいに保つため、この環境にのみgemを入れていく。

$ bundle init
Writing new Gemfile to /Users/[myHome]/Dev/debug_sample/Gemfile

出来たGemfileを編集(gem "rails"のコメントを外して、5.2系にする、6系にならないように)

# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem "rails", "~> 5.2"

パスを指定して bundle install する。

$ bundle install --path vendor/bundle

このオプションを付けることによって、プロジェクトのvendor/bundle以下にgemが格納されます。(一度オプションをつけてbundle installしたら、次回以降はオプションを付けなくてもvendor/bundle以下に格納されるようになります。.bundle/config に設定が残る)

Railsプロジェクトを生成する

$ bundle exec rails new . -B --skip-turbolinks --skip-test

. はカレントディレクトリの指定

-B はnewでbundle installをしない指定

gem をインストールする

$ bundle install

できたはずなので、起動してみる

$ bin/rails server

http://127.0.0.1:3000/ で確認。めでたし。

ちょっと画面を作る。

$ rails generate controller Welcome index

http://127.0.0.1:3000/welcome/index で確認。めでたし。

gitにコミットしておく。やりかたはVScodeでもなんでも

ローカルデバッグ

Gemfileに追加する

gem 'ruby-debug-ide'
gem 'debase'

bundle installする

$ bundle install

bootsnapを無効化する

config/boot.rb

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)

require 'bundler/setup' # Set up gems listed in the Gemfile.
# require 'bootsnap/setup' # Speed up boot time by caching expensive operations.

VS Codeでrdebug-ideの実行設定

虫マークからAdd Configrationして、RailsえらんでListen for rdebug-ideを選ぶと自動的にできる。nameだけ変えておく。

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Local Listen for rdebug-ide",
            "type": "Ruby",
            "request": "attach",
            "remoteHost": "127.0.0.1",
            "remotePort": "1234",
            "remoteWorkspaceRoot": "${workspaceRoot}"
        }
    ]
}

コントローラーに適当にデバッグ対象コードを書く

welcome_controller.rb

class WelcomeController < ApplicationController
  def index
    a = 1
    b = 3
    @c = a + b 
  end
end

コマンドラインでデバッガーを起動

$ bundle exec rdebug-ide --host 127.0.0.1 --port 1234 --dispatcher-port 26162 -- bin/rails server
Fast Debugger (ruby-debug-ide 0.6.1, debase 0.2.2, file filtering is supported) listens on 127.0.0.1:1234

この状態ではまだ、待機。VSCodeのデバッグコンソールの緑三角[Listen for rdebug-ide]を押すと、ステータスバーが赤くなって、コンソールにいかが表示される。

=> Booting Puma
=> Rails 5.2.3 application starting in development 
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.1 (ruby 2.5.1-p57), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

この状態で、 `http://127.0.0.1:3000/welcome/index にアクセスすると、ブレイクポイントでとまる。めでたし。

第二部 Dockerコンテナ内のRailsをデバッグする

いろいろな開発をするから、Macローカルじゃなくて、Dockerコンテナで開発したいですよね?私もです!できるらしいのでやってみました。

Docker-compose化

docker/rails/Dockerfile

FROM ruby:2.5.1
ENV LANG C.UTF-8

RUN apt-get update -qq && apt-get install -y build-essential nodejs

RUN gem install bundler -v 2.0.1
ENV BUNDLER_VERSION 2.0.1 
ENV APP_HOME /myapp
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME
ADD . $APP_HOME
EXPOSE 3000 1234 26162

docker-compose.yml

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/rails/Dockerfile
    command: bundle exec bin/rails server -p 3000 -b '0.0.0.0'
    ports:
      - 3000:3000
    volumes:
      - .:/myapp
    env_file:
      - ./docker/rails/rails.env
    environment:
      RAILS_ENV: development
    networks:
      - local_network
networks:
  local_network:
    driver: 'bridge'

ビルドする

$ docker-compose build --no-cache

bundle installする

$ docker-compose run --rm web bundle install

起動

$ docker-compose up -d

確認

http://127.0.0.1:3000/welcome/index

めでたし。

Docker-composeからのリモートデバッグ

デバッグ用のcomposeファイルを作る

docker-compose.debug.yml

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/rails/Dockerfile
    command: bundle exec rdebug-ide --host 0.0.0.0 --port 1234 --dispatcher-port 26162 -- bin/rails server -b 0.0.0.0
    ports:
      - 3000:3000
      - 1234:1234
      - 26162:26162
    volumes:
      - .:/myapp
      - bundle_cache:/usr/local/bundle
    env_file:
      - ./docker/rails/rails.env
    environment:
      RAILS_ENV: development
    networks:
      - local_network
networks:
  local_network:
    driver: 'bridge'
volumes:
  bundle_cache:
    driver: local

rdebug-ideを起動しているのと、ポートが開けてあるのがポイントです

デバッガーの設定にリモートデバッグを追加する

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [

        {
            "name": "Local Listen for rdebug-ide",
            "type": "Ruby",
            "request": "attach",
            "remoteHost": "127.0.0.1",
            "remotePort": "1234",
            "remoteWorkspaceRoot": "${workspaceRoot}"
        },
        {
            "name": "Docker Listen for rdebug-ide",
            "type": "Ruby",
            "request": "attach",
            "cwd": "${workspaceRoot}",
            "remoteHost": "0.0.0.0",
            "remotePort": "1234",
            "remoteWorkspaceRoot": "/myapp"
        },

    ]
}

remoteWorkspaceRootで、コンテナ内のアプリケーションRootの絶対パスを指定しているのがポイント。hostは0.0.0.0にしてあります、127.0.0.1とかでも動くかもしれない。

次に、デバッグ用のコンテナを起動

$ docker-compose -f docker-compose.debug.yml up -d
Creating debug_sample_web_1 ... done

$ docker-compose logs -f
Attaching to debug_sample_web_1
web_1  | Fast Debugger (ruby-debug-ide 0.6.1, debase 0.2.2, file filtering is supported) listens on 0.0.0.0:1234

この時点ではここまで。ログを表示させて、VSCodeのデバッガーのDocker用の設定で起動する。緑三角ボタン。するとステータスバーが赤くなってリッスン状態になる。

web_1  | => Booting Puma
web_1  | => Rails 5.2.3 application starting in development 
web_1  | => Run `rails server -h` for more startup options
web_1  | Puma starting in single mode...
web_1  | * Version 3.12.1 (ruby 2.5.1-p57), codename: Llamas in Pajamas
web_1  | * Min threads: 5, max threads: 5
web_1  | * Environment: development
web_1  | * Listening on tcp://0.0.0.0:3000
web_1  | Use Ctrl-C to stop

http://0.0.0.0:3000/welcome/index

で表示確認。ちゃんとブレイクポイントで止まる。

めでたし。

32
29
1

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
32
29