How to Use Read-Only Filesystem in Docker Containers
To use a
read-only filesystem in Docker, add the --read-only flag when running a container with docker run. This makes the container's root filesystem read-only, preventing any write operations inside the container.Syntax
The --read-only flag is used with docker run to make the container's root filesystem read-only. You can also add writable volumes or tmpfs mounts if your application needs to write data.
docker run --read-only [OPTIONS] IMAGE [COMMAND]--read-only: Makes the container's root filesystem read-only.-v / --volume: Mount writable directories if needed.--tmpfs: Mount temporary writable filesystems in memory.
bash
docker run --read-only [OPTIONS] IMAGE [COMMAND]
Example
This example runs an alpine container with a read-only filesystem. It tries to create a file inside the container, which fails because the filesystem is read-only. Then it mounts a writable volume to allow file creation.
bash
docker run --rm --read-only alpine sh -c "touch /testfile || echo 'Cannot write to root filesystem'" docker run --rm --read-only -v $(pwd)/data:/data alpine sh -c "touch /data/testfile && echo 'File created in /data'"
Output
Cannot write to root filesystem
File created in /data
Common Pitfalls
Common mistakes when using --read-only include:
- Not providing writable volumes or tmpfs mounts for directories where the app needs to write (like
/tmpor logs). - Expecting the container to write to the root filesystem, which will fail silently or cause errors.
- Forgetting to clean up or prepare writable mounts before running the container.
Always check your app's write needs and provide writable mounts accordingly.
bash
docker run --rm --read-only alpine sh -c "echo 'test' > /tmp/testfile" # This will fail because /tmp is read-only docker run --rm --read-only --tmpfs /tmp alpine sh -c "echo 'test' > /tmp/testfile && cat /tmp/testfile" # This works because /tmp is writable via tmpfs
Output
sh: can't create /tmp/testfile: Read-only file system
test
Quick Reference
Summary tips for using read-only filesystem in Docker:
- Use
--read-onlyto protect the container root filesystem. - Mount writable volumes with
-vfor persistent writable data. - Use
--tmpfsfor temporary writable directories like/tmp. - Test your container to ensure it does not fail due to write restrictions.
Key Takeaways
Use the --read-only flag with docker run to make the container filesystem read-only.
Provide writable volumes or tmpfs mounts for directories your app needs to write to.
Without writable mounts, write operations inside the container will fail.
Test containers carefully to avoid runtime errors due to read-only restrictions.
Read-only filesystems improve container security by preventing unwanted changes.