how to create nework namespace in linux
to isolate the network resources of system define as network namespace.
1-network device
2-routing table
3-ipv4 $ ipv6
4-firewall rules
5-port number
6-/proc/net directory
the enviroment of system is a firest namespace
now we implement this structure:
on the vm :
# python3 -m http.server 8080
create namespace:
# ip netns add apple_ns
list of ns (namespace):
# ip netns list
delete namespace :
# ip netns delete apple_ns
start http server on namespace :
# ip netns exec apple_ns python3 -m http.server 8080
so as we see , we don't have port conflict in different namespace.
for checking network NIC of ns :
# ip netns exec apple_ns ip a s
now for checking webserver we can use use curl command but as you see with below command , loopback interface is down and we should up the interface
# ip netns exec apple_ns curl localhost:8080
# ip netns exec apple_ns ip link set dev lo up
# ip netns exec apple_ns ip a s
for connecting two interface , the solution is making virtual interface:
# ip link add dev host_veth type veth peer name apple_veth
# ip link list
we should transfer apple_veth interface to namespace:
# ip link set apple_veth netns aplle_ns
# ip netns exec apple_ns ip link list
now up the interface and assign ip :
# ip link set dev host_veth up
# ip address add 10.0.0.10/24 dev hsot_veth
# ip netns exec apple_ns ip link set dev apple_veth up
# ip netns exec apple_ns ip address add 10.0.0.11/24 dev apple_veth
# ip netns exec apple_ns ip a s
# ping 10.0.0.10 -c 4
# ping 10.0.0.11 -c 4
ping should be ok ✔️
# curl 10.0.0.11:8080
its ok ✔️
but we don't have google ping form apple namespace ✖️
# ip netns exec aplle_ns ip route add default via 10.0.0.10
# sysctl -w net.ipv4_ip_forward=1
# sysctl -p
# ip link list
now create rule on firewall to transfer traffic form virtual interface to real interface :
# iptables --append FORWARD --in-interface host_veth --out-interface enp0s7 --jump ACCEPT
# iptables --append FORWARD --in-interface enp0s7 --out-interface host_veth --jump ACCEPT
# iptables --append POSTROUTING --table nat --out-interface enp0s7 --jump MASQUERADE
now google ping from apple namespace is ok ✔️