How to remove all network namespaces at once on Linux

Question: I have created a number of network namespaces, and now I want to remove them all. Is there a way to delete all existing network namespaces at once from the command line on Linux?

In Linux, the concept of "namespaces" was introduced as a way to isolate system resources among different groups of processes. As one of six different types of Linux namespaces, network namespaces logically isolate system resources associated with networking (e.g., network devices, IP addresses, routing table) among different process groups, thereby giving each process group a different view of the host network stack. This feature is popularly used for operating system-level virtualization.

Linux network namespaces can be created and removed by the ip command as follows.

$ sudo ip netns add <namespace-name>
$ sudo ip netns del <namespace-name>

Suppose you want to clean up all existing namespaces on your Linux system. Of course you can delete each namespace one by one with the above ip command, but this may be cumbersome. Here is how to remove all network namespaces from the command line.

Method One

The ip command comes from the iproute2 package. The latest iproute2 package allows the ip command to execute a specified action for all objects (e.g., for all existing namespaces). For this, it offers "-all" option.

For example, on Ubuntu 15.10 or Fedora 23, the ip command can remove all namespaces in one shot with "-all" option.

$ sudo ip -all netns delete

However, if your Linux system does not have the compatible iproute2 package installed, you will encounter the following error.

Option "-all" is unknown, try "ip -help".

Method Two

For those of you who do not have the latest iproute2 package installed, you can delete all network namespaces using a combination of xargs and ip as follows.

$ ip netns | xargs -I {} sudo ip netns delete {}

Basically you pipe the multi-line namespace list to xargs, which will then run the ip command for each namespace.

Download this article as ad-free PDF (made possible by your kind donation): 
Download PDF

Subscribe to Ask Xmodulo

Do you want to receive Linux related questions & answers published at Ask Xmodulo? Enter your email address below, and we will deliver our Linux Q&A straight to your email box, for free. Delivery powered by Google Feedburner.


Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

Leave a comment

Your email address will not be published. Required fields are marked *