Course contentsShow
← Linux
Lesson 546 of 1,8195. Process Management and SignalingFree lesson

Namespace Persistence and Lifetimes

Manage the lifecycle of namespaces independently of the processes inside them.

In this lesson, you will learn how to keep a Linux namespace alive even after every process inside it has finished executing.

Normally, when the last process associated with a namespace terminates, the Linux kernel automatically destroys that namespace to reclaim resources. This is efficient for transient tasks, but it poses a problem if you want to configure a network interface or mount a filesystem in a "container" and keep that environment waiting for later use.

Binding Namespaces to the Filesystem

To prevent a namespace from vanishing, you must create a persistent reference to it in the filesystem. This is achieved by "bind-mounting" a special file located in /proc/[pid]/ns/ to a permanent location, such as a file in /var/run/netns/ or /etc/netns/.

When you bind-mount a namespace file, you are essentially telling the kernel: "Hold onto this namespace object even if no processes are currently using it." As long as that mount point exists, the namespace remains active.

A Practical Example

Imagine you want to keep a Network Namespace alive for a background service that hasn't started yet:

  1. Create a mount point: touch /var/run/my_ns
  2. Bind the existing namespace to it: mount --bind /proc/1234/ns/net /var/run/my_ns

Even if process 1234 crashes or exits, the network namespace defined by that process will persist because the file /var/run/my_ns holds a reference to it. You can later join this namespace using nsenter to verify its state or launch new processes into it.

Cleaning Up

Because the kernel keeps the namespace alive based on these references, the namespace will not be garbage-collected until you explicitly remove the bind mount. You do this by unmounting the file:

umount /var/run/my_ns

Once the last reference (the file mount) is removed, the kernel detects that no processes or files are using the namespace and immediately cleans it up. This separation between the process lifecycle and the namespace lifecycle allows you to decouple your infrastructure setup from your application execution.

Key Takeaway: By bind-mounting a namespace file from /proc to a persistent location in the filesystem, you can maintain a namespace’s state indefinitely, independent of the processes running within it.