How do you mount a volume or folder as read-only in a container?
Add :ro to the -v option, or readonly in --mount. The container can then read the files but any write attempt fails. This protects config files and source mounts from accidental changes.
Explain it simply
A reference book in the library can be read but not written in. A read-only mount works the same way for a folder.
Use it when the container only needs to consume data: a config file, TLS certificates, or static website files served by nginx. If the app or a hacker tries to modify them, the write fails with 'read-only file system'. The restriction applies only to that mount; the host can still change the files, and a read-write mount of the same folder elsewhere could modify them. You can go further and make the container's whole root filesystem read-only with --read-only, adding writable tmpfs paths where needed.
Example
docker run -d -v "$(pwd)/site":/usr/share/nginx/html:ro nginx
docker run -d --mount type=bind,source="$(pwd)/nginx.conf",target=/etc/nginx/nginx.conf,readonly nginx
docker exec <id> touch /usr/share/nginx/html/x # fails: read-onlyWhat to say in the interview
"I append :ro to -v, or use readonly in --mount, when the container only needs to read the data, such as config files, certificates or static content. It prevents accidental or malicious writes."
Common mistakes
- Forgetting that the host side stays writable, so another process can still change the files.