OpenVPN in a network namespace

Everyone seems to be using different solutions which don't work for me. I ended up creating a script which works on my Ubuntu 14.04, and turned it into a node.js library, open-tune.

Here's the TL;DR of how it started.

Create a script file up.js

If you want to use anything else, i.e. pure command line, just replace the variables in my script with your params.

Run openvpn
openvpn --script-security 2 --topology subnet --ifconfig-noexec --route-noexec --route-up /path/to/up.js  

---script-security 2 to allow running node.js from our script

--topology subnet is default in versions >= 2.4, i was using 2.3

--ifconfig-noexec to prevent openvpn from creating the tunnel in the default namespace, we will create it in our separate namespace

--route-noexec to prevent openvpn from creating the routes in the default namespace and routing table

--route-up /path/to/up.js to specify which script to execute once the connection is established

Note that at this point, you have a working internet connection. DNS resolution will probably not work inside the namespace if you're using network-local DNS servers, since it is no longer accessible.