Home > Enterprise >  Create a file outside of Docker container while container is running in Python
Create a file outside of Docker container while container is running in Python

Time:01-10

I currently have a Python application running in a Docker container on Ubuntu 20.04.

In this Python application I want to create a text file every few minutes for use in other applications on the Ubuntu server. However, I am finding it challenging to create a file and save it on the server from inside a containerised Python application.

The application Dockerfile/start.sh/main.py files reside in /var/www/my_app_name/ and I would like to have the output.txt file that main.py creates in that same folder, the location of the Dockerfile/main.py source.

The text file is created in Python using a simple line:

text_file = open("my_text_file.txt", "wt")

I have seen that the best way to do this is to use a volume. My current docker run which is called by batch script start.sh includes the line:

docker run -d --name=${app} -v $PWD:/app ${app}

However I am not having much luck and the file is not created in the working directory where main.py resides.

CodePudding user response:

A bind mount is the way to go and your -v $PWD:/app should work.

If you run a command like

docker run --rm -v $PWD:/app alpine /bin/sh -c 'echo Hello > /app/hello.txt'

you'll get a file in your current directory called hello.txt.

The command runs an Alpine image, maps the current directory to /app in the container and then echoes 'Hello' to /app/hello.txt in the container.

CodePudding user response:

Ended up solving this myself, thanks to those who answered to get me on the right path.

For those finding this question in the future, creating a bind mound using the -v flag in docker run is indeed the correct way to go, just ensure that you have the correct path.

To get the file my_text_file.txt in the folder where my main.py and Dockerfile files are located, I changed my above to:

-v $PWD:/src/output ${app}

The /src/output is a folder structure within the container where my_text_file.txt is created, so in the Python, you should be saving the file using:

text_file = open("/src/output/my_text_file.txt", "wt")

The ${PWD} is where the my_text_file.txt is located on the local machine.

In short, I was not saving my file to the correct folder within the container in the Python code, it should have been saved to app in the container, and then my solution in the OP would have worked.

  • Related