Virtualizing your servers is pretty cool. But having a server in a hosted environment brings some restrictions with networking. To get around this, you can use a virtual network and configure some internal routing.
Enabling routing
To route our network we use IP-Forward. But as it is usually disabled, we have to first enable it.
1 |
echo '1' > /proc/sys/net/ipv4/ip_forward ; |
Forwarding packets
You can either forward all packets directed a specific ip address or only the ones targeting a given port. In the following example, all packets targeting the external address 123.123.123.10 will be forwarded to the internal address 192.168.1.11.
1 |
iptables -t nat -A PREROUTING -d 123.123.123.10 -j DNAT --to-destination 192.168.1.11 |
Forward only tcp packets from the external port 80 to the internal port 8080.
1 |
iptables -t nat -A PREROUTING -p tcp -d 123.123.123.10 --dport 80 -j DNAT --to-destination 192.168.1.11:8080 |
Changing internal to external ip address
Now having your VMs connect to the outer world or sending responses, you probably don’t want the internal but the external address exposed. In this example, the address within the packet will be changed from the internal 192.168.1.11 to the external 123.123.123.10 when leaving the network over the interface eth0.
1 |
iptables -t nat -A POSTROUTING -o eth0 -j SNAT -s 192.168.1.11 --to 123.123.123.10 |
Blocking requests to certain ports
IP tables also offers the possibility to block certain ports. In the following example, all requests to an FTP server (port 21) on network interface eth0 will be dropped.
1 |
iptables -A INPUT -i eth0 -p tcp --destination-port 21 -j DROP |
Saving the rules
In order to store the configured iptables settings permanently, you simply have to run the following command.
1 |
iptables-save |