Linux Network Namespace: Create an Isolated Network Stack

Quick Linux Tip #129:

Question: How do I run a command with its own isolated network stack?

Try: sudo ip netns add isolated && sudo ip netns exec isolated ip link set lo up

Info: Isolates network stacks for sandboxing or testing.

Examples:

  • $ sudo ip netns exec isolated bash  # Open an interactive shell inside the namespace
  • $ sudo ip netns del isolated  # Delete the network namespace when finished
  • $ sudo unshare -n bash  # Create an ephemeral isolated network namespace

Note: Add veth pairs if the namespace needs external network access—the same building block behind container networking. Unlike persistent ip netns entries, unshare -n ties namespace lifetime to the running process.




LinuxTeck.com
linuxteck:~$ sudo ip netns add isolated && sudo ip netns exec isolated ip link set lo up

linuxteck:~$ sudo ip netns list
isolated

linuxteck:~$ sudo ip netns exec isolated ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever

linuxteck:~$ sudo ip netns exec isolated curl https://google.com
curl: (6) Could not resolve host: google.com

linuxteck:~$ sudo ip netns exec isolated python3 -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...
linuxteck:~$

PREVIOUS ARTICLE Quick Linux Tip #128: ShellCheck Bash Script: Find Bugs and Security Issues in Linux NEXT ARTICLE Quick Linux Tip #130: HTTPie API Debugging: Test and Inspect HTTP Requests
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.