4
3

More than 3 years have passed since last update.

Nginx+unicornをherokuで使う方法

Last updated at Posted at 2021-09-02

Nginxサーバーとは

Nginxとは処理速度が速く、高負荷に比較的強いWEBサーバーのことです。
ローカル環境ではデフォルトでpumaという名前のWebサーバーが使われており、railsサーバ起動時のログでpumaが使われています。
この記事ではアプリケーションサーバー(Nginx)を設定する方法をお伝えしたいと思います。

Nginxサーバーをセッティングする

unicornのインストール
unicornについては下記サイトを参考にして下さい
https://www.autovice.jp/articles/146

まずはGemをインストール
Gemfile

gem 'unicorn'
gem 'unicorn-rails'

gemfileの書き込みが終わったら

$ bundle install

あらゆる言語でのアプリケーション開発を可能にする Heroku buildpackを実行
Nginxをインストール

$ heroku buildpacks:add heroku-community/nginx

アプリケーション直下にProcfileを作成し、下記を記載
Procfile

web: bin/start-nginx bundle exec unicorn -c config/unicorn.rb

unicorn.rbを作成し、下記を記載
app/config/unicorn.rb

require 'fileutils'
listen '/tmp/nginx.socket'
before_fork do |server,worker|
    FileUtils.touch('/tmp/app-initialized')
end

herokuの設定

$ heroku login
$ heroku create
$ rails assets:precompile RAILS_ENV=production
$ heroku buildpacks:set heroku/ruby
$ heroku buildpacks:add --index 1 heroku/nodejs

herokuにデプロイ

$ git add .
$ git commit -m "hoge"
$ git push heroku master
$ heroku run rails db:migrate

PostgreSQLへの接続ができない場合(herokuのアドオンを追加)
$ heroku addons:create heroku-postgresql

これでセッティング完了!
あとはherokuのlogからNginxのサーバーが繋がっているかを確認する
以下のコマンドから確認できると思います!

$ heroku logs -t

最後までご覧頂きありがとうございました!

4
3
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
3