Public static ip for vagrant box

Solution 1:

Since release 1.3.0:

Static IP can now be set on public networks. [GH-1745]

you just have to put this configuration in your Vagrantfile (documentation):

config.vm.network "public_network", ip: "192.168.0.200"

This Vagrant thing is really great :-)

Solution 2:

After two weeks, I resolved my question this way:

  • Wrote vagrant-boxes cookbook: https://github.com/numbata/cookbook-vagrant
  • Wrote rebuild-iptables with nat support. https://github.com/numbata/rebuild-iptables

Cookbook generates Vagrantfile from template:

Vagrant::Config.run do |config|
  config.vm.define :gitlab do |box_config|
    box_config.vm.box = "mybox"
    box_config.vm.host_name = "mybox"
    box_config.vm.forward_port 80, 4567
    box_config.vm.forward_port 22, 2222
    box_config.vm.network :hostonly, "192.168.5.10"
  end
end

rebuild-iptables needs to generate and apply iptables rules:

# /etc/iptables/general
*filter
:INPUT ACCEPT [0,0]
:FORWARD ACCEPT [0,0]
:OUTPUT ACCEPT [0,0]
# Vagrand boxes forwarding ports
-A FORWARD -p tcp -d 192.168.5.10 --dport 80 -j ACCEPT
-A FORWARD -p tcp -d 192.168.5.10 --dport 22 -j ACCEPT
COMMIT
*nat
:PREROUTING ACCEPT [0,0]
:POSTROUTING ACCEPT [0,0]
:OUTPUT ACCEPT [0,0]
# Nat all traffic to vagrant boxes
# For example, my vagrant box public static ip is 8.8.8.8
-A PREROUTING -d 8.8.8.8 -p tcp -j DNAT --to-destination 192.168.5.10
-A POSTROUTING -j MASQUERADE
COMMIT

And:

echo '1' > /proc/sys/net/ipv4/ip_forward

Now, i can install applications to the box and connect to them over public static ip without "port_forwarding" setup (Like on VPS).