Search code examples
pythondockerdocker-volume

how to save a file outside the docker container with python


So I have this structure:

myapp

  • Dockerfile
  • main.py
  • req.txt

this is the content of my Dockerfile:

FROM python:3.8
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY . /app
WORKDIR /app
RUN pip3 install -r req.txt
RUN playwright install
RUN playwright install-deps

CMD ["python", "./main.py"]

and on my main.py, eventually, I have this code

 current_path = os.path.dirname(os.path.abspath(__file__))
 result_path = os.path.join(current_path, 'result.json')

 with open(result_path, 'w') as json_file:
    json.dump(result, json_file, indent=4)

I can see that the script is running successfully, but I can't see the file that was supposed to be created in the same folder, I understand that the file is being created at

/app/results.json

but there's a way for this file to be created outside the container?

EDIT: I have done my build with:

docker build -t myapp .

and I run like this:

docker run myapp

Solution

  • So far so good, the way you are running app is perfectly alright.

    So in Docker to save files on host's file system theres is a concept called mounting the volume from which file or directory of host can be directly mounted to your running container.

    So right now I do not know where you want that file to be written on host. but the general command will be like this:

    docker run -v app:/app -it myapp

    This mounts app folder of your host to app folder in the container

    More read on the same topic: https://docs.docker.com/storage/bind-mounts/

    Hope this helps. Thanks.