As I know, commands in Dockerfile affects only the built image, not the container where it runs. But for me it seems that this scenario writing files to the attached volume which should be impossible, because the volume is not attached while building the image:
Dockerfile:
FROM alpine
RUN mkdir /data
RUN date > /data/timestamp
RUN echo "Content in image:" && cat /data/timestamp
docker-compose.yml:
version: "3"
services:
my-service:
build: .
image: my-image
entrypoint: cat /data/timestamp
volumes:
- my-volume:/data
other-service:
image: alpine
entrypoint: cat /data/timestamp
volumes:
- my-volume:/data
volumes:
my-volume:
Output:
$ docker-compose build --no-cache; docker-compose up
other-service uses an image, skipping
Building my-service
Step 1/4 : FROM alpine
---> e66264b98777
Step 2/4 : RUN mkdir /data
---> Running in 969f72e0e71c
Removing intermediate container 969f72e0e71c
---> 21277c5b67b6
Step 3/4 : RUN date > /data/timestamp
---> Running in 09b2e14d742a
Removing intermediate container 09b2e14d742a
---> ba94d6c58c1f
Step 4/4 : RUN echo "Directory content in image:" && cat /data/timestamp
---> Running in 985e8e48bd80
Content in image:
Fri Jul 15 11:20:14 UTC 2022
Removing intermediate container 985e8e48bd80
---> adcbeac42123
Successfully built adcbeac42123
Successfully tagged my-image:latest
Creating volume "docker-test_my-volume" with default driver
Creating docker-test_other-service_1 ... done
Creating docker-test_my-service_1 ... done
Attaching to docker-test_other-service_1, docker-test_my-service_1
my-service_1 | Fri Jul 15 11:20:14 UTC 2022
other-service_1 | Fri Jul 15 11:20:14 UTC 2022
docker-test_other-service_1 exited with code 0
docker-test_my-service_1 exited with code 0
The other-service should be not able to read the contents of /data/timestamp, because it's using a different image (alpine) and the file exists only in my-image, not in the volume. How is it possible that the file exists on the volume? It seems that nothing changes if I add VOLUME /data instead of RUN mkdir /data to Dockerfile, what should I expect from this command?