I can't add a file after mounting

Hello!
After starting the container, I don’t have the file I need on the local volume that I mounted to the container.

Dockerfile:

VOLUME /var/www/localhost/htdocs

RUN echo "<?php phpinfo(); ?>" > /var/www/localhost/htdocs/index.php

I have tried the ADD, COPY commands with no result. If I don’t specify a location to store the volume on local storage, then the file appears.

Which Docker Desktop version and which Docker version?

I remember I had something similar years ago and I could not say what exactly it was or whether I made a mistake which I did not realize then, but I think it mattered where I added the VOLUME instruction and somehow the data was written to the image filesystem which was then overwritten by the volume definition. It would not make sense and I could not reproduce it today, but the version of your Docker Desktop and Docker could be important.

And one mor ething. How exactly do you test the existense of the file? Can you share commands to reproduce the issue?

If you define a VOLUME in a Dockerfile, the container is expected to mount a volume. If the container does not configure a volume mapping for that container path, an anonymous volume (appears as a random alphanum character name in docker volume ls) will be created and used.

If you bind a host path into the container path, then the original content of the container path will be eclipsed by the content of the host path mapped into the container path. Thus, no file that came from the image will be visible/accessible in the container.

Named volumes and anonymous volumes on the other hand copy existing data from the container path, back into the volume before it gets mounted at the container path. Of course the volume eclipses the container path as well, but since the pre-existing data was copied back into the volume, the files will be in the volume. Though, this copy back mechanism only works once, when the volume was empty.