skip to Main Content

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

3

Answers


  1. Use bind mount at docker run:

    docker run -v /path/to/host_app_dir:/app  myapp
    

    This will bind two directories: the /path/to/host_app_dir in your host system and the /app folder inside docker. Any file written to /app will appear in /path/to/host_app_dir. They are essentially the same folder on your hard disk. That is the magic of bind mount.

    Be careful, because you copy something into the /app folder (COPY . /app) during docker build. The content of /app will be replaced by the content of your host folder using the bind mount option above. See the documentation.

    I suggest that you use a different folder instead of /app to share files between the host and container.

    Login or Signup to reply.
  2. You need to mount bind a folder on your machine to a folder inside the container with the-v option.
    Files created inside this folder are then outside of the container.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search