Can you force a Dockerfile to write to a volume?

I’m attempting to get a Dockerfile to write directly to a volume, instead of to the intermediate container’s file system.

Tried by creating the named volume:

docker volume create --name ..

The using it in the docker-compose

services:
  flask:
    ...
    volumes:
     - <volume_name>:/opt/foodtrucks/project/flask-app

volumes:
    <volume_name>:
     external: true

when the Dockerfile writes to the mounted location:

COPY --from=builder .... /opt/foodtrucks/project/flask-app

Why is this not working? the image doesn’t get smaller which suggests to me that the files are still copied to the image’s file system…

It might be possible with BuildKit frontend syntax. Though, I have never used it and as such have no experience that I could share. Judged by the documentation, something like might do the trick:

# syntax=docker/dockerfile:1.3
FROM {baseimage}
RUN --mount=type=bind,source=/host/path,target=/container/path \
  {your command 1} && \
  {your command 2} && \
  ... && \
  {your command n}

The scope of the mount will be limited to the RUN instruction. You would need to use it on each RUN instruction that should use the mount.

Please open and read the link from above, as there are different types of --mount=type available and you propbably might need to add another parameter or even require a different type than used above.

1 Like