0
0
Dockerdevops~5 mins

Mounting read-only volumes in Docker - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to share files or folders with a container but prevent the container from changing them. Mounting a volume as read-only lets the container use the files without risking accidental changes.
When you want to share configuration files with a container but keep them safe from modification.
When you run a container that needs to read data files but should not write or delete them.
When multiple containers share the same data but only one container should be allowed to modify it.
When you want to protect important scripts or binaries inside a container from being changed.
When you want to debug or inspect files inside a container without risking changes.
Commands
This command runs an Nginx container named 'my-nginx'. It mounts the host folder '/usr/share/nginx/html' into the container as a read-only volume using ':ro'. The container listens on port 80, mapped to host port 8080.
Terminal
docker run -d --name my-nginx -v /usr/share/nginx/html:/usr/share/nginx/html:ro -p 8080:80 nginx:1.23.3
Expected OutputExpected
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6
-v - Mounts a volume from host to container
:ro - Makes the mounted volume read-only inside the container
-p - Maps container port to host port
This command lists the files inside the mounted folder in the running container to verify the volume is mounted correctly and accessible.
Terminal
docker exec my-nginx ls -l /usr/share/nginx/html
Expected OutputExpected
total 4 -rw-r--r-- 1 root root 612 Apr 10 12:00 index.html
This command tries to create a new file inside the read-only mounted volume to demonstrate that write operations are blocked.
Terminal
docker exec my-nginx touch /usr/share/nginx/html/testfile
Expected OutputExpected
touch: cannot touch '/usr/share/nginx/html/testfile': Read-only file system
Key Concept

If you remember nothing else from this pattern, remember: adding ':ro' after the volume path makes the container see the volume as read-only.

Common Mistakes
Forgetting to add ':ro' after the volume path when mounting.
The volume will be mounted with default read-write permissions, allowing the container to modify files.
Always append ':ro' to the volume path to enforce read-only access.
Trying to write or create files inside a read-only mounted volume.
The container will get a 'Read-only file system' error and fail to write.
Avoid write operations on read-only volumes or mount a separate writable volume if needed.
Summary
Use the '-v' flag with ':ro' to mount a host folder as read-only inside a container.
Verify the volume is mounted by listing files inside the container.
Write operations inside a read-only volume will fail with a read-only file system error.