A network namespace is a logical copy of the network stack from the host system. This means that each namespace has its own IP addresses, network interfaces, routing tables, and so forth. Network namespaces are useful for setting up containers or virtual environments.
This documentation provides a step-by-step guide on how to create two network namespaces and connect them using a veth (Virtual Ethernet) cable. We'll also demonstrate how to ping from one namespace to another. This setup can be useful for network testing, container networking, or simulating network environments. Let's get started!
Before proceeding, ensure that you have the following requirements:
- A Linux-based operating system (e.g., Ubuntu, CentOS)
- Root or sudo access on your machine
- Basic knowledge of Linux networking and terminal commands
Namespaces allow us to create isolated network environments. In this example, we'll create two namespaces: red and green. Follow these steps:
-
Open a terminal or shell.
-
Create the first namespace red using the ip command:
sudo ip netns add red
-
Create the second namespace green:
sudo ip netns add green
-
Show created namespaces
sudo ip netns
The veth cable is a virtual Ethernet cable that connects two namespaces. We'll create a pair of veth interfaces and assign each end to a different namespace:
-
Create the veth pair rveth and gveth:
sudo ip link add rveth type veth peer name gveth
-
Connect gveth to green and rveth to red:
sudo ip link set rveth netns red sudo ip link set gveth netns green
-
Bring up the loopback & virthual ethernet interface within the red namespace:
sudo ip netns exec red bash ip link set dev lo up ip link set dev rveth up
-
In red, assign an IP address to rveth:
ip addr add 192.168.1.1 dev rveth
-
Bring up the loopback & virthual ethernet interface within the green namespace:
sudo ip netns exec red bash ip link set dev lo up ip link set dev rveth up
-
In green, assign an IP address to gveth:
ip addr add 192.168.1.2 dev gveth
-
Add route table to assign ip into the corresponding interface. The kernel uses it to determine how to forward network packets to their destination.
-
In red namespace :
ip route add 192.168.1.2 dev rveth ip route
-
In green namespace :
ip route add 192.168.1.1 dev gveth ip route
-
ping
sudo ip netns exec red ping 192.168.1.2 sudo ip netns exec green ping 192.168.1.1
If the ping is successful, you should see responses indicating a successful connection.
We have successfully created two namespaces and connected them using a veth cable. We have also tested the connectivity by pinging between the namespaces.
-