ActionCable не работает с nginx на облачном сервере

Я использую направляющие 5 для кабеля. Я разработал и протестировал приложение с actioncable на моем локальном компьютере (в среде разработки). Но когда я пытаюсь развернуть код на облачном сервере (например, в digitalocean). Actioncable внезапно перестает работать. Я использую Puma с nginx. Я попытался запустить сервер в режиме разработки, но он все еще не работает.

Мои файлы следующие: development.rb 'Rails.application.configure do # Указанные здесь настройки будут иметь приоритет над параметрами в config / application.rb.

# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false

# Do not eager load code on boot.
config.eager_load = false

config.action_cable.disable_request_forgery_protection = true

# Show full error reports.
config.consider_all_requests_local = true

config.action_mailer.default_url_options = { host: 'localhost:3000' }

# Rails.application.configure do 
#   config.action_cable.url = "ws://localhost:3000/cable"
# end 

config.action_cable.allowed_request_origins = ['webserver','webserver']
config.web_socket_server_url = "wss://webserver/cable" 


# Rails.application.configure do 
#   config.action_cable.url = "wss://webserver/cable"
# end 

# config.action_cable.allowed_request_origins = ['http://webserver']

# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true

config.cache_store = :memory_store
config.public_file_server.headers = {
  'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false

config.cache_store = :null_store
end

# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false

config.action_mailer.perform_caching = false

# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log

# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true

# Suppress logger output for asset requests.
config.assets.quiet = true
config.active_job.queue_adapter = :resque

# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true

# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end

файл nginx conf

    upstream app_server {
            server 127.0.0.1:3000;
    }

    server {
        listen   80;
        root /home/spot_me/public;
        server_name 165.227.186.52;
        index index.htm index.html;

        location / {
                try_files $uri/index.html $uri.html $uri @app;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
                        try_files $uri @app;
                }

         location @app {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                proxy_pass http://app_server;
        }

         location /cable {
            proxy_pass http://app_server/;
            proxy_http_version 1.1;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Proto http;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header X-Real-IP $remote_addr;
            proxy_read_timeout 86400;
            proxy_redirect off;
                }

    }

config / puma.rb

     Puma can serve each request in a thread from an internal thread pool.
    # The `threads` method setting takes two numbers a minimum and maximum.
    # Any libraries that use thread pools should be configured to match
    # the maximum value specified for Puma. Default is set to 5 threads for minimum
    # and maximum, this matches the default thread size of Active Record.
    #
    threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
    threads threads_count, threads_count

    # Specifies the `port` that Puma will listen on to receive requests, default is 3000.
    #
    port        ENV.fetch("PORT") { 3000 }

    # Specifies the `environment` that Puma will run in.
    #
    environment ENV.fetch("RAILS_ENV") { "development" }

    # Specifies the number of `workers` to boot in clustered mode.
    # Workers are forked webserver processes. If using threads and workers together
    # the concurrency of the application would be max `threads` * `workers`.
    # Workers do not work on JRuby or Windows (both of which do not support
    # processes).
    #
    # workers ENV.fetch("WEB_CONCURRENCY") { 2 }

    # Use the `preload_app!` method when specifying a `workers` number.
    # This directive tells Puma to first boot the application and load code
    # before forking the application. This takes advantage of Copy On Write
    # process behavior so workers use less memory. If you use this option
    # you need to make sure to reconnect any threads in the `on_worker_boot`
    # block.
    #
    # preload_app!

    # The code in the `on_worker_boot` will be called if you are using
    # clustered mode by specifying a number of `workers`. After each worker
    # process is booted this block will be run, if you are using `preload_app!`
    # option you will want to use this block to reconnect to any threads
    # or connections that may have been created at application boot, Ruby
    # cannot share connections between processes.
    #
    # on_worker_boot do
    #   ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
    # end

    # Allow puma to be restarted by `rails restart` command.
    plugin :tmp_restart

person dArK kNiGhT    schedule 19.09.2017    source источник


Ответы (1)


Nginx без сбоев работает с пассажирским сервером. Вы можете использовать сервер приложений для пассажиров, чтобы запустить приложение rails. Добавьте gem 'passenger' в свой Gemfile и запустите bundle install. Для запуска приложения используйте следующую команду: RAILS_ENV=production passenger start -p 3000

Также вы можете проверить следующие файлы / шаги в своем приложении:

  1. Убедитесь, что в вашем Gemfile есть gem 'redis', '~> 3.0'.
  2. config/cable.yml файл должен быть добавлен и должен иметь следующее содержимое:

    default: &default
    adapter: redis
      url: redis://localhost:6379/1
    
    development:
      <<: *default
    
    test:
      adapter: async
    
    production:
      adapter: redis
      url: redis://localhost:6379/1
    
  3. mount ActionCable.server => '/cable' добавить маршрут вверху файла маршрута.

  4. Добавить <%= action_cable_meta_tag %> в application.html.erb

  5. Добавьте следующие строки в application.js:

    +//= require cable
    +//= require_tree ./channels
    
  6. Перед запуском приложения rails убедитесь, что вы запустили сервер Redis. redis-server
person Community    schedule 19.09.2017
comment
На самом деле я использую Android как интерфейс, а не веб-страницу. Теперь проблема в том, что этот связанный метод метода connect channels / connection.rb вызывается, но я не могу вызывать подписки какого-либо объекта канала. Заранее спасибо. @vijaymmali - person dArK kNiGhT; 20.09.2017