In this lesson, you will learn how the time namespace enables containers to maintain independent system clocks, preventing clock drift or manipulation from affecting the host or other containers.
The Problem with Shared Time
By default, all processes on a Linux system share a single global notion of time (both CLOCK_REALTIME, which tracks wall-clock time, and CLOCK_MONOTONIC, which tracks time elapsed since boot). In containerized environments, this creates a security and operational challenge: a container might need to be live-migrated to a new host, or it might require a specific "start time" for testing purposes. Without isolation, an unprivileged container cannot adjust the system clock without impacting the host’s global settings.
Virtualizing the Clock
A time namespace provides a virtualized view of CLOCK_MONOTONIC and CLOCK_BOOTTIME for processes within that namespace. When you create a new time namespace, the kernel allows you to set an offset. Any process inside this namespace that queries the clock will receive the host's actual time plus your defined offset.
Crucially, this is a per-namespace offset. If you freeze a container using CRIU (Checkpoint and Restore in Userspace), you can capture the precise time state. When restoring the container on a different machine, the kernel applies the stored offsets so the container perceives time as continuous, even if the actual physical wall clock on the new host differs significantly.
Implementation Concept
You interact with time namespaces by manipulating the /proc/self/timens_offsets file. Before a process calls unshare(CLONE_NEWTIME), it can write to this file to define how far "ahead" or "behind" its clock should be relative to the host:
# Example format in /proc/self/timens_offsets:
# <clock-id> <offset-seconds> <offset-nanoseconds>
echo "monotonic 100 0" > /proc/self/timens_offsets
Once applied, clock_gettime(CLOCK_MONOTONIC) within that namespace will return a value shifted by 100 seconds. This allows applications to simulate specific time environments or handle container migration without the kernel's global clock state leaking into or out of the container’s isolated domain.
Key Takeaway: The time namespace virtualizes monotonic clocks by applying specific offsets per namespace, allowing containers to maintain consistent time perceptions during migration or simulation without requiring host-level clock modifications.