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 proxy
:
1 |
|
With the namespace created, the following syntax can be used to execute a command inside a network namespace:
1 |
|
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.
1 |
|
Verify the interface with ip a
Now assign the created macvlan interface to the namespace:
1 |
|
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:
1 |
|
Note that by default, the lo
interface is not up, means that you cannot use 127.0.0.1
or localhost
in the namespace by default. This can easily be fixed:
1 |
|
Now the IP address can be assigned to the macvlan interface:
1 |
|
Set the routing table and the namespace is ready to use:
1 |
|
Test:
1 |
|
The network namespace does not persist after boot, but to remove it manually:
1 |
|
I worte a script for easy creation. Usage: netns.sh <on|off>
1 |
|