Course contentsShow
← Linux
Lesson 1470 of 1,81913. Containerization Primitives and NamespacesFree lesson

Namespace Persistence and Lifecycles

Manage the persistence of namespaces even when no child processes remain attached.

In this lesson, you will learn how to maintain a Linux namespace in an active state even after all processes belonging to it have terminated.

The Problem: Namespace Ephemerality

By default, Linux namespaces are transient. When you create a namespace (like a Network or Mount namespace) and start a process inside it, the kernel tracks the namespace's reference count. As long as at least one process remains in that namespace, or a file descriptor remains open to its entry in /proc/[pid]/ns/, the namespace persists. Once the final process exits and all descriptors are closed, the kernel garbage-collects the namespace, destroying any state—such as virtual network interfaces or specific mount points—associated with it.

The Solution: Bind Mounting

To keep a namespace alive, you must "pin" it to the filesystem. The kernel allows you to bind-mount the specific namespace file from the /proc filesystem to a regular file on your disk. Because a mount point acts as a reference, the kernel will not destroy the namespace even if all associated processes terminate.

For example, to persist a network namespace even after your containerized process exits:

  1. Create a persistent file: touch /var/run/netns/my_namespace
  2. Mount the namespace into that file:
    # Assuming you have a process PID in the target namespace
    mount --bind /proc/PID/ns/net /var/run/netns/my_namespace
    

Managing the Lifecycle

Once you have bind-mounted the namespace, you can manage it independently of the process lifecycle. You can enter this persistent namespace using nsenter at any time to inspect state, reconfigure virtual interfaces, or execute new processes.

To decommission the namespace, you must explicitly remove the pin by unmounting the file:

umount /var/run/netns/my_namespace

Once unmounted, if no processes remain within that namespace, the kernel will immediately reclaim the resources, completing the lifecycle. This mechanism is the bedrock for tools that require persistent network topologies that survive application crashes or restarts.

Key Takeaway: By bind-mounting a namespace entry from /proc to a file on the filesystem, you decouple the namespace's existence from the lifetime of its child processes.