0
FROM ubuntu:latest
VOLUME /myVol
RUN echo "Hello World" > /myVol/message.txt
CMD cat /myVol/message.txt

When I run the container (after a successful image build), I get "Container cannot find file in volume- "No such file or directory". When I open an interactive session to the container, I see the volume, but no file (from the RUN echo..) in it. Why?

  • How is this volume set up? – GabeRAMturn Oct 09 '22 at 20:15
  • Host is an Ubuntu VM - since its a Dockerfile, I understand we can create volumes using the `VOLUME` instruction, which will build an image that will create the volume when you start a container. I see the volume is created, but no file in it. – Shyam Gupta Oct 09 '22 at 20:18
  • Does this answer your question? [Understanding "VOLUME" instruction in DockerFile](https://stackoverflow.com/questions/41935435/understanding-volume-instruction-in-dockerfile) – GabeRAMturn Oct 09 '22 at 20:23
  • I am new to Docker, I did go through the above article, but I dont think it does. In a Dockerfile , how do I create a volume and post that save the output of RUN command in that volume ? – Shyam Gupta Oct 09 '22 at 20:31
  • VOLUME takes two arguments. You only provided one. – GabeRAMturn Oct 09 '22 at 21:16
  • No, in the Dockerfile, it only takes one. – Shyam Gupta Oct 09 '22 at 21:17

1 Answers1

0

The most visible effect of VOLUME is to prevent any subsequent RUN command from modifying the VOLUME directory; this is mentioned under "Notes about specifying volumes" in the linked documentation.

For most purposes, you don't need VOLUME. In particular you do not need to declare a directory a VOLUME in the Dockerfile just because you expect an operator will eventually mount something there; when a container is run Docker volumes and host directories can be mounted on any container path regardless of whether or not it's a VOLUME.

You should be able to safely delete the VOLUME line with no consequences, and the file you're creating will actually exist.

David Maze
  • 130,717
  • 29
  • 175
  • 215
  • Other visible effects include leaking anonymous volumes in `docker volume ls` output, and in the unusual event you try to `docker commit` a container, it will not include content in a `VOLUME` directory. Some of the reasons it's hard to create a database image with preloaded data are specifically because their data directories are declared as `VOLUME`s. – David Maze Oct 09 '22 at 23:56
  • Thank you David, that explains why the file doesn't exist. So the recommended approach is to mount any volumes while spinning up containers? – Shyam Gupta Oct 10 '22 at 03:45
  • The approach I'd recommend is to not use any volumes at all, if that's a choice. If your application does need persistent state and you can't keep it somewhere outside the container (like in a database) then you should mount whatever storage when you need when you run the container. – David Maze Oct 10 '22 at 09:43