Railsアプリ作ってみました(初期編)
やっと…!やっとここまで…!
Railsアプリ作成
1.Railsプロジェクトを作成
Rails 5 + Unicorn + Nginx 環境構築メモ(自動起動設定も) - Qiita
【完全網羅】rails newの基礎からオプションまで(db, rspec) | 侍エンジニア塾ブログ | プログラミング入門者向け学習情報サイト
hogehogeはアプリ名を指定、「--skip-bundle」はbundleインストールをスキップ、「-d mysql」はDBをMySQLに指定。
$ rbenv exec bundle exec rails new hogehoge --skip-bundle -d mysql
Rails をローカルインストールするために使用した Bundler 環境を削除
$ ls -a
. .. hogehoge .bundle Gemfile Gemfile.lock vendor
$ rm -f Gemfile; rm -f Gemfile.lock; rm -rf .bundle; rm -rf vendor
$ ls -a
. .. hogehoge
綺麗になりました~
Railsアプリ環境に自動生成されているGemfile内に記述のあるrailsを含め、gemパッケージをbundlerでローカルインストールし直す。
$ cd hogehoge
$ sudo yum install mysql-devel
$ rbenv exec bundle install --path vendor/bundle
git管理ファイル.gitignoreに「vendor/bundle」を含めないように編集
$ echo '/vendor/bundle' >> .gitignore
確認
Railsサーバ起動
$ bundle exec rails server -e production
HTTPレスポンス確認
$ curl -I localhost:3000
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
X-Request-Id: 14e2df0f-eccb-4f3c-b5f2-4481afd3e00f
X-Runtime: 0.036461
Content-Length: 1722
hogehoge/publicの下にindex.html作ってないからそりゃそうだ。
前記事「GCEで事前準備(SSHでサーバー接続するまで編)」を参考にGCPコンソールでポート番号3000を開ける。
そのままブラウザで確認。http://【VMインスタンス外部IP】:3000/
わあああああああああRubyっぽいの出たーーーーーーー!!!!
エラーなのに喜ぶ私…
ちなみに↑これはpublic/404.htmlの表示で、index.htmlがないから出てると思うんだけど、Rails4まではpublic/index.htmlが自動的に作成されていたんだって…
2.MySQLの設定
データベース設定の編集
database.ymlのデータベース設定を編集
$ cp ./config/database.yml ./config/database_180411.yml
$ vim ./config/database.yml
本番環境想定なので、「development:」から始まる開発環境セクションと「test:」から始まるテスト環境セクションをコメントアウト。
「production:」から始まる本番環境セクションに「host: 【VMインスタンスの外部IP】」を追記、「username: hogehoge_user」に変更する。
MySQLユーザの作成
上記ユーザhogehoge_userをMySQLに作成する。
$ mysql -u root -p
> CREATE USER 'hogehoge_user'@'localhost' IDENTIFIED BY '【MySQLパスワード】';
------------間違えとそれの取り消し------------------------------------------------------------------
> GRANT ALL PRIVILEGES ON database_name.* TO 'hogehoge_user'@'localhost';
> FLUSH PRIVILEGES;
間違えた…
> SHOW GRANTS FOR 'hogehoge_user'@'localhost';
> revoke ALL PRIVILEGES ON `database_name`.* from 'hogehoge_user'@'localhost';
--------------------------------------------------------------------------------------------------------------
> GRANT ALL PRIVILEGES ON *.* TO 'hogehoge_user'@'localhost';
> SHOW GRANTS FOR 'hogehoge_user'@'localhost';
> FLUSH PRIVILEGES;
環境変数の設定
環境変数に追加
以下を追記
export RAILS_ENV='production'
export RAILS_DATABASE_PASSWORD='【MySQLパスワード】'
.bash_profileを再読込
$ source ~/.bash_profile
3.Railsアプリのデータベース作成
database.ymlの内容でデータベースを作成
$ bundle exec rake db:create RAILS_ENV=production
(略)
rake aborted!
Bundler::GemRequireError: There was an error while trying to load the gem 'uglifier'.
Gem Load Error is: Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes.
Backtrace for gem load error is:
/var/www/rails/hogehoge/vendor/bundle/ruby/2.5.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:58:in `autodetect'
(略)
あらららエラー…青字エラーで確認。
2個めの参照リンクでNode.jsが足りないとあるので、先にyumリポジトリにnodejsを追加(EPELのリポジトリを使用)
$ sudo yum install nodejs --enablerepo=epel
$ bundle exec rake db:create RAILS_ENV=production
#<Mysql2::Error: Can't connect to MySQL server on '【VMインスタンスの外部IP】' (110)>
Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "pool"=>5,
(略)
Created database 'hogehoge_production'
エラーが変わった。MySQLに接続できない\(^o^)/外部IP指定しちゃだめなのか。
$ vim ./config/database.yml
「production:」から始まる本番環境セクションに「host: localhost」に変更
$ bundle exec rake db:create RAILS_ENV=production
Access denied for user 'hogehoge_user'@'localhost' (using password: NO)Please provide the root password for your MySQL installation
>
rootのパスワード入力するが、
Mysql2::Error: Your password does not satisfy the current policy requirements: GRANT ALL PRIVILEGES ON `hogehoge_production`.* TO 'hogehoge_user'@'localhost' IDENTIFIED BY '' WITH GRANT OPTION;
Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "pool"=>5, "username"=>"hogehoge_user", "password"=>nil, "socket"=>"/var/lib/mysql/mysql.sock", "database"=>"hogehoge_production", "host"=>"localhost"}
rake aborted!
(略)
まだエラー出る割に、MySQLでDB確認するとDB作成されてる…
青字はdatabase.ymlでpasswordが設定されていなかったら出るエラーらしい。
database.ymlを再度確認すると
password: <%= ENV['HOGEHOGE_DATABASE_PASSWORD'] %>
先程.bash_profileの環境変数には「RAILS_DATABASE_PASSWORD」を設定したわけだから、「RAILS_DATABASE_PASSWORD」で揃える。
$ bundle exec rake db:create RAILS_ENV=production
Database 'hogehoge_production' already exists
そりゃそうだ…気持ち悪いから作り直そう…
$ bundle exec rake db:migrate:reset RAILS_ENV=production
Dropped database 'hogehoge_production'
Created database 'hogehoge_production'
db/migrateディレクトリ内のファイルを使い、DBにテーブル作成
$ bundle exec rake db:migrate RAILS_ENV=production
> use hogehoge_production;
> show tables;
+-------------------------------+
| Tables_in_hogehoge_production |
+-------------------------------+
| ar_internal_metadata |
| schema_migrations |
+-------------------------------+
2 rows in set (0.00 sec)
4.Secret Key登録
Rails 5 + Unicorn + Nginx 環境構築メモ(自動起動設定も) - Qiita
Rails5.1をproduction環境で起動する際の秘密鍵設定 - Qiita
Rails が production 環境で真っ白、SECRET_KEY_BASE 設定忘れが原因でした | EasyRamble
RailsをProduction環境で起動するにはRails4.1から秘密鍵を設定しないといけないようです。
$ bundle exec rake secret
長い文字列が出てくるので、これを環境変数に設定する。
以下を追記(xxx部分を上記結果の長い文字列に)
export SECRET_KEY_BASE='xxx'
.bash_profileを再読込
source ~/.bash_profile
5.JavaScript Runtimeの有効
Unicorn入れようと思って調べたら、Rails起動するときエラーになるときあるのでtherubyracerインストールしとけって。
これ前記事でbundle exec rake db:create RAILS_ENV=production時に「There was an error while trying to load the gem 'uglifier'.」のエラーが出て、対応の一つであったけどbundle installで上手くいかなくて、yumリポジトリにnodejs追加したらrake db:create出来たから、まあいいかと放置してたやつだ…
$ cd hogehoge
$ vim Gemfile
以下のコメントアウトを外す
gem 'therubyracer', platforms: :ruby
therubyracerをbundle installするためにはg++が必要とのことなのでインストール
$ sudo yum install gcc-c++.x86_64
$ rbenv exec bundle install --path vendor/bundle
6.Unicornインストール
今回結局、ApacheじゃなくてNginx入れたので、Unicornの方がいいらしい。
なのでUnicon(RailsがApacheやNginxで動くためのアプリケーションサーバ)を入れていく。
Unicornのインストール
Gemfileの編集
$ cd hogehoge
$ vim Gemfile
以下を追記
gem 'unicorn'
bundleを使ってUnicornをインストール
$ rbenv exec bundle install --path vendor/bundle
configファイルの作成と編集
一度Unicorn設定および自動起動設定(/etc/init.d/)をしたけどエラーにハマり、結局database.ymlにパスワード直書きなら解決したけど、そりゃじゃ気持ち悪いので自動起動をRakeタスクに変更しました。変更前の紆余曲折を見たい方は↓どうぞ。
②CentOS7にRailsとUnicornとNginxをインストールして連携させる(あとMySQLも) - とりとめも
$ cd hogehoge/config
$ vim unicorn.rb
以下の内容を追記(基本はリンク①だが青字のみリンク③)
# Railsのルートパスを求める。(RAILS_ROOT/config/unicorn.rbに配置している場合。)
rails_root = File.expand_path('../../', __FILE__)
ENV['BUNDLE_GEMFILE'] = rails_root + "/Gemfile"
# Unicornのワーカー数
worker_processes 2
# Unicornの起動コマンドを実行するディレクトリを指定
working_directory rails_root
# 接続タイムアウト時間
timeout 30
# Unicornのエラーログと通常ログの位置の指定
stderr_path File.expand_path('../../log/unicorn_stderr.log', __FILE__)
stdout_path File.expand_path('../../log/unicorn_stdout.log', __FILE__)
# Nginxで使用
listen File.expand_path('../../tmp/sockets/unicorn.sock', __FILE__)
# とりあえず起動して動作確認をしたい場合は以下の設定を行う。
# listen 8080
# プロセスの停止などに必要なPIDファイルの保存先を指定
pid File.expand_path('../../tmp/pids/unicorn.pid', __FILE__)
# 基本的には`true`を指定する。Unicornの再起動時にダウンタイムなしで再起動が行われる。
preload_app true
# USR2シグナルを受けると古いプロセスを止める。
before_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
Process.kill 'QUIT', Process.pid
end
defined?(ActiveRecord::Base) and
ActiveRecord::Base.connection.disconnect!
end
after_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
end
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection
end
自動起動の設定(/etc/init.d/unicornを新規作成)
$ cd /etc/init.d/
$ sudo vim unicorn
リンク③をそのまま追記
$ ls -al
total 44
(略)
-rw-r--r-- 1 root root 1420 Apr 11 23:11 unicorn
ファイル権限を変更
$ chmod 755 /etc/init.d/unicorn
$ ls -al
total 44
(略)
-rwxr-xr-x 1 root root 1420 Apr 11 23:11 unicorn
自動起動設定
$ sudo chkconfig unicorn on
Unicorn起動
$ sudo service unicorn start
start production
/etc/init.d/unicorn: line 32: bundle: command not found
おおう…
-------意味ない対応-----------------------------------------------------
$ which bundle
~/.rbenv/shims/bundle
$ bundle show unicorn
/var/www/rails/hogehoge/vendor/bundle/ruby/2.5.0/gems/unicorn-5.4.0
違うけど…
.bundle]$ rbenv exec gem install bundler
Successfully installed bundler-1.16.1
Parsing documentation for bundler-1.16.1
Done installing documentation for bundler after 5 seconds
1 gem installed
再度bundlerインストールしても結果は変わらず。
------------------------------------------------------------------------------
$ cd hogehoge
$ bundle exec unicorn_rails -c config/unicorn.rb -D -E production
これならエラーなく通る。自動起動がこれやるとダメなのか…
gemの情報表示
$ gem environment
RubyGems Environment:
- RUBYGEMS VERSION: 2.7.6
(略)
- EXECUTABLE DIRECTORY: /home/【ユーザ名】/.rbenv/versions/2.5.1/bin
(略)
$ echo $PATH
これに表示されるPATHにはEXECUTABLE DIRECTORY指定のディレクトリはなかった…だから通らなかったのか。
とりあえず/etc/init.d/unicornに直でPATH書いてしまう。
$ sudo vim /etc/init.d/unicorn
以下をコメント直下に追記
export PATH=/home/【ユーザ名】/.rbenv/versions/2.5.1/bin:$PATH
Unicornサービス起動
$ sudo service unicorn start
start production
master failed to start, check stderr log for details
エラーが変わった。
とりあえず全部上手く行ったら、PATHの直書きやめて、以下を参考に対応したい。
ログを確認。
$ view log/unicorn_stderr.log
すると以下のエラーが書いてあった。
ArgumentError: Already running on PID:12789 (or pid=/var/www/rails/hogehoge/tmp/pids/unicorn.pid is stale)
すでに起動していると出るみたい。そういえばさっき起動してた…( ;∀;)
Unicorn停止してから再度起動
$ sudo kill -QUIT `cat tmp/pids/unicorn.pid`
$ sudo service unicorn start
start production
master failed to start, check stderr log for details
またかよ~~~
$ view log/unicorn_stderr.log
今度のエラーはまた違う…
ERROR -- : Access denied for user 'hogehoge_user'@'localhost' (using password: NO) (Mysql2::Error)
DBパスワードの環境変数が上手く読み込めないことがあるみたい。
確かにdatabase.ymlでpassword直書きして「sudo service unicorn start」したらいけた…でも環境変数に戻したい。
また戻して、さらにdefaultセクションもuserおよびpasswordを直して再チャレンジ。
$ sudo service unicorn start
start production
master failed to start, check stderr log for details
またかよ~~~
$ view log/unicorn_stderr.log
(略)
E, [2018-04-12T02:34:24.933441 #14713] ERROR -- : adding listener failed addr=/var/www/rails/hogehoge/tmp/sockets/unicorn.sock (in use)
Errno::EADDRINUSE: Address already in use - connect(2) for /var/www/rails/hogehoge/tmp/sockets/unicorn.sock
(略)
今度また違うエラー…ソケットがもう使われてるって。
$ netstat -anp
↓結果
Proto | RefCnt | Flags | Type | State | I-Node | PID/ Program name |
Path |
---|---|---|---|---|---|---|---|
unix | 2 | [ ACC ] | STREAM | LISTENING | 334765 | - | /var/www/ rails/hogehoge/ tmp/sockets/ unicorn.sock |
unicorn.sockが既に起動されてるからのエラーだと思う。
↓これを見直してみると、Nginxの設定してからsocketの設定(listen部分)した方がいいようだ…ああああ凡ミス…
以下の部分のコメントを逆に
# Nginxで使用
# listen File.expand_path('../../tmp/sockets/unicorn.sock', __FILE__)
# とりあえず起動して動作確認をしたい場合は以下の設定を行う。
listen 8080
再度Unicorn起動
$ sudo service unicorn start
start production
master failed to start, check stderr log for details
もう疲れたよ母ちゃん…( ;∀;)
$ view log/unicorn_stderr.log
(略)
ERROR -- : Access denied for user 'hogehoge_user'@'localhost' (using password: NO) (Mysql2::Error)
(略)
またお前かーーーーーーーーーーー
ちなみにRailsのコンソールで確認すると
$ rbenv exec bundle exec rails c
Loading production environment (Rails 5.1.6)
irb(main):001:0> ENV['RAILS_DATABASE_PASSWORD']
=> "xxx"
ちゃんと表示されている…
$ sudo vim /etc/profile
$ source /etc/profile
これに環境変数追加してもだめ( ;∀;)
CapistranoでUnicorn + nginx in Ubuntuにデプロイしたら環境変数が適用されない問題解決メモ - Qiita
どうもservice起動だと環境変数が適用されないようだ…でも
$ sudo /etc/init.d/unicorn start
これで起動してもだめ( ;∀;)
$ sudo vim /etc/init.d/unicorn
これに環境変数をまた直書きする…
export RAILS_DATABASE_PASSWORD='【DBパスワード】':$RAILS_DATABASE_PASSWORD
で、またUnicorn起動してみるとエラーが変わった↓
RuntimeError: YAML syntax error occurred while parsing /var/www/rails/hogehoge/config/database.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Error: (<unknown>): mapping values are not allowed in this context at line 58 column 24
config/database.ymlの構成がダメなんだって。タブ入ってるんじゃないかって。
入ってねーよ。
もうまたconfig/database.ymlにDBパスワード直書きする…
いけた…( ;∀;)
とりあえずGithubとかに上げる予定もないし、これで進む…
Nginxの再設定
前記事で作成したRails個別のNginx設定ファイルをUniorn用に編集する。
$ sudo vim /etc/nginx/conf.d/hogehoge.conf
編集
upstream unicorn {
unix:/var/www/rails/hogehoge/tmp/sockets/unicorn.sock;
}
server {
listen 80;
server_name 【VMインスタンスの外部IP】;
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
root /var/www/rails/hogehoge/public;
client_max_body_size 100m;
error_page 404 /404.html;
error_page 500 502 503 504 /500.html;
try_files $uri/index.html $uri @unicorn;
location @unicorn {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://unicorn;
}
}
Nginx再起動
$ sudo systemctl restart nginx
Unicornの再設定
で、さっきUniorn設定時にUnicorn単体で使うために「listen 8080」としたところをNginx用の設定に戻す。
内容
# Nginxで使用
listen File.expand_path('../../tmp/sockets/unicorn.sock', __FILE__)
# とりあえず起動して動作確認をしたい場合は以下の設定を行う。
#listen 8080
Unicorn再起動
$ sudo service unicorn start
start production
master failed to start, check stderr log for details
エラー確認
$ view log/unicorn_stderr.log
E, [2018-04-13T11:53:19.349097 #31351] ERROR -- : adding listener failed addr=/var/www/rails/branches/tmp/sockets/unicorn.sock (in use)
Errno::EADDRINUSE: Address already in use - connect(2) for /var/www/rails/branches/tmp/sockets/unicorn.sock
ああああ上のエラーと一緒( ;∀;)まだ残ってたか…
unicorn.rbを絶対パスに直すのと、ソケットをunlink
$ cd tmp/sockets
$ ls
unicorn.sock
$ unlink unicorn.sock
$ ls
unicorn.sockなくなった。また「netstat -anp」してみてもunicorn.sock上がってくるがいけるだろうか。
$ sudo service unicorn start
start production
いけたーーーーー!!
あとCentOS7ではソケットがあるtmpを共有できないらしいので、対応しておく。
CentOS7にRailsとUnicornとNginxをインストールして連携させる(あとMySQLも) - とりとめも
AWS(Amazon Web Services) - AWS デプロイ 500エラー になります!(85616)|teratail
内容
# Nginxで使用
#listen File.expand_path('/var/www/rails/branches/tmp/sockets/unicorn.sock', __FILE__)
listen File.expand_path('/var/run/unicorn/unicorn.sock', __FILE__)
$ sudo vim /etc/nginx/conf.d/hogehoge.conf
内容
upstream unicorn {
#server unix:/var/www/rails/hogehoge/tmp/sockets/unicorn.sock;
server unix:/var/run/unicorn/unicorn.sock;
}
あと格納ディレクトリが存在しないとエラーになるので作成(unicorn.socketいらないんじゃ…?)
$ sudo mkdir /var/run/unicorn/unicorn.socket
$ sudo chmod 755 /var/run/unicorn/unicorn.socket
Unicorn設定ファイルを新規作成する。
ちなみにsockファイルの場所は以下を参照。
CentOS7にRailsとUnicornとNginxをインストールして連携させる(あとMySQLも) - とりとめも
AWS(Amazon Web Services) - AWS デプロイ 500エラー になります!(85616)|teratail
$ cd /var/www/rails/branches
内容
worker_processes Integer(ENV["WEB_CONCURRENCY"] || 2)
timeout 15
preload_app true
listen '/var/run/unicorn/unicorn.sock'
pid '/var/www/rails/hogehoge/tmp/pids/unicorn.pid'
before_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
Process.kill 'QUIT', Process.pid
end
defined?(ActiveRecord::Base) and
ActiveRecord::Base.connection.disconnect!
end
after_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
end
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection
end
stderr_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])
stdout_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])
Rakeタスクの作成
Rakeタスクを新規作成する。
$ rbenv exec bundle exec rails g task unicorn
create lib/tasks/unicorn.rake
$ vim lib/tasks/unicorn.rake
内容
namespace :unicorn do
# Tasks
desc "Start unicorn"
task(:start) {
config = Rails.root.join('config', 'unicorn.rb')
#sh "unicorn -c #{config} -E development -D"
sh "unicorn -c #{config} -E production -D"
}
desc "Stop unicorn"
task(:stop) {
unicorn_signal :QUIT
}
desc "Restart unicorn with USR2"
task(:restart) {
unicorn_signal :USR2
}
desc "Increment number of worker processes"
task(:increment) {
unicorn_signal :TTIN
}
desc "Decrement number of worker processes"
task(:decrement) {
unicorn_signal :TTOU
}
desc "Unicorn pstree (depends on pstree command)"
task(:pstree) do
sh "pstree '#{unicorn_pid}'"
end
# Helpers
def unicorn_signal signal
Process.kill signal, unicorn_pid
end
def unicorn_pid
begin
#File.read("/home/vagrant/myapp/tmp/unicorn.pid").to_i
File.read("/var/www/rails/branches/tmp/pids/unicorn.pid").to_i
rescue Errno::ENOENT
raise "Unicorn does not seem to be running"
end
end
end
開発環境DB作成
開発環境のDB作成してなかったので、作成する。
$ rbenv exec bundle exec rake db:create RAILS_ENV=development
Created database 'branches_development'
MySQLに接続して確認。
mysql> show databases;
+----------------------+
| Database |
+----------------------+
| information_schema |
| hogehoge_development |
| hogehoge_production |
| mysql |
| performance_schema |
| sys |
+----------------------+
6 rows in set (0.17 sec)
hogehoge_developmentが作られてる~~\(^o^)/
Unicorn起動
$ rbenv exec bundle exec rake unicorn:start
エラー出たので確認。
内容
F, [2018-04-13T23:15:34.998489 #5224] FATAL -- : error adding listener addr=/var/run/unicorn/unicorn.sock
/var/www/rails/branches/vendor/bundle/ruby/2.5.0/gems/unicorn-5.4.0/lib/unicorn/socket_helper.rb:128:in `unlink': Permission denied @ apply2files - /var/run/unicorn/unicorn.sock (Errno::EACCES)
ここらへん↓参考にしてNginxの実行ユーザ変えてみたりUnicorn実行文にポート追加してみたりしたけどダメだった。
あとこのへんも↓参考にして「$ sudo /home/【ユーザ名】/.rbenv/bin/rbenv exec bundle exec rake unicorn:start」のroot権限で実行してみたけど、「/usr/bin/env: ruby: No such file or directory」というエラーが出てダメだった。
$ ls -al /var/run/unicorn/
srwxrwxrwx 1 root root 0 Apr 13 14:01 unicorn.sock
そもそもunlinkなら上のディレクトリの権限もいる…?(適当な予想)
$ ls -al /var/run/
drwxr-xr-x 3 root root 80 Apr 13 14:01 unicorn
$ sudo chmod 777 /var/run/unicorn
$ ls -al /var/run/
drwxrwxrwx 3 root root 80 Apr 13 14:01 unicorn
$ rbenv exec bundle exec rake unicorn:start
いけた!ちなみに775でもダメだった。
あと、↓この記事で同じく権限777にしてるからいいや。
Unicorn停止もしてみる。
$ rbenv exec bundle exec rake unicorn:stop
次はNginx起動だ!
Nginxの設定変更
$ sudo vim /etc/nginx/conf.d/hogehoge.conf
内容
upstream unicorn {
#server unix:/home/vagrant/myapp/tmp/unicorn.sock;
server unix:/var/run/unicorn/unicorn.sock;
}
server {
listen 80;
#server_name 192.168.33.12;
server_name 【VMインスタンスの外部IP】;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
#root /home/vagrant/myapp/public;
root /var/www/rails/hogehoge/public;
client_max_body_size 100m;
error_page 404 /404.html;
error_page 500 502 503 504 /500.html;
try_files $uri/index.html $uri @unicorn;
location @unicorn {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://unicorn;
}
}
$ sudo systemctl start nginx
よし、次は本番環境でもいけるかやってみる。
以下の部分を変更。
#sh "unicorn -c #{config} -E development -D"
sh "unicorn -c #{config} -E production -D"
$ rbenv exec bundle exec rake unicorn:start
いけた!\(^o^)/
ちなみにrbenv execって付けてるけど、システムのbundle使ってじゃなくてrbenvの現在有効なbundle使って実行って意味らしい。
7.Nginxの設定
Nginxの再々設定
ドキュメントルート変更
$ sudo vim /etc/nginx/conf.d/hogehoge.conf
root /var/www/rails/hogehoge/public;
Nginxの自動起動設定
$ sudo systemctl enable nginx.service
Nginx再起動。
先にNginxインストールして起動しちゃってたけど、今までの参考リンク見てるとUnicorn→Nginxの順にインストールしてるのよね(・_・;)
今度するときはそうしよう…
8.エラー対応
さて、UnicornもNginxも起動したわけだが、ブラウザで外部IPにアクセスすると
500エラー…
/var/log/nginx/error.log見てもアクセス日時のエラー出てないぞ…
public/index.html作成→エラー
/etc/nginx/conf.d/branches.confのserver_nameを「localhost」に変更→Nginxのデフォルトページ表示→多分 /etc/nginx/nginx.confの設定が上書きされてる→戻す
とかやってる間に表示された…
原因は謎…
しかしページがないのなら、public/500.htmlが表示されるべきでは?
Railsの方ルートやらまったく触ってないので、それを触ってから解決してみる。
とりあえず以上!