WittCode💻

Docker Readonly and Read/Write Volumes

By

Learn how to create a Docker container with read/write and read only volumes. We will also learn the differences between read/write and read only volumes with a demonstration.

Table of Contents 📖

Read Write Volumes

By default, Docker volumes are read write. This means that if we change a file inside the Docker container it will be reflected on the host machine and vice versa. To demonstrate, lets create a Nginx Docker container with a volume to the index.html file.

docker run --name nginx-c -p 6464:80 -v ./index.html:/usr/share/nginx/html/index.html nginx
<h1>WittCepter is the best Chrome Extension!</h1>

INFO: By default the Nginx Docker container serves up static content from the /usr/share/nginx/html directory on port 80.

If we then send a request to Nginx, we will get this HTML file returned.

curl localhost:6464
<h1>WittCepter is the best Chrome Extension!</h1>

Now if we edit this HTML file and re-request it, the changes will have been reflected in the Docker container.

<h1>This is an edit from the host computer!</h1>
curl localhost:6464
<h1>This is an edit from the host computer!</h1>

However, if we also change the file from inside the Docker container, this will be reflected on the host.

docker exec -it nginx-c sh
echo "<h1>Edit from inside Docker Container</h1>" > /usr/share/nginx/html/index.html

Now, if we check the contents of index.html on our host computer, we can see that it has changed aswell!

<h1>Edit from inside Docker Container</h1>

This is because, by default, Docker volumes are read write. This means that what happens in the Docker container also happens to the host machine.

Read Only Volumes

However, there are times where we only want the container to read the data in the volume. We can do this by specifying the Docker volume as readonly.

docker run --name nginx-c -p 6464:80 -v ./index.html:/usr/share/nginx/html/index.html:ro nginx

INFO: We can specify a Docker volume as read only by specifying the :ro at the end of the volume.

Now lets edit the index.html file on our host machine.

<h1>WittCepter analyzes browser network traffic!</h1>
curl localhost:6464
<h1>WittCepter analyzes browser network traffic!</h1>

As expected, the changes are reflected in the container. However, as the volume is now readonly, we should not be allowed to edit the index.html file from inside the Docker container.

docker exec -it nginx-c sh
echo "<h1>Edit from inside Docker Container</h1>" > /usr/share/nginx/html/index.html
sh: 1: cannot create /usr/share/nginx/html/index.html: Read-only file system

If we check the console, we can see that we are unable to edit a read-only file system.