Skip to content

Instantly share code, notes, and snippets.

@BattleBrisket
Last active September 9, 2015 10:33
Show Gist options
  • Save BattleBrisket/234ee8a366c47820f3c4 to your computer and use it in GitHub Desktop.
Save BattleBrisket/234ee8a366c47820f3c4 to your computer and use it in GitHub Desktop.
Revert WEBrick bind address in Rails 4

Rails changed the default behavior for WEBrick somewhere around version 4. Instead of binding to 0.0.0.0, it will now default to localhost.

This makes life difficult when you're running Rails inside a VM like Vagrant, mostly because it won't work. ;)

Fortunately, you can force Rails back into the old universal address with the following snippet

# config/boot.rb

# ... end of existing file

require 'rails/commands/server'
# Enforce WEBrick classic port and host
module Rails
  class Server
    def default_options
      super.merge(Host: '0.0.0.0', Port: 3000)
    end
  end
end

This way you can continue to simply call rails server without having to addthe extra -b parameter.

Be sure to leave the port assignment in there; our tests indicate that changing the default host causes the port to break in weird ways (we got a default port assignment of 9292).

@phlegx
Copy link

phlegx commented Sep 9, 2015

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'

See http://stackoverflow.com/a/32476858/132235

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment