OpenVPN Internet Routing on OpenVZ VPS

As far as I know, the iptables masquerade module is not compatible with OpenVZ. As a result, many guides online on how to route all traffic through an OpenVPN Tunnel do not work with OpenVZ, as they depend on the masquerade module of iptables. This IPTables rule:

iptables -t nat -A POSTROUTING -o venet0 -j SNAT --to-source XXX.XXX.XXX.XXX

where XXX.XXX.XXX.XXX is your VPS’s EXTERNAL IP ADDRESS

can be used instead. You can add these lines to your /etc/rc.local file so that they are run at boot. You will also need to edit your /etc/sysctl.conf file, and uncomment this line:

#net.ipv4.ip_forward=1

by removing the #, so that it looks like this:

net.ipv4.ip_forward=1

to enable ip forwarding. Since this file is loaded at boot, you can enable IP Forwarding on the fly by running:

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

through the command line.

I hope that this has helped someone – I know that I had to look through several guides online before I managed to get it working.

8 thoughts on “OpenVPN Internet Routing on OpenVZ VPS

  1. Thanks very much!!! I was on the brink of giving up and finally after typing those iptables commands for my OpenVZ VPS , it’s working like magic!

    Darn.. there were so many different commands out there but they didn’t specify whether it’s for OpenVZ or not.

    For those who have problems accessing Internet after configuring traffic to route over the VPN… restart your iptables (to flush whatever junk you entered before) and then enter those commands above.

    I finally got OpenVPN to work on a CentOS 5 OpenVZ VPS!

    1. Hi Kevin,

      Glad it’s working for you. I think most guides assume you’re running on a dedicated box (or on a fully virtualised machine).

  2. Another tip: Make sure you use venet0, not venet0:0, even if the latter is the interface that is actually assigned your server’s IP address. That stumped me for weeks while I was trying to get this working.

Leave a Reply

Your email address will not be published. Required fields are marked *