在这里找到了非常好的解释: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 的主机)的连接将不起作用。