Rails 4.2 Server port forwarding on Vagrant does not work

后端 未结 5 1184
感情败类
感情败类 2020-12-22 22:44

I have a Vagrant VM with Rails installed with a sample app. The VM is configured to forward the port 3000 (of Rails Webrick server) to my host 3000 port.

co         


        
5条回答
  •  无人及你
    2020-12-22 23:20

    Really nice explanation found here: Rails 4.2.0.beta2 - Can't connect to LocalHost?

    I had exactly the same problem, with the exception that my PC is Mac machine. I've used this vagrantfile to get it working (with 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
    

    after having the VM up and running, I would run bundle install in my project repo and then rails server -b 0.0.0.0. As pointed out in linked answer above:

    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.

提交回复
热议问题