This blog is running from an OpenVZ container on a server with a single public IP. There is no separate router; the eth0 interfaces is connected directly to the Internet. Therefore, I had to create a vlan with private IPs for my containers which would share the one public IP. Here’s how I did it.
/etc/network/interfaces
auto eth0
iface eth0 inet static
address x.x.x.x
netmask 255.255.255.254
gateway x.x.x.x
auto venet0:0
iface venet0:0 inet static
address 172.29.247.100
netmask 255.255.255.0
Note that the venet0 interface is created when installing OpenVZ. By default it has no IP. I assigned a static IP of 172.29.247.100 and netmask of 255.255.255.0 to allow space for a whole lot of containers. Now for the fun part, messing with iptables.
# NAT VM subnet (247) to external ip
/sbin/iptables -t nat -A POSTROUTING -s 172.29.247.0/24 -o eth0 -j SNAT --to x.x.x.x
# Allow all traffic for venet0 interface
/sbin/iptables -A INPUT -i venet0 -j ACCEPT
# ssh to containers
/sbin/iptables -t nat -I PREROUTING -p tcp -d x.x.x.x --dport 2222 -j DNAT --to 172.29.247.103:22
/sbin/iptables -I FORWARD -p tcp -d 172.29.247.103 --dport 2222
/sbin/iptables -t nat -I PREROUTING -p tcp -d x.x.x.x --dport 2223 -j DNAT --to 172.29.247.102:22
/sbin/iptables -I FORWARD -p tcp -d 172.29.247.102 --dport 2223
It may not be the optimal solution, but it works, it’s stable, and I’m quite proud of myself.
