How to remove all network namespaces at once on Linux

Last updated on July 13, 2020 by Dan Nanni

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.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean