Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 148 of 8022. Docker Image LifecycleFree lesson

Hardening Container Filesystems with Read-Only Mounts

Apply security best practices by configuring containers to run with read-only filesystems, preventing unauthorized modifications to the application environment at runtime.

In this lesson, you will learn how to lock down your container’s filesystem to prevent unauthorized runtime modifications, significantly limiting the impact of potential security breaches.

Why Read-Only Filesystems?

By default, Docker containers allow processes to write anywhere in the filesystem. This is a security risk: if an attacker gains control of your application, they might try to modify existing binaries, inject malicious scripts, or install persistent tools.

A "Read-Only" filesystem (often called read-only rootfs) forces the container’s filesystem into a state where no changes can be persisted. If an attacker manages to execute code, they cannot overwrite system files, modify configuration files, or drop malware, because the OS will reject any write attempts.

How to Implement It

You can enforce this behavior at runtime using the --read-only flag in Docker or via the securityContext in Kubernetes.

In Docker: Simply add the flag to your docker run command:

docker run --read-only my-secure-app:latest

In Kubernetes: Define it within your Pod manifest:

spec:
  containers:
  - name: my-app
    securityContext:
      readOnlyRootFilesystem: true

Handling Necessary Writes

Real-world applications often need some place to write data, such as logs, temporary files, or cache directories. When you set the filesystem to read-only, you must explicitly mount specific directories as temporary volumes (tmpfs) to allow writing.

For example, if your app needs to write to /tmp, you can map a memory-based volume to that path:

# Kubernetes example
volumeMounts:
- name: tmp-volume
  mountPath: /tmp
volumes:
- name: tmp-volume
  emptyDir:
    medium: Memory

By restricting write access to only the bare essentials—and keeping everything else locked down—you effectively stop entire classes of attacks that rely on modifying the container environment. It turns your container from a dynamic playground for intruders into a rigid, immutable artifact that only does exactly what you programmed it to do.

Key Takeaway: Setting your container’s filesystem to read-only is a powerful security defense that ensures your application remains immutable and resistant to unauthorized tampering at runtime.