In modern DevOps, immutability is a cornerstone of both security and reliability. Docker makes it straightforward to enforce immutability by mounting the container’s root file system as read‑only. This prevents any runtime modification—accidental or malicious—of the files baked into the image.
This lab‐style guide shows you how to:
Build a minimal image.
Launch a container with a read‑only root.
Prove—both manually and programmatically—that it really is read‑only.
Why lock the root file system?
- Defense in depth – Attackers (or faulty scripts) can’t tamper with binaries or libraries.
- Operational consistency – Every container instance is bit‑for‑bit identical to the image.
- Stateless architecture – Ideal for workloads where state lives in external services, volumes, or databases.
Scenario
“As the company’s DevOps engineer, you must deploy containers that cannot be modified in production. Your task: configure a container with a read‑only root and verify that the restriction works.”
Objectives
- Build a Docker image for testing.
- Run the container with
--read-only.
- Validate that write attempts fail and confirm the flag via docker inspect.
1. Build a test image
Create a new directory and add the following Dockerfile:
# Use a lightweight, secure base image
FROM alpine:latest
# Create sample data to test read‑only behavior
RUN mkdir /data \
&& echo "This is a read‑only test file." > /data/test.txt
WORKDIR /data
CMD ["sh"]
Build the image:
docker build -t readonly-test .
2. Run the container in read‑only mode
Command: docker run --rm -it --read-only readonly-test
--rm
cleans up the container on exit.-it
opens an interactive shell.--read-only
mounts the root file system as read‑only.
You are now inside the container’s shell.
3. Attempt to write
Inside the container, try the following:
# Append to existing file
echo "Trying to write…" >> /data/test.txt
# Create a new file
touch /data/newfile.txt
Expected outcome
sh: can't create /data/test.txt: Read-only file system
touch: /data/newfile.txt: Read-only file system
4. Confirm programmatically
Open another terminal on the host:
# Find the running container
docker ps
# Replace <container_id> with the actual ID or name
docker inspect <container_id> | grep '"ReadonlyRootfs"'
Output:
"ReadonlyRootfs": true,
Docker’s metadata confirms the root file system is indeed read‑only.
Conclusion
By combining a minimal image with the --read-only
flag, you have created an immutable runtime environment that:
Blocks unauthorized changes.
Reduces attack surface.
Guarantees that every container matches the original image.
Add this technique to your DevOps toolkit whenever you need strict runtime integrity—whether for compliance, security hardening, or simply peace of mind.
Top comments (0)