Creating a new namespace is done with the ip netns
command
eg
ip netns add newnamespace
In order to let the namespace talk to the rest of the network it needs a veth endpoint inside the namespace. This basically creates a virtual “point to point” connection, and you can place one end inside the namespace and leave the other in the “root” namespace. Let’s call the two network points space-root and space-ns.
ip link add space-root type veth peer name space-ns
ip link set space-ns netns newnamespace
Now each interface needs an IP address. Let’s use the 192.168.200.0/24 network. And while we’re at it we can add a loopback and a default route inside the container.
ip addr add 192.168.200.1/24 dev space-root
ip link set space-root up
ip netns exec newnamespace ip addr add 192.168.200.2/24 dev space-ns
ip netns exec newnamespace ip link set space-ns up
ip netns exec newnamespace ip link set lo up
ip netns exec newnamespace ip route add default via 192.168.200.1
This will let the namespace talk to the parent. For it to see the rest of the network (or the internet) we need routes or NAT. In my use case ( https://www.sweharris.org/post/2023-04-29-netns-ip4only/ ) I only needed outgoing connections so I used NAT, which I was able to set up with iptables
echo 1 > /proc/sys/net/ipv4/ip_forward
# Enable masquerading of 192.168.200.0
iptables -t nat -A POSTROUTING -s 192.168.200.0/255.255.255.0 -o eth0 -j MASQUERADE
# Allow forwarding between eth0 and space-root
iptables -A FORWARD -i eth0 -o space-root -j ACCEPT
iptables -A FORWARD -o eth0 -i space-root -j ACCEPT
You can enter the namespace with ip netns exec
e.g.
$ sudo ip netns exec newnamespace ping -c 1 www.google.com
PING www.google.com (142.251.40.132) 56(84) bytes of data.
64 bytes from lga25s80-in-f4.1e100.net (142.251.40.132): icmp_seq=1 ttl=117 time=4.47 ms
--- www.google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 4.474/4.474/4.474/0.000 ms
Note this runs as root ('cos of the sudo) so you need to be aware of this and maybe drop permissions. Or create a wrapper program with cap_sys_admin
admins permission.