Rails 4.2 Vagrant 上的服务器端口转发不起作用

Rails 4.2 Server port forwarding on Vagrant does not work

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

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

一切都已配置,如很多示例所示。

但是,当我尝试访问 http://localhost:3000 时,没有任何反应。我也尝试转发到其他随机端口,如 8081、25600,但没有成功。执行 curl 请求也不会得到任何东西(只是 Connection reset by the peer 消息),并且 VM 内的 curl 请求完美运行(如预期)。

我的 PC 和虚拟机都运行 Ubuntu 12.04。我正在使用 Ruby 2.2.0 和 Rails 4.2.0.

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

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

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

到特定端口上的 运行:

rails server -b 0.0.0.0 -p 8520

使用:

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

一起工作

你可以使用别名,在Ubuntu上把它放在~/.bash_aliases
我用:
alias rs="rails server -b 0.0.0.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 并 运行ning 后,我会 运行 bundle install 在我的项目存储库中,然后 rails server -b 0.0.0.0。 正如上面的链接答案所指出的:

127.0.0.1:3000 will only allow connections from that address on port 3000, whereas 0.0.0.0:3000 will allow connections from any address at port 3000.

Since Rails 4.2 only accepts connections from localhost by default, you can only access the server from localhost (eg. inside the VM); connections from another machine (eg. VM's host) will not work.