Поиск и устранение неисправностей Rails nginx + Пассажир 500 ошибка - PullRequest
0 голосов
/ 19 октября 2018

Я пытаюсь выяснить, почему nginx возвращает 500 Internal Server Error.Первоначально у меня было это приложение, работающее в автономном режиме с Passenger, но я намереваюсь разместить несколько других приложений сейчас, и я не могу пройти через это приложение, используя nginx для обслуживания запросов.Я могу запустить приложение с WEBrick, но сейчас это совсем не пойдет на достижение поставленных целей.

Я не использую capistrano или какие-либо другие типы автоматических сборщиков,и это работает на линоде VPS.Он работал нормально около десяти месяцев назад, до того как Линод перезагрузил аппаратное обеспечение, а после этой перезагрузки он был мертв.Это было около 10 месяцев назад, поэтому перед тем, как отправиться в это путешествие, я обновил все пакеты в системе на случай, если это как-то повлияет на проблему.

Вот что я получаю при попытке запустить приложение:

$ bundle exec passenger start
Unable to autodetect the currently active RVM gem set name. This could happen if you ran this program using 'sudo' instead of 'rvmsudo'. When using RVM, you're always supposed to use 'rvmsudo' instead of 'sudo!'.

Please try rerunning this program using 'rvmsudo'. If that doesn't help, please contact this program's author for support.

Вот мое окружение:

$ cat /proc/version
Linux version 4.18.8-x86_64-linode117 (maker@build.linode.com) (gcc version 4.9.2 (Debian 4.9.2-10+deb8u1)) #1 SMP PREEMPT Tue Sep 18 18:48:25 UTC 2018

$ rvm list
=* ruby-2.5.1 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

$ rails -v
Rails 5.0.1

$ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]

$ bundle -v
Bundler version 1.16.2

$ gem -v
2.7.7

nginx.conf:

# cat /etc/nginx/nginx.conf 
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Phusion Passenger config
    ##
    # Uncomment it if you installed passenger or passenger-enterprise
    ##

    # include /etc/nginx/passenger.conf;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

# cat /etc/nginx/conf.d/mod-http-passenger.conf 
passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
#passenger_ruby /usr/bin/passenger_free_ruby;
passenger_ruby /home/deploy/.rvm/rubies/ruby-2.5.1/bin/ruby;


# cat /etc/nginx/sites-available/site 
server {
    listen 80 default_server;
    server_name site.com www.site.com;
    passenger_ruby /home/deploy/.rvm/gems/ruby-2.5.1/wrappers/ruby;
    passenger_enabled on;
    root /var/www/site/code/public;
    rails_env production;

        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
        add_header X-Frame-Options DENY;                # prevents page from being embedded in other pages
        add_header X-Content-Type-Options nosniff;      # prevents MIME type sniffing
        add_header X-XSS-Protection "1; mode=block";    # prevents XSS rendering
        add_header X-Robots-Tag none;                   # prevents robots from crawling the requested page
        add_header Pragma "no-cache";                   # don't store a cached version of the site resources
        add_header Cache-Control "no-cache";            # don't store a cached version of the site resources
        add_header X-uri "$uri";                        # requested URI
        add_header Access-Control-Allow-Origin *;       # required for Google fonts (CORS strikes again)
    }
}

pg_hba.conf

# cat /etc/postgresql/9.4/main/pg_hba.conf 
# PostgreSQL Client Authentication Configuration File
# ===================================================
#
# Refer to the "Client Authentication" section in the PostgreSQL
# documentation for a complete description of this file.  A short
# synopsis follows.
#
# This file controls: which hosts are allowed to connect, how clients
# are authenticated, which PostgreSQL user names they can use, which
# databases they can access.  Records take one of these forms:
#
# local      DATABASE  USER  METHOD  [OPTIONS]
# host       DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostssl    DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostnossl  DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
#
# (The uppercase items must be replaced by actual values.)
#
# The first field is the connection type: "local" is a Unix-domain
# socket, "host" is either a plain or SSL-encrypted TCP/IP socket,
# "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a
# plain TCP/IP socket.
#
# DATABASE can be "all", "sameuser", "samerole", "replication", a
# database name, or a comma-separated list thereof. The "all"
# keyword does not match "replication". Access to replication
# must be enabled in a separate record (see example below).
#
# USER can be "all", a user name, a group name prefixed with "+", or a
# comma-separated list thereof.  In both the DATABASE and USER fields
# you can also write a file name prefixed with "@" to include names
# from a separate file.
#
# ADDRESS specifies the set of hosts the record matches.  It can be a
# host name, or it is made up of an IP address and a CIDR mask that is
# an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that
# specifies the number of significant bits in the mask.  A host name
# that starts with a dot (.) matches a suffix of the actual host name.
# Alternatively, you can write an IP address and netmask in separate
# columns to specify the set of hosts.  Instead of a CIDR-address, you
# can write "samehost" to match any of the server's own IP addresses,
# or "samenet" to match any address in any subnet that the server is
# directly connected to.
#
# METHOD can be "trust", "reject", "md5", "password", "gss", "sspi",
# "ident", "peer", "pam", "ldap", "radius" or "cert".  Note that
# "password" sends passwords in clear text; "md5" is preferred since
# it sends encrypted passwords.
#
# OPTIONS are a set of options for the authentication in the format
# NAME=VALUE.  The available options depend on the different
# authentication methods -- refer to the "Client Authentication"
# section in the documentation for a list of which options are
# available for which authentication methods.
#
# Database and user names containing spaces, commas, quotes and other
# special characters must be quoted.  Quoting one of the keywords
# "all", "sameuser", "samerole" or "replication" makes the name lose
# its special character, and just match a database or username with
# that name.
#
# This file is read on server startup and when the postmaster receives
# a SIGHUP signal.  If you edit the file on a running system, you have
# to SIGHUP the postmaster for the changes to take effect.  You can
# use "pg_ctl reload" to do that.

# Put your actual configuration here
# ----------------------------------
#
# If you want to allow non-local connections, you need to add more
# "host" records.  In that case you will also need to make PostgreSQL
# listen on a non-local interface via the listen_addresses
# configuration parameter, or via the -i or -h command line switches.




# DO NOT DISABLE!
# If you change this first entry you will need to make sure that the
# database superuser can access the database using some other method.
# Noninteractive access to all databases is required during automatic
# maintenance (custom daily cronjobs, replication, and similar tasks).
#
# Database administrative login by Unix domain socket
local   all             postgres                                peer
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5

site-enabled/ имеет символические ссылки на файлы конфигурации в sites-available/.

Я получаю следующее, и все же единственная причина, по которой я попытался выполнить эту команду, заключалась в устранении ошибки, на которую она жалуется.

$ passenger-config compile-agent --force
Checking for required software...

 * Checking for C compiler...
      Found: yes
      Location: /usr/bin/cc
 * Checking for C++ compiler...
      Found: yes
      Location: /usr/bin/c++
Unable to autodetect the currently active RVM gem set name. This could happen if you ran this program using 'sudo' instead of 'rvmsudo'. When using RVM, you're always supposed to use 'rvmsudo' instead of 'sudo!'.

Please try rerunning this program using 'rvmsudo'. If that doesn't help, please contact this program's author for support.

Проверка /var/log/ngingx/error.log показывает мне:

App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] Started GET "/" for [REDACTED] at 2018-10-18 19:18:43 -0700
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] Processing by PagesController#home as HTML
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]   Rendering pages/home.html.erb within layouts/application
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]   Rendered shared/_tweets.html.erb (1.2ms)
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]   Rendered pages/home.html.erb within layouts/application (10.9ms)
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]   Rendered shared/_application_nav.html.erb (20.4ms)
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] Completed 500 Internal Server Error in 541ms
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]   
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] ActionView::Template::Error (FATAL:  Peer authentication failed for user "[REDACTED]"
App 26325 output: ):
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]     3:     <h3 class="masthead-brand">Site Name</h3>
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]     4:     <nav class="nav nav-masthead">
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]     5:       <%= nav_generator 'nav-link', 'span' %>
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]     6:       <%= login_helper 'nav-link' %>
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]     7:     </nav>
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]     8:   </div>
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]     9: </div>
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158]   
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] app/models/concerns/current_user_concern.rb:9:in `guest_user'
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] app/models/concerns/current_user_concern.rb:5:in `current_user'
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] app/helpers/application_helper.rb:3:in `login_helper'
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] app/views/shared/_application_nav.html.erb:6:in `_app_views_shared__application_nav_html_erb___1001043723099543592_69980262645600'
App 26325 output: [d3f637be-1308-4fdc-ad97-d0476633b158] app/views/layouts/application.html.erb:48:in `_app_views_layouts_application_html_erb__4053957196745232794_40927140'

Уже упомянутая документация:

Не удается запустить сторожевой таймер Phusion Passenger?

https://www.phusionpassenger.com/library/walkthroughs/start/ruby.html#bundle-exec-rails-server

https://www.phusionpassenger.com/library/admin/nginx/troubleshooting/ruby/#first-things-to-try

https://www.reddit.com/r/rails/comments/4i0m8j/migrate_from_webrick_to_phusion_passenger/

https://serverfault.com/questions/362697/nginx-passenger-returning-500s-for-every-request

https://medium.com/@maciejmensfeld/ruby-2-5-0-upgrade-remarks-100d7c0dd73d

https://www.linode.com/docs/development/ror/ruby-on-rails-nginx-debian/

Я знаю, что забыл некоторую дополнительную информацию, которая может помочь, поэтому, если у вас есть идея и вам нужно больше деталей, дайте мне точно знать, что вам нужно, и я получу обновлениеост.Спасибо за любую помощь!

1 Ответ

0 голосов
/ 19 октября 2018

Peer authentication failed for user "[REDACTED]"

Это похоже на проблему аутентификации базы данных.У вас есть правильная настройка переменных среды, чтобы вы могли подключаться с rails к вашей базе данных И настройка pg_hba.conf для обеспечения правильной аутентификации?

Примечание: если это так, вы можете рассмотреть возможность ужесточения, чтобы не быть равноправной аутентификацией и использовать что-то сильное.https://www.postgresql.org/docs/9.3/static/auth-methods.html

...