LoginSignup
0
0

More than 1 year has passed since last update.

Rails 環境構築 

Last updated at Posted at 2021-06-18

環境

  • OS:Ubuntu 20.04

現場で使える Ruby on Rails 5速習実践ガイド を使用して環境構築
51KHr6cffnL._SX258_BO1,204,203,200_.jpg

※まだ初学者でメモもかねて記録しているので見るに堪えない点などあるかと思いますがご容赦ください。

rbenvインストール

$ git clone https://github.com/rbenv/rbenv.git ~/.rbenv

rbenvはRubyのバージョンを簡単に切り替えてくれるツール。
RubyやRailsを使って開発を行う上で、複数のバージョンを使いたい&管理したい時などに便利。

パス設定と初期化処理

$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
$ echo 'eval "$(rbenv int -)"' >> ~/.bashrc

.bashrcの末尾に追記されていることを確認

$ vi ~/.bashrc

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv int -)"

sourceコマンドで.bashrcの内容を読み込む。

$ source ~/.bashrc

ruby-buildセットアップ

$ git clone https://github.com/rbenv/ruby-build.git "$(rbenv root)"/plugins/ruby-build

Rubyのインストールのために必要なパッケージインストール

$ sudo apt-get install autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm3 libgdbm-dev

※zlib1g-devがzliblg-devに見えるので要注意

うまくいったと思っていたが、うまくいってなかったらしい。(後で発覚)

インストール可能なRubyのバージョンを確認

$ rbenv install -l
2.6.7
2.7.3
3.0.1
jruby-9.2.19.0
mruby-3.0.0
rbx-5.0
truffleruby-21.1.0
truffleruby+graalvm-21.1.0

Only latest stable releases for each Ruby implementation are shown.
Use 'rbenv install --list-all / -L' to show all local versions.

rbenvを使ってRubyをインストールする。ここでは3.0.1を選択。

$ rbenv install 3.0.1
Downloading ruby-3.0.1.tar.gz...
-> https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.1.tar.gz
Installing ruby-3.0.1...

BUILD FAILED (Ubuntu 20.04 using ruby-build 20210611-1-g1b477ae)

Inspect or clean up the working tree at /tmp/ruby-build.20210619023003.2897.EkvasP
Results logged to /tmp/ruby-build.20210619023003.2897.log

Last 10 log lines:
checking target system type... x86_64-pc-linux-gnu
checking for gcc... no
checking for clang... no
checking for cc... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/tmp/ruby-build.20210619023003.2897.EkvasP/ruby-3.0.1':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details

うーん。。失敗。
Cコンパイラが入っていないというエラーらしい。

Cコンパイラインストール

$ sudo apt install gcc
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  binutils binutils-common binutils-x86-64-linux-gnu cpp cpp-9 gcc-9 gcc-9-base libasan5 libatomic1
  libbinutils libc-dev-bin libc6-dev libcc1-0 libcrypt-dev libctf-nobfd0 libctf0 libgcc-9-dev libgomp1
  libisl22 libitm1 liblsan0 libmpc3 libquadmath0 libtsan0 libubsan1 linux-libc-dev manpages-dev
Suggested packages:
  binutils-doc cpp-doc gcc-9-locales gcc-multilib make autoconf automake libtool flex bison gdb gcc-doc
  gcc-9-multilib gcc-9-doc glibc-doc
The following NEW packages will be installed:
  binutils binutils-common binutils-x86-64-linux-gnu cpp cpp-9 gcc gcc-9 gcc-9-base libasan5 libatomic1
  libbinutils libc-dev-bin libc6-dev libcc1-0 libcrypt-dev libctf-nobfd0 libctf0 libgcc-9-dev libgomp1
  libisl22 libitm1 liblsan0 libmpc3 libquadmath0 libtsan0 libubsan1 linux-libc-dev manpages-dev
0 upgraded, 28 newly installed, 0 to remove and 0 not upgraded.
Need to get 1116 kB/28.6 MB of archives.
After this operation, 123 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Ign:1 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 linux-libc-dev amd64 5.4.0-65.73
Err:1 http://security.ubuntu.com/ubuntu focal-updates/main amd64 linux-libc-dev amd64 5.4.0-65.73
  404  Not Found [IP: 91.189.88.152 80]
E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/main/l/linux/linux-libc-dev_5.4.0-65.73_amd64.deb  404  Not Found [IP: 91.189.88.152 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

なんか失敗する。
Rubyのビルドに必要なライブラリが不足していることが原因のよう。
Rubyのビルドに必要なライブラリとそのインストール方法がOSごとにまとめられているページ

先程実行したRubyのインストールのために必要なパッケージインストールをやり直す。
libreadline6-devをlibreadline-devに変更
Ubuntu 20.04はlibgdbm3ではなくlibgdbm6でないとだめらしい。

$ sudo apt update
$ sudo apt-get install autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm6 libgdbm-dev libdb-dev

Rubyのビルドに必要なライブラリをインストールした後、改めてCコンパイラインストール

$ sudo apt install gcc
Reading package lists... Done
Building dependency tree
Reading state information... Done
gcc is already the newest version (4:9.3.0-1ubuntu2).
gcc set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 95 not upgraded.

インストール成功!

rbenvを使ってRubyを改めてインストール

$ rbenv install 3.0.1
Downloading ruby-3.0.1.tar.gz...
-> https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.1.tar.gz
Installing ruby-3.0.1...
Installed ruby-3.0.1 to /home/[username]/.rbenv/versions/3.0.1

$ rbenv global 3.0.0

rubyのバージョン確認

$ ruby -v

Command 'ruby' not found, but can be installed with:

sudo apt install ruby

バージョンが出ないので取り合えず言われた通り「$ sudo apt install ruby」やってみる。

$ sudo apt install ruby

rubyのバージョン確認

$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-gnu]

バージョンが表示された。

新しいバージョンを使えるようにアップデート

$ gem update --system
Updating rubygems-update
Fetching rubygems-update-3.2.20.gem
ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /var/lib/gems/2.7.0 directory.

なんか失敗する。。

rbenvについて、下記コマンドでバージョンが一度は表示されていたのに、再度開いたらなぜか表示されなくなっていた。。
マジでなぞ。。。

$ rbenv -v

Command 'rbenv' not found, but can be installed with:

sudo apt install rbenv

再度、インストール

$ sudo apt install rbenv

バージョンが表示された。

$ rbenv -v
rbenv 1.1.1

エラーが出てた「gem update --system」を再度実行したら最後のパスが変わってる。。

$ gem update --system
Updating rubygems-update
ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /usr/local/bin directory.

このあたりの記事参考になりそう。
https://qiita.com/nishina555/items/63ebd4a508a09c481150
システムのrubyを利用しているため、権限不足でgemのインストールができない可能性が高いらしい。
システムのrubyではなく、rbenvでrubyを管理するように設定変更する。

この記事の通り、現状確認してみる。
/usr/binというシステムのパスを指しているらしい。

$ which gem
/usr/bin/gem

$ which ruby
/usr/bin/ruby

バージョン確認。上のrbenv -vと何が違うのだろうか。。

$ rbenv version
3.0.1 (set by /home/[username]/.rbenv/version)

3.0.1をglobalで利用するように変更

$ rbenv global 3.0.1

なんかうまくいかない。。

色々調べたところ、どうも原因はrbenvにパスが通ってないことのよう。
.bashrcに設定した記述ではうまくいかなかったようで。。

.bash_profileを以下のように変更したら以下のようにrbenvのパスを指すようになった。

$ vi .bash_profile
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

$ source ~/.bash_profile

$ which gem
/home/[username]/.rbenv/shims/gem

$ which ruby
/home/[username]/.rbenv/shims/ruby

今度はうまくいった!

$ gem update --system
Updating rubygems-update
Fetching rubygems-update-3.2.21.gem
Successfully installed rubygems-update-3.2.21
Parsing documentation for rubygems-update-3.2.21
Installing ri documentation for rubygems-update-3.2.21

Installing darkfish documentation for rubygems-update-3.2.21
Done installing documentation for rubygems-update after 103 seconds
Parsing documentation for rubygems-update-3.2.21
Done installing documentation for rubygems-update after 0 seconds
Installing RubyGems 3.2.21
  Successfully built RubyGem
  Name: bundler
  Version: 2.2.21
  File: bundler-2.2.21.gem
Bundler 2.2.21 installed
RubyGems 3.2.21 installed
Regenerating binstubs
Regenerating plugins
Parsing documentation for rubygems-3.2.21
Installing ri documentation for rubygems-3.2.21

# 3.2.21 / 2021-06-23

## Enhancements:

* Fix typo in OpenSSL detection. Pull request #4679 by osyoyu
* Add the most recent licenses from spdx.org. Pull request #4662 by nobu
* Simplify setup.rb code to allow installing rubygems from source on
  truffleruby 21.0 and 21.1. Pull request #4624 by deivid-rodriguez

## Bug fixes:

* Create credentials folder when setting API keys if not there yet. Pull
  request #4665 by deivid-rodriguez

# 3.2.20 / 2021-06-11

## Security fixes:

* Verify plaform before installing to avoid potential remote code
  execution. Pull request #4667 by sonalkr132

## Enhancements:

* Add better specification policy error description. Pull request #4658 by
  ceritium

# 3.2.19 / 2021-05-31

## Enhancements:

* Fix `gem help build` output format. Pull request #4613 by tnir

# 3.2.18 / 2021-05-25

## Enhancements:

* Don't leave temporary directory around when building extensions to
  improve build reproducibility. Pull request #4610 by baloo

# 3.2.17 / 2021-05-05

## Enhancements:

* Only print month & year in deprecation messages. Pull request #3085 by
  Schwad
* Make deprecate method support ruby3's keyword arguments. Pull request
  #4558 by mame
* Update the default bindir on macOS. Pull request #4524 by nobu
* Prefer File.open instead of Kernel#open. Pull request #4529 by mame

## Documentation:

* Fix usage messages to reflect the current POSIX-compatible behaviour.
  Pull request #4551 by graywolf-at-work

# 3.2.16 / 2021-04-08

## Bug fixes:

* Correctly handle symlinks. Pull request #2836 by voxik


------------------------------------------------------------------------------

RubyGems installed the following executables:
        /home/[username]/.rbenv/versions/3.0.1/bin/gem
        /home/[username]/.rbenv/versions/3.0.1/bin/bundle
        /home/[username]/.rbenv/versions/3.0.1/bin/bundler

Ruby Interactive (ri) documentation was installed. ri is kind of like man
pages for Ruby libraries. You may access it like this:
  ri Classname
  ri Classname.class_method
  ri Classname#instance_method
If you do not wish to install this documentation in the future, use the
--no-document flag, or set it as the default in your ~/.gemrc file. See
'gem help env' for details.

RubyGems system software updated
$ gem -v
$ gem list
$ gem install bundler

またrubyのバージョンが出なくなってしまった。

$ ruby -v
rbenv: version `ruby-2.7.0' is not installed (set by /home/[username]/[projectname]/.ruby-version)

$ rbenv install 3.0.1

rbenvにどんなバージョンがインストールされているか確認

$ rbenv versions
rbenv: version `ruby-2.7.0' is not installed (set by /home/[username]/[projectname]/.ruby-version)
  system
  3.0.1

/home/[username]/[projectname]/.ruby-versionでrubyのバージョンを設定するらしい。
2.7.0となっていた。

[projectname]プロジェクトのrubyのバージョンを指定する。

$ cd /home/[username]/[projectname]
$ rbenv local 3.0.1

/home/[username]/[projectname]/.ruby-versionの中身が2.7.0から3.0.1に変更された。

前に実行した $ rbenv global 3.0.1 は環境全体のRubyバージョンを指定したい場合に使用するものらしい。
local は特定のプロジェクトだけで指定したい場合に使用。

rubyのバージョンが表示された。

$ ruby -v
ruby 3.0.1p64 (2021-04-05 revision 0fb782ee38) [x86_64-linux]

rails最新版をインストール

$ gem list rails -re

*** REMOTE GEMS ***

rails (6.1.4)

$ gem install rails -v 6.1.4

うまくいったかと思ったらまたエラーが出た。。

$ rails -v
Your Ruby version is 2.7.0, but your Gemfile specified 3.0.1

RubyのGemfileのバージョンと指定しているRubyのバージョンが異なるというエラーのよう。
GemfileのRubyのバージョンを変更3.0.1に変更すればよい。

Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '3.0.1'

??
3.0.1になってる。

修正が反映できてない?

$ bundle install

なおらない。

原因はこれか?
Your Ruby version is 2.5.3, but your Gemfile specified 2.5.1

$ sudo vi /usr/local/bin/bundler

#!/usr/bin/ruby2.7
#
# This file was generated by RubyGems.
#
# The application 'bundler' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

version = ">= 0.a"

str = ARGV.first
if str
  str = str.b[/\A_(.*)_\z/, 1]
  if str and Gem::Version.correct?(str)
    version = str
    ARGV.shift
  end
end

if Gem.respond_to?(:activate_bin_path)
load Gem.activate_bin_path('bundler', 'bundler', version)
else
gem "bundler", version
load Gem.bin_path("bundler", "bundler", version)
end

!/usr/bin/ruby2.7 

!/home/[username]/.rbenv/shims/ruby
に変更してみる。

なおらない。。

ターミナルを閉じてもう一度実行してみたらバージョン表示されたが、プロジェクトのバージョンがなぜか5.2.6になってる。。
ホームディレクトリの方でバージョン確認すると最新版が入っている。。
※/usr/local/bin/bundlerの記述を修正したから直ったのかは定かではない。あとで調査する。

$ cd /home/[username]/[projectname]
$ rails -v
Rails 5.2.6

$ cd /
$ rails -v
Rails 6.1.4

いったん先に進む。

Node.jsインストール

$ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
$ sudo apt install nodejs

Postgresインストール

$ sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
$ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
$ sudo apt update
$ sudo apt install postgresql
$ psql -V
psql (PostgreSQL) 13.3 (Ubuntu 13.3-1.pgdg20.04+1)

$ sudo service postgresql start
$ sudo su postgres -c 'createuser -s [username]'
$ psql postgres
\qを入力して抜ける。

$ sudo apt install libpq-dev

サーバー起動したらエラー発生

$ cd /home/[username]/[projectname]
$ bin/rails s
=> Booting Puma
=> Rails 5.2.6 application starting in development
=> Run `rails server -h` for more startup options
Exiting
/home/[username]/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-5.2.6/lib/action_dispatch/middleware/static.rb:111:in `initialize': wrong number of arguments (given 3, expected 2) (ArgumentError)

static.rbとは?
static.rb:111:in `initialize': wrong number of arguments (given 3, expected 2)
given 3, expected 2は引数が2つ欲しいのに、3つ渡されているというメッセージらしい。

static.rb
110   class Static
111     def initialize(app, path, index: "index", headers: {})
112       @app = app
113       @file_handler = FileHandler.new(path, index: index, headers: headers)
114     end
115
116     def call(env)
117       req = Rack::Request.new env
118
119       if req.get? || req.head?
120         path = req.path_info.chomp("/".freeze)
121         if match = @file_handler.match?(path)
122           req.path_info = match
123           return @file_handler.serve(req)
124         end
125       end
126
127       @app.call(req.env)
128     end
129   end

非常手段でinitializeにダミーで引数1つ追加したらサーバ起動したけど、(絶対に良くない笑)
起動したurl叩いてもページが表示されない。

https://qiita.com/zaru/items/ccf328e87c768168134d
[projectname]の下にfile_path作って
server.crt server.csr server.key 作ったけどエラー

Firewalld(iptablesのCentOS7用)をオフにしてオプションで -b 0.0.0.0にして実行したけどダメ

$ sudo systemctl stop firewalld.service
$ sudo systemctl mask firewalld.service
$ sudo systemctl list-unit-files | grep firewalld
$ bin/rails s -b 0.0.0.0

ダミーで引数1つ追加したのよくなかったから元に戻して別のやり方を模索中。。

[projectname]プロジェクトのrailsのバージョンを5.2.6から6.1.4にしてみる。

一度、プロジェクト削除して作り直す

$ rm -rf [projectname]/
rm: cannot remove '[projectname]/tmp/db': Device or resource busy

削除できない。。
postgresのプロセスをkillで殺したり、umountしてみたりしたけど変わらない。。

よくわからんけど、Dockerを起動したら削除できた。

node.jsやpostgresをrailsコマンドで作成したプロジェクトの中で作ってしまっていたようだが、一つ上の階層(ホームディレクトリ)で作る必要があったかもしれない。。

node.jsとpostgresのインストールをホームディレクトリで実施。

今度はホームディレクトリ直下に正常に入った。railsコマンドでプロジェクト新規作成。

$ cd ~/
$ psql -V
psql (PostgreSQL) 13.3 (Ubuntu 13.3-1.pgdg20.04+1)
$ rails new [projectname] -d postgresql
$ cd [projectname]
$ rails -v
Rails 6.1.4

ちゃんと6.1.4が入った。

データベース作成してサーバを起動。

$ bin/rails db:create
$ bin/rails s
/home/[username]/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/webpacker-5.2.1/lib/webpacker/configuration.rb:96:in 
`read': No such file or directory @ rb_sysopen - [projectname]/config/webpacker.yml (Errno::ENOENT)

動かない。。調べたらwebpacker.ymlがないことによるエラーらしい

$ rails webpacker:install
Yarn not installed. Please download and install Yarn from https://yarnpkg.com/lang/en/docs/install/
Exiting!

yarnがインストールされていないと上記のようにエラーが出るらしいのでyarnインストール

$ yarn -v
Command 'yarn' not found, but can be installed with:
sudo apt install cmdtest$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
$ sudo apt-get update && sudo apt-get install yarn
$ yarn -v
1.22.5
$ rails webpacker:install

webpacker.ymlができた。
気を取り直してサーバを起動。

$ bin/rails s
=> Booting Puma
=> Rails 6.1.4 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.3.2 (ruby 3.0.1-p64) ("Sweetnighter")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 6813
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop

動いた!!

http://127.0.0.1:3000で接続できない。。

どのアドレスからも受け付けるようになる以下を試す。

$ rails s -b 0.0.0.0
=> Booting Puma
=> Rails 6.1.4 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.3.2 (ruby 3.0.1-p64) ("Sweetnighter")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 380
* Listening on http://0.0.0.0:3000
Use Ctrl-C to stop

http://localhost:3000/
http://127.0.0.1:3000/
http://0.0.0.0:3000/
どれでアクセスしても接続できない。

ただ①②は
このサイトにアクセスできません
localhost で接続が拒否されました。
と表示されるのに対し

③は
このサイトにアクセスできません
http://0.0.0.0:3000/ のウェブページは一時的に停止しているか、新しいウェブアドレスに移動した可能性があります。
と少し違ったエラーメッセージが表示される。

そもそも3000番ポートは空いてるのか。

$ telnet 127.0.0.1 3000
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused

サーバーが立ち上がっていても、接続できないときは、ファイアウォール(iptablesなど)で拒否されている可能性もあるので、要確認。とあったので、確認する。

ポートの確認をしたかったので、nmapを入れてみた。
nmapはポートの空き/閉じ等を確認できる。

$ sudo apt-get install nmap
$ nmap localhost
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-06 04:56 JST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000054s latency).
All 1000 scanned ports on localhost (127.0.0.1) are closed

Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds

All 1000 scanned ports on localhost (127.0.0.1) are closed
(127.0.0.1)でスキャンされた1000個のポートはすべて閉じられています。だと…

-pでポート番号を指定できるらしい。これは単一のポート番号はもちろん、-p 1-1024のように範囲を指定できるので3000まで指定してみた。

$ nmap -p 1-3000 localhost
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-06 05:08 JST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000037s latency).
All 3000 scanned ports on localhost (127.0.0.1) are closed

Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds

(127.0.0.1)でスキャンされた3000個のポートはすべて閉じられています。と出るのう…

ポートが開いてないから接続できないと推測。

ファイアーウォールも動かないし、プロセスのPIDもおかしくなってるし、
おそらくだけど、インストールをミスりまくってUbuntuの環境自体をぶっ壊してしまったのではないかと推測している…
解決に時間かかりそうだから、いったん環境削除して作り直すか…

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