46

我有一个安装了 Rails 的 Vagrant VM 和示例应用程序。虚拟机配置为将端口 3000(Rails Webrick 服务器的)转发到我的主机 3000 端口。

config.vm.network "forwarded_port", guest: 3000, host: 3000

一切都按照许多示例进行配置。

但是,当我尝试访问时,http://localhost:3000什么也没有发生。我也尝试转发到其他随机端口,如 8081、25600,但没有成功。执行 curl 请求也不会得到任何东西(只是对等消息重置连接),并且 VM 内部的 curl 请求可以正常工作(如预期的那样)。

我的 PC 和 VM 都运行 Ubuntu 12.04。我正在使用 Ruby 2.2.0 和 Rails 4.2.0。

重要的一点是 Apache 工作正常。我将端口 80 转发到端口 8080,一切正常。似乎问题出在 Rails 服务器上,即使我使用其他端口(rails server -p 4000例如)

4

5 回答 5

91

Rails 4.2 现在默认绑定到127.0.0.1而不是0.0.0.0.

使用启动服务器bin/rails server -b 0.0.0.0,它应该对其进行排序。

于 2015-01-06T13:12:30.007 回答
10

在特定端口上运行:

rails server -b 0.0.0.0 -p 8520
于 2015-01-20T11:58:01.097 回答
4

使用

rails s -b 0.0.0.0

或者

添加config/boot.rb

require 'rails/commands/server'

module Rails
  class Server
    new_defaults = Module.new do
      def default_options        
        default_host = Rails.env == 'development' ? '0.0.0.0' : '127.0.0.1'
        super.merge( Host: default_host )
      end
    end

    # Note: Module#prepend requires Ruby 2.0 or later
    prepend new_defaults
  end
end

并与rails s

于 2015-07-10T09:42:16.363 回答
0

在这里找到了非常好的解释:Rails 4.2.0.beta2 - Can't connect to LocalHost?

我遇到了完全相同的问题,只是我的 PC 是 Mac 机器。我已经使用这个 vagrantfile 来让它工作(使用 virtualbox 4.3.36)

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  # Use Ubuntu 14.04 Trusty Tahr 64-bit as our operating system
  config.vm.box = "ubuntu/trusty64"

  # Configurate the virtual machine to use 2GB of RAM
  config.vm.provider :virtualbox do |vb|
    vb.customize ["modifyvm", :id, "--memory", "2048"]
  end

  config.vm.provision "shell", inline: <<-SHELL
    ## Install necessary dependencies
    sudo apt-get --assume-yes install libsqlite3-dev libcurl4-openssl-dev git

    ## Install GPG keys and download rvm, ruby and rails
    curl -sSL https://rvm.io/mpapis.asc | gpg --import -
    curl -L https://get.rvm.io | bash -s stable --ruby
    curl -L https://get.rvm.io | bash -s stable --rails
    echo "[[ ls \"$HOME/.rvm/scripts/rvm\" ]] && . \"$HOME/.rvm/scripts/rvm\"" >> ~/.profile
    ## Adding vagrant user to the group that can access rvm
    usermod -G rvm vagrant
  SHELL

  # Forward the Rails server default port to the host
  config.vm.network :forwarded_port, guest: 3000, host: 3000

end

启动并运行 VM 后,我将bundle install在我的项目 repo 中运行,然后rails server -b 0.0.0.0. 正如上面链接的答案中所指出的:

127.0.0.1:3000 将只允许来自该地址在端口 3000 上的连接,而 0.0.0.0:3000 将允许来自任何地址在端口 3000 上的连接。

由于 Rails 4.2 默认只接受来自 localhost 的连接,因此您只能从 localhost 访问服务器(例如,在 VM 内部);来自另一台机器(例如 VM 的主机)的连接将不起作用。

于 2016-03-23T20:39:50.840 回答
0

您可以使用别名,在 Ubuntu 上将其放入~/.bash_aliases
I use:
alias rs="rails server -b 0.0.0.0"

You have to reload the terminal before you can use it

于 2015-08-24T17:24:22.613 回答