質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
unicorn

Unicornは、汎用のRackアプリケーションサーバ。RackとWebサーバーの機能を併せ持ちます。レスポンス処理や、Nginx単体がRackの機能をサポートしていない事から、一般的にはNginx+Unicorn+Railsの構成を取って用います。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

nginx

nginixは軽量で高性能なwebサーバーの1つです。BSD-likeライセンスのもとリリースされており、あわせてHTTPサーバ、リバースプロキシ、メールプロキシの機能も備えています。MacOSX、Windows、Linux、上で動作します。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

Capistrano

Rubyで書かれたサーバオーケストレーションで、複数のサーバでスクリプトを実行する際に用いられます。主な使用用途はWebアプリケーションのデプロイメントです。 アプリケーションのバージョンアップ自動化、およびデータベースの変更などもできます。

Q&A

1回答

4199閲覧

502 Bad Gatewayを解決しrailsアプリを画面に表示させたい

anago1030

総合スコア1

unicorn

Unicornは、汎用のRackアプリケーションサーバ。RackとWebサーバーの機能を併せ持ちます。レスポンス処理や、Nginx単体がRackの機能をサポートしていない事から、一般的にはNginx+Unicorn+Railsの構成を取って用います。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

nginx

nginixは軽量で高性能なwebサーバーの1つです。BSD-likeライセンスのもとリリースされており、あわせてHTTPサーバ、リバースプロキシ、メールプロキシの機能も備えています。MacOSX、Windows、Linux、上で動作します。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

Capistrano

Rubyで書かれたサーバオーケストレーションで、複数のサーバでスクリプトを実行する際に用いられます。主な使用用途はWebアプリケーションのデプロイメントです。 アプリケーションのバージョンアップ自動化、およびデータベースの変更などもできます。

0グッド

0クリップ

投稿2021/02/17 20:17

編集2021/02/18 09:57

解決したいこと

railsアプリを作成し、AWSのEC2で本番環境にデプロイをしました。
問題なく本番環境で動作していたのですが、突然エラーが起こりアクセスできなくなってしまいました。

nginxがエラー原因に絡んでいると考えたのでいろいろ試しましたがエラーが解決しません。
どうかご協力いただきたいです。

開発環境

  • MacOS Catarina
  • Ruby2.6.5
  • Ruby on Rails 6.0
  • AWS(EC2)
  • Nginx
  • Unicorn
  • Capistrano

エラー画面

イメージ説明

試したこと

1. Nigixのエラーログを確認

php:ターミナル

1$ sudo cat /var/log/nginx/error.log 2 3# 実行結果 4[error] 10239#0: *1 connect() to unix:/var/www/entertainer/shared/tmp/sockets/unicorn.sock failed (111: Connection refused) while connecting to upstream

1の実行結果より
unix:/var/www/rails/xxxxxx/tmp/sockets/.unicorn.sock failedでググるとこちらの記事に
行き着きました

Nginx + Unicorn + Rails ドハマリしたエラーを3つ解説

2. Nginxのステータスを確認
先程の記事とエラーの内容が同じだったのでNginxのステータスを確認しました。

php:ターミナル

1$ systemctl status nginx.service 2 3# 実行結果 4systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument

ここから先はコマンドの意味が理解できなかったのですが、とりあえず記事の通りに実行しました。

php:ターミナル

1$ mkdir /etc/systemd/system/nginx.service.d 2 3# 実行結果 4mkdir: ディレクトリ `/etc/systemd/system/nginx.service.d' を作成できません: File exists 5 6# rootに移行 7$ sudo su - root 8[root@ip-172-31-45-167 ~]# 9 10[root@ip-172-31-45-167 ~]# printf "[Service]\nExecStartPost=/bin/sleep 0.1\n" > /etc/systemd/system/nginx.service.d/override.conf 11[root@ip-172-31-45-167 ~]# systemctl daemon-reload 12[root@ip-172-31-45-167 ~]# systemctl restart nginx 13 14# 念の為 15[root@ip-172-31-45-167 ~]# exit 16[ec2-user@ip-172-31-45-167 app]$ sudo systemctl daemon-reload 17[ec2-user@ip-172-31-45-167 app]$ sudo systemctl restart nginx 18

もう一度ステータスを確認すると2で確認したエラーは解消されていました。

php;ターミナル

1$ systemctl status nginx.service 2 3# 実行結果 4217 19:24:31 ip-172-31-45-167.ap-northeast-1.compute.internal systemd[1]: Starting The nginx HTTP and reverse proxy server... 5 217 19:24:31 ip-172-31-45-167.ap-northeast-1.compute.internal nginx[10224]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 6 217 19:24:31 ip-172-31-45-167.ap-northeast-1.compute.internal nginx[10224]: nginx: configuration file /etc/nginx/nginx.conf test is successful 7 217 19:24:31 ip-172-31-45-167.ap-northeast-1.compute.internal systemd[1]: Started The nginx HTTP and reverse proxy server. 8```   9 10 11しかし、確認のためIPアドレスをブラウザでうってもまだ502のエラーは解消されませんでした。 12ここから手詰まりになってしまいました。。。 13 14# /etc/nginx/conf.d/rails.conf 15```php: /etc/nginx/conf.d/rails.conf 16upstream app_server { 17 server unix:/var/www/entertainer/shared/tmp/sockets/unicorn.sock; 18} 19 20server { 21 listen 80; 22 server_name 54.150.30.40; 23 # currnetの中の中身を参照するよう変更 24 root /var/www/entertainer/currnet/public; 25 26 location ^~ /assets/ { 27 gzip_static on; 28 expires max; 29 add_header Cache-Control public; 30 # currentの中を参照するよう変更 31 root /var/www/entertainer/current/public; 32 } 33 34 try_files $uri/index.html $uri @unicorn; 35 36 location @unicorn { 37 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 proxy_set_header Host $http_host; 39 proxy_redirect off; 40 proxy_pass http://app_server; 41 } 42 43 error_page 500 502 503 504 /500.html; 44}

unicorn.rb

php:unicorn.rb

1# ../が一つ増えている 2app_path = File.expand_path('../../../', __FILE__) 3 4worker_processes 1 5# currentを指定 6working_directory "#{app_path}/current" 7 8# それぞれ、sharedの中を参照するよう変更 9listen "#{app_path}/shared/tmp/sockets/unicorn.sock" 10pid "#{app_path}/shared/tmp/pids/unicorn.pid" 11stderr_path "#{app_path}/shared/log/unicorn.stderr.log" 12stdout_path "#{app_path}/shared/log/unicorn.stdout.log" 13 14#Railsアプリケーションの応答を待つ上限時間を設定 15timeout 60 16 17#以下は応用的な設定なので説明は割愛 18 19preload_app true 20GC.respond_to?(:copy_on_write_friendly=) && GC.copy_on_write_friendly = true 21 22check_client_connection false 23 24run_once = true 25 26before_fork do |server, worker| 27 defined?(ActiveRecord::Base) && 28 ActiveRecord::Base.connection.disconnect! 29 30 if run_once 31 run_once = false # prevent from firing again 32 end 33 34 old_pid = "#{server.config[:pid]}.oldbin" 35 if File.exist?(old_pid) && server.pid != old_pid 36 begin 37 sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU 38 Process.kill(sig, File.read(old_pid).to_i) 39 rescue Errno::ENOENT, Errno::ESRCH => e 40 logger.error e 41 end 42 end 43end 44 45after_fork do |_server, _worker| 46 defined?(ActiveRecord::Base) && ActiveRecord::Base.establish_connection 47end

config/environments/production.rb

php:config/environments/production.rb

1Rails.application.configure do 2 # Settings specified here will take precedence over those in config/application.rb. 3 4 # Code is not reloaded between requests. 5 config.cache_classes = true 6 7 # Eager load code on boot. This eager loads most of Rails and 8 # your application in memory, allowing both threaded web servers 9 # and those relying on copy on write to perform better. 10 # Rake tasks automatically ignore this option for performance. 11 config.eager_load = true 12 13 # Full error reports are disabled and caching is turned on. 14 config.consider_all_requests_local = false 15 config.action_controller.perform_caching = true 16 17 # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 18 # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 # config.require_master_key = true 20 21 # Disable serving static files from the `/public` folder by default since 22 # Apache or NGINX already handles this. 23 # config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 config.public_file_server.enabled = true 25 26 # Compress CSS using a preprocessor. 27 # config.assets.css_compressor = :sass 28 29 # Do not fallback to assets pipeline if a precompiled asset is missed. 30 config.assets.compile = false 31 32 # Enable serving of images, stylesheets, and JavaScripts from an asset server. 33 # config.action_controller.asset_host = 'http://assets.example.com' 34 35 # Specifies the header that your server uses for sending files. 36 # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 37 # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 38 39 # Store uploaded files on the local file system (see config/storage.yml for options). 40 config.active_storage.service = :local 41 42 # Mount Action Cable outside main process or domain. 43 # config.action_cable.mount_path = nil 44 # config.action_cable.url = 'wss://example.com/cable' 45 # config.action_cable.allowed_request_origins = [ 'http://example.com', /http://example.*/ ] 46 47 # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 48 # config.force_ssl = true 49 50 # Use the lowest log level to ensure availability of diagnostic information 51 # when problems arise. 52 config.log_level = :debug 53 54 # Prepend all log lines with the following tags. 55 config.log_tags = [ :request_id ] 56 57 # Use a different cache store in production. 58 # config.cache_store = :mem_cache_store 59 60 # Use a real queuing backend for Active Job (and separate queues per environment). 61 # config.active_job.queue_adapter = :resque 62 # config.active_job.queue_name_prefix = "entertainer_production" 63 64 config.action_mailer.perform_caching = false 65 66 # Ignore bad email addresses and do not raise email delivery errors. 67 # Set this to true and configure the email server for immediate delivery to raise delivery errors. 68 # config.action_mailer.raise_delivery_errors = false 69 70 # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 71 # the I18n.default_locale when a translation cannot be found). 72 config.i18n.fallbacks = true 73 74 # Send deprecation notices to registered listeners. 75 config.active_support.deprecation = :notify 76 77 # Use default logging formatter so that PID and timestamp are not suppressed. 78 config.log_formatter = ::Logger::Formatter.new 79 80 # Use a different logger for distributed setups. 81 # require 'syslog/logger' 82 # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 83 84 if ENV["RAILS_LOG_TO_STDOUT"].present? 85 logger = ActiveSupport::Logger.new(STDOUT) 86 logger.formatter = config.log_formatter 87 config.logger = ActiveSupport::TaggedLogging.new(logger) 88 end 89 90 # Do not dump schema after migrations. 91 config.active_record.dump_schema_after_migration = false 92 93 # Inserts middleware to perform automatic connection switching. 94 # The `database_selector` hash is used to pass options to the DatabaseSelector 95 # middleware. The `delay` is used to determine how long to wait after a write 96 # to send a subsequent read to the primary. 97 # 98 # The `database_resolver` class is used by the middleware to determine which 99 # database is appropriate to use based on the time delay. 100 # 101 # The `database_resolver_context` class is used by the middleware to set 102 # timestamps for the last write to the primary. The resolver uses the context 103 # class timestamps to determine how long to wait before reading from the 104 # replica. 105 # 106 # By default Rails will store a last write timestamp in the session. The 107 # DatabaseSelector middleware is designed as such you can define your own 108 # strategy for connection switching and pass that into the middleware through 109 # these configuration options. 110 # config.active_record.database_selector = { delay: 2.seconds } 111 # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 112 # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 113end

どうかご教授願いたいです。。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

nginxがフロントエンド、unicornがバックエンドの環境で
nginxが応答(502エラー)を返していることから、unicorn側でNGになっているものと予想されます。

単にunicornが落ちてるのではないでしょうか。その場合、unicornを起動してからブラウザでアクセスしてみてください。

投稿2021/02/18 05:34

yukky1201

総合スコア2751

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

anago1030

2021/02/18 10:09

ご返信ありがとうございます! ps -ef | grep unicorn | grep -v grepをターミナルで実行したところ、yukkyさんのおっしゃる通りunicornが停止していました。 RAILS_SERVE_STATIC_FILES=1 unicorn_rails -c config/unicorn.rb -E production -Dコマンドで 再起動し、ブラウザで確認してみると、502のエラーは解消したのですが、We're sorry, but something went wrong.のエラーが新しく発生しました。 less log/unicorn.stderr.logでunicornのログを確認したところ Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) (Mysql2::Error::ConnectionError)というエラーを確認しました。 データベースが起動していないのではないかという仮説が立ったので sudo systemctl status mariadbコマンドとsudo systemctl status nginx.serviceコマンドを実行し確認しましたが、mariadbとnginxはactive runningで起動していました。。 unicorn、nginx、mariadb全て起動していますが、ブラウザWe're sorry, but something went wrong.の状態です。。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問