vagrantvagrantfilehostsvirtual-hostsvagrant-provision

vagrant /etc/hosts: machine IP vs localhost


I have a vagrant machine setup with this IP address:

Vagrant.configure("2") do |config|
    config.vm.network :private_network, ip: 192.168.33.11
    config.vm.network "forwarded_port", guest: 80, host: 8080
    config.vm.hostname = "my-devenv"
...
end

Everything works just fine. But I am confused on the /etc/hosts file on the VM: What is the difference between using localhost and VM's IP (127.0.0.1 some-dev-site.dev vs 192.168.33.11 some-dev-site.dev)?

127.0.0.1 localhost
127.0.0.1 some-dev-site.dev
192.168.33.11 some-dev-site.dev

Solution

  • General

    The localhost is normally always the same on different machines: 127.0.0.1 (local loopback) and the VM IP is the external IP on the 'network'. You can for example connect from your machine to your VM by accessing the VM IP, but if you connect to localhost from your machine to the VM, you end up on your own machine.

    If you bind a service to 127.0.0.1 you will not be able to reach it from 'outside' of the 'machine'.

    This offers probably a better explanation if you want to read more: https://www.lifewire.com/network-computer-special-ip-address-818385

    More specific to your situation

    Not sure if I understood your question correctly, but I guess your question is about: what are the hostnames in the /etc/hosts of your virtual machine? That is because they don't exist in the DNS and if you are connecting to these hosts it needs to end up at the right place and that, in this case is the VM itself.