I have a second gateway in my network, and I want a specific program to use that gateway.
This can be achieved by using linux kernel feature: network namespace.
A network namespace is logically another copy of the network stack, with its own routes, firewall rules, and network devices.
My goal is to create a network namespace that uses the second gateway, and run my program within it.
Add a network namespace named
With the namespace created, the following syntax can be used to execute a command inside a network namespace:
However, the namespace does not have Internet connection yet, thus a virtual network interface (read more) must be created. Many tutorials I read descibe the method utilizing veth to create a NATed network, but the method would not work in my case, since the default gateway in a routing table must be direct connected. The namespace must be connected to the LAN appearing as a direct connected device. Macvlan bridge is the virtual interface type I prefered for this task. Note in macvlan bridge mode, host to client communication may not work.
Verify the interface with
Now assign the created macvlan interface to the namespace:
The interface is now moved to the
proxy and become invisible in the default namespace.
Before an IP address can be assigned to the interface, it must be brought up:
Note that by default, the
lo interface is not up, means that you cannot use
localhost in the namespace by default. This can easily be fixed:
Now the IP address can be assigned to the macvlan interface:
Set the routing table and the namespace is ready to use:
The network namespace does not persist after boot, but to remove it manually:
I worte a script for easy creation. Usage: