You cannot modify files inside a volume with a dockerfile

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the containerization category.

Last Updated: 2024-04-18

When I was building atop the WordPress docker base image, my changes (e.g. composer install) from a prior step in a Dockerfile kept disappearing at the next step. This was because the base Wordpress image declared VOLUME /var/www/html (Aside: this folder is the apache document root)

This also happened to be the subfolder into which I wanted to make changes (i.e. by calling composer install in /var/www/html/wp-content/plugins/x)

What was up? Here is a simple demonstration:

FROM alpine:3

VOLUME /myvol
RUN echo 'Hello World' >> /myvol/hello
RUN cat /myvol/hello
# cat: can't open '/myvol/hello': No such file or directory

Here's the key insight:

"If any build steps change the data within the volume after it has been declared, those changes will be discarded."

What do do instead?

Option 1: Write the file first declare a volume afterwards

FROM ubuntu:16.04

RUN mkdir /myvol
RUN echo 'Hello World' >> /myvol/hello
VOLUME /myvol

Option 2: Write to a different folder, one that is not in the volume of the base image. Programmer S on Project P ended up doing this as a workaround for the WordPress container thing.

Resources