Skip to content
shellhacks.dev
Docker

Mount read-only

Mount a host directory read-only into a container with -v "$PWD":/data:ro. A write from inside fails with a read-only file system error, even as root.

1 min read
Summarize in AI

A container needs to read your files, such as a config or a source tree, and it should not be able to change them.

Shell
mkdir data && echo hello > data/note.txt
docker run --rm -v "$PWD/data":/data:ro alpine:3.20 sh -c 'cat /data/note.txt; touch /data/new.txt'
echo "exit: $?"
ls data
Text
hello
touch: /data/new.txt: Read-only file system
exit: 1
note.txt

The :ro suffix makes the bind mount read-only inside the container, so the kernel refuses any write, create or delete on it, including from root. The syntax is documented under bind mounts. The listing at the end shows that no file was created on the host.

Only that one mount is read-only: the rest of the container's file system is still writable unless you add --read-only. A read-only bind mount also does not stop writes through a second, writable mount of the same directory. Use --mount type=bind,src=...,dst=...,readonly when you prefer named keys.

Share

More snippets

Docker

Run a throwaway container

Run a container once and remove it on exit with docker run --rm. Without the flag every run leaves a stopped container behind, one per invocation.

1 min read
Docker

Set environment variables

Set an environment variable in a container with docker run -e NAME=value. Pass -e NAME with no value to copy the value from the calling shell.

1 min read
Docker

Load environment from a file

Load variables from a file with docker run --env-file. The file is not parsed by a shell, so quotes stay in the value and a line with export fails.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.