Bind rails server to 127.0.0.1 by default

…衆ロ難τιáo~ 提交于 2020-05-26 10:27:42

问题


I'd like to bind the rails server to 127.0.0.1, instead of 0.0.0.0 so its not accessible when I'm working from coffee shops.

Is there a configuration file where I can specify this option so I don't have to pass the command line switch:

rails server -b 127.0.0.1

?


回答1:


If you are searching for Rails 5: Answer


In Rails ~> 4.0 you can customize the boot section of the Server class:

In /config/boot.rb add this lines:

require 'rails/commands/server'

module Rails
  class Server
    def default_options
      super.merge({Port: 10524, Host: '127.0.0.1'})
    end
  end
end

As already answered on this questions:

How to change Rails 3 server default port in develoment?

How to change the default binding ip of Rails 4.2 development server?




回答2:


You can make a bash script to just run the command by default:

#!/bin/bash
rails server -b 127.0.0.1

Put it in the same folder as your project, name it anything you want (e.g. devserv), then

chmod +x devserv

And all you have to do is ./devserv




回答3:


I use Foreman as a process manager in development.

After adding gem 'foreman' to your Gemfile and running bundle install, create a file Procfile in the root of your application directory.

While you can add lines to manage other processes, mine just reads:

web: rails server -p $PORT -b 127.0.0.1

Then, to start the Rails server via the Procfile, run foreman start. If you have other processes here (Redis, workers) they'll boot at the same time.




回答4:


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:  '127.0.0.1', Port: 10524)
      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:  '127.0.0.1', Port: 10524)
      end
    end
  end
end

require 'rails/commands'


来源:https://stackoverflow.com/questions/29945850/bind-rails-server-to-127-0-0-1-by-default

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