How to change default port of a Rails 4 app?

前端 未结 5 517
礼貌的吻别
礼貌的吻别 2020-12-08 03:23

I know that I can start a rails server on another port via -p option. But I\'d like to setup another port per application as long as I start webrick.

An

相关标签:
5条回答
  • 2020-12-08 03:28

    For Rails 5.1:

    # config/boot.rb
    
    # ... existing code
    
    require 'rails/command'
    require 'rails/commands/server/server_command'
    
    Rails::Command::ServerCommand.send(:remove_const, 'DEFAULT_PORT')
    Rails::Command::ServerCommand.const_set('DEFAULT_PORT', 3333)
    
    0 讨论(0)
  • 2020-12-08 03:32

    Append this to config/boot.rb:

    require 'rails/commands/server'
    
    module DefaultOptions
      def default_options
        super.merge!(Port: 3001)
      end
    end
    
    Rails::Server.send(:prepend, DefaultOptions)
    

    Note: ruby >= 2.0 required.

    0 讨论(0)
  • 2020-12-08 03:35

    If you put the default options on config/boot.rb then all command attributes for rake and rails fails (example: rake -T or rails g model user)! So, append this to bin/rails after line require_relative '../config/boot' and the code is executed only for the rails server command:

    if ARGV.first == 's' || ARGV.first == 'server'
      require 'rails/commands/server'
      module Rails
        class Server
          def default_options
            super.merge(Host:  '0.0.0.0', Port: 3000)
          end
        end
      end
    end
    

    The bin/rails file loks like this:

    #!/usr/bin/env ruby
    APP_PATH = File.expand_path('../../config/application',  __FILE__)
    require_relative '../config/boot'
    
    # Set default host and port to rails server
    if ARGV.first == 's' || ARGV.first == 'server'
      require 'rails/commands/server'
      module Rails
        class Server
          def default_options
            super.merge(Host:  '0.0.0.0', Port: 3000)
          end
        end
      end
    end
    
    require 'rails/commands'
    
    0 讨论(0)
  • 2020-12-08 03:46

    Quick solution: Append to Rakefile

    task :server do
      `bundle exec rails s -p 8080`
    end
    

    Then run rake server

    0 讨论(0)
  • 2020-12-08 03:51

    Option 1:

    You can launch WEBrick like so:

        rails server -p 8080
    

    Where 8080 is your port. If you like, you can throw this in a bash script for convenience.

    Option 2:

    You could install $ gem install foreman, and use foreman to start your production webserver (e.g. unicorn) as defined in your Procfile like so: $ foreman run web. If unicorn is your web server you can specify the port in your unicorn config file (as with most server choices). The benefit of this approach is not only can you set the port in the config, but you're using an environment which is closer to production.

    0 讨论(0)
提交回复
热议问题