How to change default port of a Rails 4 app?

夙愿已清 提交于 2019-11-28 04:43:27

Quick solution: Append to Rakefile

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

Then run rake server

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.

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.

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'

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!