dockerdockerfile

Writing VOLUME in Dockerfile


I have to instructions for dockerfile

FROM ubuntu:22.04
RUN echo Hello world! >> /internal_volume/file.txt
VOLUME /internal_volume

and

FROM ubuntu:22.04
VOLUME /internal_volume
RUN echo Hello world! >> /internal_volume/file.txt 

Which of them is preferred and why? Where should we place VOLUME instruction in the beginning or in the end?


Solution

  • Depending on the tooling, this second version may not work:

    FROM ubuntu:22.04
    VOLUME /internal_volume
    RUN echo Hello world! >> /internal_volume/file.txt # changes may be lost
    

    Docker's original build tooling would run the RUN step in a container with an anonymous volume defined. The changes would not apply to the image layers and the anonymous volume would be discarded by the builder.

    Here's the warning in the Dockerfile documentation:

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