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.
2
Answers
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 indocker 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 mymain.py
andDockerfile
files are located, I changed my above to:The
/src/output
is a folder structure within the container wheremy_text_file.txt
is created, so in the Python, you should be saving the file using:The
${PWD}
is where themy_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.A bind mount is the way to go and your
-v $PWD:/app
should work.If you run a command like
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.