Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 527 of 8028. Security and ObservabilityFree lesson

Enforcing Immutable Root Filesystems in Containers

Learners will configure container security contexts to prevent unauthorized modifications to the application filesystem at runtime.

In this lesson, you will learn how to harden your containers by configuring a read-only root filesystem to prevent malicious actors from modifying your application code at runtime.

The Concept of Immutability

By default, containers allow processes to write files anywhere in the root filesystem. While useful for debugging, this creates a significant security risk: if an attacker gains control of your application, they can install backdoors, modify binaries, or tamper with configuration files. By enforcing an immutable root filesystem, we restrict the container to a read-only state. Any attempt by a process to modify the core filesystem will be blocked by the kernel, effectively neutralizing many common post-exploitation techniques.

Implementing Read-Only Filesystems

In Kubernetes, you enforce this at the Pod level using the securityContext. When you set readOnlyRootFilesystem: true, the container’s root directory is mounted as read-only.

Here is how you apply it in your deployment manifest:

spec:
  containers:
  - name: secure-app
    image: my-app:latest
    securityContext:
      readOnlyRootFilesystem: true
      allowPrivilegeEscalation: false

Handling Required Writes

Often, applications need to write to specific directories (like /tmp or log folders) to function correctly. Since the entire root is now read-only, you must explicitly provide writable storage for those specific paths using Kubernetes emptyDir volumes:

    volumeMounts:
    - name: tmp-storage
      mountPath: /tmp
  volumes:
  - name: tmp-storage
    emptyDir: {}

By combining readOnlyRootFilesystem: true with targeted emptyDir mounts, you achieve a "Zero Trust" approach to your container's local storage. This ensures your application stays exactly as it was built, significantly reducing the attack surface by preventing runtime tampering. Even if an attacker executes code, they will find themselves in a "trapped" environment with no ability to persist changes or write malicious files to disk.

Key Takeaway: Setting readOnlyRootFilesystem: true in your container security context is a powerful defense-in-depth measure that prevents attackers from modifying your application binaries or injecting persistent malware at runtime.